file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IVaultManager { function controllers(address) external view returns (bool); function getHarvestFeeInfo() external view returns (address, address, uint256, address, uint256, address, uint256); function governance() external view returns (address); function harvester() external view returns (address); function insuranceFee() external view returns (uint256); function insurancePool() external view returns (address); function insurancePoolFee() external view returns (uint256); function stakingPool() external view returns (address); function stakingPoolShareFee() external view returns (uint256); function strategist() external view returns (address); function treasury() external view returns (address); function treasuryBalance() external view returns (uint256); function treasuryFee() external view returns (uint256); function vaults(address) external view returns (bool); function withdrawalProtectionFee() external view returns (uint256); function yax() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./IVaultManager.sol"; /** * @title yAxisMetaVaultManager * @notice This contract serves as the central point for governance-voted * variables. Fees and permissioned addresses are stored and referenced in * this contract only. */ contract yAxisMetaVaultManager is IVaultManager { // solhint-disable-line contract-name-camelcase address public override governance; address public override harvester; address public override insurancePool; address public override stakingPool; address public override strategist; address public override treasury; address public override yax; /** * The following fees are all mutable. * They are updated by governance (community vote). */ uint256 public override insuranceFee; uint256 public override insurancePoolFee; uint256 public override stakingPoolShareFee; uint256 public override treasuryBalance; uint256 public override treasuryFee; uint256 public override withdrawalProtectionFee; mapping(address => bool) public override vaults; mapping(address => bool) public override controllers; /** * @param _yax The address of the YAX token */ constructor(address _yax) public { yax = _yax; governance = msg.sender; strategist = msg.sender; harvester = msg.sender; stakingPoolShareFee = 2000; treasuryBalance = 20000e18; treasuryFee = 500; withdrawalProtectionFee = 10; } /** * GOVERNANCE-ONLY FUNCTIONS */ /** * @notice Allows governance to pull tokens out of this contract * (it should never hold tokens) * @param _token The address of the token * @param _amount The amount to withdraw * @param _to The address to send to */ function governanceRecoverUnsupported( IERC20 _token, uint256 _amount, address _to ) external { require(msg.sender == governance, "!governance"); _token.transfer(_to, _amount); } /** * @notice Sets the governance address * @param _governance The address of the governance */ function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } /** * @notice Sets the insurance fee * @dev Throws if setting fee over 1% * @param _insuranceFee The value for the insurance fee */ function setInsuranceFee(uint256 _insuranceFee) public { require(msg.sender == governance, "!governance"); require(_insuranceFee <= 100, "_insuranceFee over 1%"); insuranceFee = _insuranceFee; } /** * @notice Sets the insurance pool address * @param _insurancePool The address of the insurance pool */ function setInsurancePool(address _insurancePool) public { require(msg.sender == governance, "!governance"); insurancePool = _insurancePool; } /** * @notice Sets the insurance pool fee * @dev Throws if setting fee over 20% * @param _insurancePoolFee The value for the insurance pool fee */ function setInsurancePoolFee(uint256 _insurancePoolFee) public { require(msg.sender == governance, "!governance"); require(_insurancePoolFee <= 2000, "_insurancePoolFee over 20%"); insurancePoolFee = _insurancePoolFee; } /** * @notice Sets the staking pool address * @param _stakingPool The address of the staking pool */ function setStakingPool(address _stakingPool) public { require(msg.sender == governance, "!governance"); stakingPool = _stakingPool; } /** * @notice Sets the staking pool share fee * @dev Throws if setting fee over 50% * @param _stakingPoolShareFee The value for the staking pool fee */ function setStakingPoolShareFee(uint256 _stakingPoolShareFee) public { require(msg.sender == governance, "!governance"); require(_stakingPoolShareFee <= 5000, "_stakingPoolShareFee over 50%"); stakingPoolShareFee = _stakingPoolShareFee; } /** * @notice Sets the strategist address * @param _strategist The address of the strategist */ function setStrategist(address _strategist) external { require(msg.sender == governance, "!governance"); strategist = _strategist; } /** * @notice Sets the treasury address * @param _treasury The address of the treasury */ function setTreasury(address _treasury) public { require(msg.sender == governance, "!governance"); treasury = _treasury; } /** * @notice Sets the maximum treasury balance * @dev Strategies will read this value to determine whether or not * to give the treasury the treasuryFee * @param _treasuryBalance The maximum balance of the treasury */ function setTreasuryBalance(uint256 _treasuryBalance) public { require(msg.sender == governance, "!governance"); treasuryBalance = _treasuryBalance; } /** * @notice Sets the treasury fee * @dev Throws if setting fee over 20% * @param _treasuryFee The value for the treasury fee */ function setTreasuryFee(uint256 _treasuryFee) public { require(msg.sender == governance, "!governance"); require(_treasuryFee <= 2000, "_treasuryFee over 20%"); treasuryFee = _treasuryFee; } /** * @notice Sets the withdrawal protection fee * @dev Throws if setting fee over 1% * @param _withdrawalProtectionFee The value for the withdrawal protection fee */ function setWithdrawalProtectionFee(uint256 _withdrawalProtectionFee) public { require(msg.sender == governance, "!governance"); require(_withdrawalProtectionFee <= 100, "_withdrawalProtectionFee over 1%"); withdrawalProtectionFee = _withdrawalProtectionFee; } /** * @notice Sets the YAX address * @param _yax The address of the YAX token */ function setYax(address _yax) external { require(msg.sender == governance, "!governance"); yax = _yax; } /** * (GOVERNANCE|STRATEGIST)-ONLY FUNCTIONS */ /** * @notice Sets the status for a controller * @param _controller The address of the controller * @param _status The status of the controller */ function setControllerStatus(address _controller, bool _status) external { require(msg.sender == strategist || msg.sender == governance, "!strategist"); controllers[_controller] = _status; } /** * @notice Sets the harvester address * @param _harvester The address of the harvester */ function setHarvester(address _harvester) external { require(msg.sender == strategist || msg.sender == governance, "!strategist"); harvester = _harvester; } /** * @notice Sets the status for a vault * @param _vault The address of the vault * @param _status The status of the vault */ function setVaultStatus(address _vault, bool _status) external { require(msg.sender == strategist || msg.sender == governance, "!strategist"); vaults[_vault] = _status; } /** * EXTERNAL VIEW FUNCTIONS */ /** * @notice Returns a tuple of: * YAX token, * Staking pool address, * Staking pool share fee, * Treasury address, * Checks the balance of the treasury and returns the treasury fee * if below the treasuryBalance, or 0 if above */ function getHarvestFeeInfo() external view override returns (address, address, uint256, address, uint256, address, uint256) { return ( yax, stakingPool, stakingPoolShareFee, treasury, IERC20(yax).balanceOf(treasury) >= treasuryBalance ? 0 : treasuryFee, insurancePool, insurancePoolFee ); } }
Sets the strategist address _strategist The address of the strategist/
function setStrategist(address _strategist) external { require(msg.sender == governance, "!governance"); strategist = _strategist; }
10,063,153
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\ERC20Basic.sol pragma solidity ^0.4.21; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: node_modules\openzeppelin-solidity\contracts\token\ERC20\ERC20.sol pragma solidity ^0.4.21; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: node_modules\openzeppelin-solidity\contracts\token\ERC20\SafeERC20.sol pragma solidity ^0.4.21; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } // File: node_modules\openzeppelin-solidity\contracts\math\SafeMath.sol pragma solidity ^0.4.21; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: node_modules\openzeppelin-solidity\contracts\token\ERC20\BasicToken.sol pragma solidity ^0.4.21; /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); 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 view returns (uint256) { return balances[_owner]; } } // File: node_modules\openzeppelin-solidity\contracts\token\ERC20\StandardToken.sol pragma solidity ^0.4.21; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); 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'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 view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721Basic.sol pragma solidity ^0.4.21; /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } // File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721Receiver.sol pragma solidity ^0.4.21; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. This function MUST use 50,000 gas or less. Return of other * than the magic value MUST result in the transaction being reverted. * Note: the contract address is always the message sender. * @param _from The sending address * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` */ function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4); } // File: node_modules\openzeppelin-solidity\contracts\AddressUtils.sol pragma solidity ^0.4.21; /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly return size > 0; } } // File: node_modules\openzeppelin-solidity\contracts\token\ERC721\ERC721BasicToken.sol pragma solidity ^0.4.21; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC721Basic { using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existance of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * @dev The zero address indicates there is no approved address. * @dev There can only be one approved address per token at a given time. * @dev Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); if (getApproved(_tokenId) != address(0) || _to != address(0)) { tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for a the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * @dev An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * @dev If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @dev Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) { address owner = ownerOf(_tokenId); return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender); } /** * @dev Internal function to mint a new token * @dev Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * @dev Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * @dev Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); emit Approval(_owner, address(0), _tokenId); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * @dev The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } // File: contracts\Strings.sol pragma solidity ^0.4.23; library Strings { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint i) internal pure returns (string) { if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } } // File: contracts\DefinerBasicLoan.sol pragma solidity ^0.4.23; interface ERC721Metadata /* is ERC721 */ { /// @notice A descriptive name for a collection of NFTs in this contract function name() external view returns (string _name); /// @notice An abbreviated name for NFTs in this contract function symbol() external view returns (string _symbol); /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view returns (string); } contract DefinerBasicLoan is ERC721BasicToken, ERC721Metadata { using SafeERC20 for ERC20; using SafeMath for uint; enum States { Init, //0 WaitingForLender, //1 WaitingForBorrower, //2 WaitingForCollateral, //3 WaitingForFunds, //4 Funded, //5 Finished, //6 Closed, //7 Default, //8 Cancelled //9 } address public ownerAddress; address public borrowerAddress; address public lenderAddress; string public loanId; uint public endTime; // use to check default uint public nextPaymentDateTime; // use to check default uint public daysPerInstallment; // use to calculate next payment date uint public totalLoanTerm; // in days uint public borrowAmount; // total borrowed amount uint public collateralAmount; // total collateral amount uint public installmentAmount; // amount of each installment uint public remainingInstallment; // total installment left States public currentState = States.Init; /** * TODO: change address below to actual factory address after deployment * address constant private factoryContract = 0x... */ address internal factoryContract; // = 0x38Bddc3793DbFb3dE178E3dE74cae2E223c02B85; modifier onlyFactoryContract() { require(factoryContract == 0 || msg.sender == factoryContract, "not factory contract"); _; } modifier atState(States state) { require(state == currentState, "Invalid State"); _; } modifier onlyOwner() { require(msg.sender == ownerAddress, "Invalid Owner Address"); _; } modifier onlyLender() { require(msg.sender == lenderAddress || msg.sender == factoryContract, "Invalid Lender Address"); _; } modifier onlyBorrower() { require(msg.sender == borrowerAddress || msg.sender == factoryContract, "Invalid Borrower Address"); _; } modifier notDefault() { require(now < nextPaymentDateTime, "This Contract has not yet default"); require(now < endTime, "This Contract has not yet default"); _; } /** * ERC721 Interface */ function name() public view returns (string _name) { return "DeFiner Contract"; } function symbol() public view returns (string _symbol) { return "DFINC"; } function tokenURI(uint256) public view returns (string) { return Strings.strConcat( "https://api.definer.org/OKh4I2yYpKU8S2af/definer/api/v1.0/opensea/", loanId ); } function transferFrom(address _from, address _to, uint256 _tokenId) public { require(_from != address(0)); require(_to != address(0)); super.transferFrom(_from, _to, _tokenId); lenderAddress = tokenOwner[_tokenId]; } function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); lenderAddress = tokenOwner[_tokenId]; } function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); lenderAddress = tokenOwner[_tokenId]; } /** * Borrower transfer ETH to contract */ function transferCollateral() public payable /*atState(States.WaitingForCollateral)*/; /** * Check if borrower transferred correct amount of Token */ function checkCollateral() public /*atState(States.WaitingForCollateral)*/; /** * Borrower cancel the transaction is Default */ function borrowerCancel() public /*onlyLender atState(States.WaitingForLender)*/; /** * Lender cancel the transaction is Default */ function lenderCancel() public /*onlyLender atState(States.WaitingForBorrower)*/; /** * Lender transfer ETH to contract */ function transferFunds() public payable /*atState(States.WaitingForFunds)*/; /** * Check if lender transferred correct amount of Token */ function checkFunds() public /*atState(States.WaitingForFunds)*/; /** * Borrower pay back ETH or Token */ function borrowerMakePayment() public payable /*onlyBorrower atState(States.Funded) notDefault*/; /** * Borrower gets collateral back */ function borrowerReclaimCollateral() public /*onlyBorrower atState(States.Finished)*/; /** * Lender gets collateral when contract state is Default */ function lenderReclaimCollateral() public /*onlyLender atState(States.Default)*/; /** * Borrower accept loan */ function borrowerAcceptLoan() public atState(States.WaitingForBorrower) { require(msg.sender != address(0), "Invalid address."); borrowerAddress = msg.sender; currentState = States.WaitingForCollateral; } /** * Lender accept loan */ function lenderAcceptLoan() public atState(States.WaitingForLender) { require(msg.sender != address(0), "Invalid address."); lenderAddress = msg.sender; currentState = States.WaitingForFunds; } function transferETHToBorrowerAndStartLoan() internal { borrowerAddress.transfer(borrowAmount); endTime = now.add(totalLoanTerm.mul(1 days)); nextPaymentDateTime = now.add(daysPerInstallment.mul(1 days)); currentState = States.Funded; } function transferTokenToBorrowerAndStartLoan(StandardToken token) internal { require(token.transfer(borrowerAddress, borrowAmount), "Token transfer failed"); endTime = now.add(totalLoanTerm.mul(1 days)); nextPaymentDateTime = now.add(daysPerInstallment.mul(1 days)); currentState = States.Funded; } //TODO not in use yet function checkDefault() public onlyLender atState(States.Funded) returns (bool) { if (now > endTime || now > nextPaymentDateTime) { currentState = States.Default; return true; } else { return false; } } // For testing function forceDefault() public onlyOwner { currentState = States.Default; } function getLoanDetails() public view returns (address,address,address,string,uint,uint,uint,uint,uint,uint,uint,uint,uint) { // address public ownerAddress; // address public borrowerAddress; // address public lenderAddress; // string public loanId; // uint public endTime; // use to check default // uint public nextPaymentDateTime; // use to check default // uint public daysPerInstallment; // use to calculate next payment date // uint public totalLoanTerm; // in days // uint public borrowAmount; // total borrowed amount // uint public collateralAmount; // total collateral amount // uint public installmentAmount; // amount of each installment // uint public remainingInstallment; // total installment left // States public currentState = States.Init; // // return ( // nextPaymentDateTime, // remainingInstallment, // uint(currentState), // loanId, // borrowerAddress, // lenderAddress // ); return ( ownerAddress, borrowerAddress, lenderAddress, loanId, endTime, nextPaymentDateTime, daysPerInstallment, totalLoanTerm, borrowAmount, collateralAmount, installmentAmount, remainingInstallment, uint(currentState) ); } } // File: contracts\ERC20ETHLoan.sol pragma solidity ^0.4.23; /** * Collateral: ERC20 Token * Borrowed: ETH */ contract ERC20ETHLoan is DefinerBasicLoan { StandardToken token; address public collateralTokenAddress; /** * NOT IN USE * WHEN COLLATERAL IS TOKEN, TRANSFER IS DONE IN FRONT END */ function transferCollateral() public payable { revert(); } function establishContract() public { // ERC20 as collateral uint amount = token.balanceOf(address(this)); require(amount >= collateralAmount, "Insufficient collateral amount"); // Ether as Fund require(address(this).balance >= borrowAmount, "Insufficient fund amount"); // Transit to Funded state transferETHToBorrowerAndStartLoan(); } /** * NOT IN USE * WHEN FUND IS ETH, CHECK IS DONE IN transferFunds() */ function checkFunds() onlyLender atState(States.WaitingForFunds) public { return establishContract(); } /** * Check if borrower transferred correct amount of token to this contract */ function checkCollateral() public onlyBorrower atState(States.WaitingForCollateral) { uint amount = token.balanceOf(address(this)); require(amount >= collateralAmount, "Insufficient collateral amount"); currentState = States.WaitingForLender; } /** * Lender transfer ETH to fund this contract */ function transferFunds() public payable onlyLender atState(States.WaitingForFunds) { if (address(this).balance >= borrowAmount) { establishContract(); } } /* * Borrower pay back ETH */ function borrowerMakePayment() public payable onlyBorrower atState(States.Funded) notDefault { require(msg.value >= installmentAmount); remainingInstallment--; lenderAddress.transfer(installmentAmount); if (remainingInstallment == 0) { currentState = States.Finished; } else { nextPaymentDateTime = nextPaymentDateTime.add(daysPerInstallment.mul(1 days)); } } /* * Borrower gets collateral token back when contract completed */ function borrowerReclaimCollateral() public onlyBorrower atState(States.Finished) { uint amount = token.balanceOf(address(this)); token.transfer(borrowerAddress, amount); currentState = States.Closed; } /* * Lender gets collateral token when contract defaulted */ function lenderReclaimCollateral() public onlyLender atState(States.Default) { uint amount = token.balanceOf(address(this)); token.transfer(lenderAddress, amount); currentState = States.Closed; } } // File: contracts\ERC20ETHLoanBorrower.sol pragma solidity ^0.4.23; /** * Collateral: ERC20 Token * Borrowed: ETH */ contract ERC20ETHLoanBorrower is ERC20ETHLoan { function init ( address _ownerAddress, address _borrowerAddress, address _lenderAddress, address _collateralTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId ) public onlyFactoryContract { require(_collateralTokenAddress != address(0), "Invalid token address"); require(_borrowerAddress != address(0), "Invalid lender address"); require(_lenderAddress != address(0), "Invalid lender address"); require(_remainingInstallment > 0, "Invalid number of installments"); require(_borrowAmount > 0, "Borrow amount must not be 0"); require(_paybackAmount > 0, "Payback amount must not be 0"); require(_collateralAmount > 0, "Collateral amount must not be 0"); super._mint(_lenderAddress, 1); factoryContract = msg.sender; ownerAddress = _ownerAddress; loanId = _loanId; collateralTokenAddress = _collateralTokenAddress; borrowAmount = _borrowAmount; collateralAmount = _collateralAmount; totalLoanTerm = _remainingInstallment * _daysPerInstallment; daysPerInstallment = _daysPerInstallment; remainingInstallment = _remainingInstallment; installmentAmount = _paybackAmount / _remainingInstallment; token = StandardToken(_collateralTokenAddress); borrowerAddress = _borrowerAddress; lenderAddress = _lenderAddress; // initialial state for borrower initiated ERC20 flow currentState = States.WaitingForCollateral; } /** * NOT IN USE * WHEN FUND IS ETH, CHECK IS DONE IN transferFunds() */ function checkFunds() onlyLender atState(States.WaitingForFunds) public { return establishContract(); } /** * Check if borrower transferred correct amount of token to this contract */ function checkCollateral() public onlyBorrower atState(States.WaitingForCollateral) { uint amount = token.balanceOf(address(this)); require(amount >= collateralAmount, "Insufficient collateral amount"); currentState = States.WaitingForFunds; } /** * Lender transfer ETH to fund this contract */ function transferFunds() public payable onlyLender atState(States.WaitingForFunds) { if (address(this).balance >= borrowAmount) { establishContract(); } } /* * Borrower gets collateral token back when contract completed */ function borrowerCancel() public onlyBorrower atState(States.WaitingForFunds) { uint amount = token.balanceOf(address(this)); token.transfer(borrowerAddress, amount); currentState = States.Cancelled; } /* * Lender gets funds token back when contract is cancelled */ function lenderCancel() public onlyLender atState(States.WaitingForCollateral) { // For ETH leader, no way to cancel revert(); } } // File: contracts\ERC20ETHLoanLender.sol pragma solidity ^0.4.23; /** * Collateral: ERC20 Token * Borrowed: ETH */ contract ERC20ETHLoanLender is ERC20ETHLoan { function init ( address _ownerAddress, address _borrowerAddress, address _lenderAddress, address _collateralTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId ) public onlyFactoryContract { require(_collateralTokenAddress != address(0), "Invalid token address"); require(_borrowerAddress != address(0), "Invalid lender address"); require(_lenderAddress != address(0), "Invalid lender address"); require(_remainingInstallment > 0, "Invalid number of installments"); require(_borrowAmount > 0, "Borrow amount must not be 0"); require(_paybackAmount > 0, "Payback amount must not be 0"); require(_collateralAmount > 0, "Collateral amount must not be 0"); super._mint(_lenderAddress, 1); factoryContract = msg.sender; ownerAddress = _ownerAddress; loanId = _loanId; collateralTokenAddress = _collateralTokenAddress; borrowAmount = _borrowAmount; collateralAmount = _collateralAmount; totalLoanTerm = _remainingInstallment * _daysPerInstallment; daysPerInstallment = _daysPerInstallment; remainingInstallment = _remainingInstallment; installmentAmount = _paybackAmount / _remainingInstallment; token = StandardToken(_collateralTokenAddress); borrowerAddress = _borrowerAddress; lenderAddress = _lenderAddress; // initialial state for borrower initiated ERC20 flow currentState = States.WaitingForFunds; } /** * Check if borrower transferred correct amount of token to this contract */ function checkCollateral() public onlyBorrower atState(States.WaitingForCollateral) { return establishContract(); } /** * Lender transfer ETH to fund this contract */ function transferFunds() public payable onlyLender atState(States.WaitingForFunds) { if (address(this).balance >= borrowAmount) { currentState = States.WaitingForCollateral; } } /* * Borrower gets collateral token back when contract completed */ function borrowerCancel() public onlyBorrower atState(States.WaitingForFunds) { revert(); } /* * Lender gets funds token back when contract is cancelled */ function lenderCancel() public onlyLender atState(States.WaitingForCollateral) { lenderAddress.transfer(address(this).balance); currentState = States.Cancelled; } } // File: contracts\ETHERC20Loan.sol pragma solidity ^0.4.23; /** * Collateral: ETH * Borrowed: ERC20 Token */ contract ETHERC20Loan is DefinerBasicLoan { StandardToken token; address public borrowedTokenAddress; function establishContract() public { // ERC20 as collateral uint amount = token.balanceOf(address(this)); require(amount >= collateralAmount, "Insufficient collateral amount"); // Ether as Fund require(address(this).balance >= borrowAmount, "Insufficient fund amount"); // Transit to Funded state transferETHToBorrowerAndStartLoan(); } /* * Borrower pay back ERC20 Token */ function borrowerMakePayment() public payable onlyBorrower atState(States.Funded) notDefault { require(remainingInstallment > 0, "No remaining installments"); require(installmentAmount > 0, "Installment amount must be non zero"); token.transfer(lenderAddress, installmentAmount); remainingInstallment--; if (remainingInstallment == 0) { currentState = States.Finished; } else { nextPaymentDateTime = nextPaymentDateTime.add(daysPerInstallment.mul(1 days)); } } /* * Borrower gets collateral ETH back when contract completed */ function borrowerReclaimCollateral() public onlyBorrower atState(States.Finished) { borrowerAddress.transfer(address(this).balance); currentState = States.Closed; } /* * Lender gets collateral ETH when contract defaulted */ function lenderReclaimCollateral() public onlyLender atState(States.Default) { lenderAddress.transfer(address(this).balance); currentState = States.Closed; } } // File: contracts\ETHERC20LoanBorrower.sol pragma solidity ^0.4.23; /** * Collateral: ETH * Borrowed: ERC20 Token */ contract ETHERC20LoanBorrower is ETHERC20Loan { function init ( address _ownerAddress, address _borrowerAddress, address _lenderAddress, address _borrowedTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId ) public onlyFactoryContract { require(_borrowedTokenAddress != address(0), "Invalid token address"); require(_borrowerAddress != address(0), "Invalid lender address"); require(_lenderAddress != address(0), "Invalid lender address"); require(_remainingInstallment > 0, "Invalid number of installments"); require(_borrowAmount > 0, "Borrow amount must not be 0"); require(_paybackAmount > 0, "Payback amount must not be 0"); require(_collateralAmount > 0, "Collateral amount must not be 0"); super._mint(_lenderAddress, 1); factoryContract = msg.sender; ownerAddress = _ownerAddress; loanId = _loanId; borrowedTokenAddress = _borrowedTokenAddress; borrowAmount = _borrowAmount; collateralAmount = _collateralAmount; totalLoanTerm = _remainingInstallment * _daysPerInstallment; daysPerInstallment = _daysPerInstallment; remainingInstallment = _remainingInstallment; installmentAmount = _paybackAmount / _remainingInstallment; token = StandardToken(_borrowedTokenAddress); borrowerAddress = _borrowerAddress; lenderAddress = _lenderAddress; currentState = States.WaitingForCollateral; } /** * Borrower transfer ETH to contract */ function transferCollateral() public payable atState(States.WaitingForCollateral) { if (address(this).balance >= collateralAmount) { currentState = States.WaitingForFunds; } } /** * */ function checkFunds() public onlyLender atState(States.WaitingForFunds) { uint amount = token.balanceOf(address(this)); require(amount >= borrowAmount, "Insufficient borrowed amount"); transferTokenToBorrowerAndStartLoan(token); } /** * NOT IN USE * WHEN COLLATERAL IS ETH, CHECK IS DONE IN transferCollateral() */ function checkCollateral() public { revert(); } /** * NOT IN USE * WHEN FUND IS TOKEN, TRANSFER IS DONE IN FRONT END */ function transferFunds() public payable { revert(); } /* * Borrower gets collateral ETH back when contract completed */ function borrowerCancel() public onlyBorrower atState(States.WaitingForFunds) { borrowerAddress.transfer(address(this).balance); currentState = States.Cancelled; } /* * Borrower gets collateral ETH back when contract completed */ function lenderCancel() public onlyLender atState(States.WaitingForCollateral) { revert(); } } // File: contracts\ETHERC20LoanLender.sol pragma solidity ^0.4.23; /** * Collateral: ETH * Borrowed: ERC20 Token */ contract ETHERC20LoanLender is ETHERC20Loan { function init ( address _ownerAddress, address _borrowerAddress, address _lenderAddress, address _borrowedTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId ) public onlyFactoryContract { require(_borrowedTokenAddress != address(0), "Invalid token address"); require(_borrowerAddress != address(0), "Invalid lender address"); require(_lenderAddress != address(0), "Invalid lender address"); require(_remainingInstallment > 0, "Invalid number of installments"); require(_borrowAmount > 0, "Borrow amount must not be 0"); require(_paybackAmount > 0, "Payback amount must not be 0"); require(_collateralAmount > 0, "Collateral amount must not be 0"); super._mint(_lenderAddress, 1); factoryContract = msg.sender; ownerAddress = _ownerAddress; loanId = _loanId; borrowedTokenAddress = _borrowedTokenAddress; borrowAmount = _borrowAmount; collateralAmount = _collateralAmount; totalLoanTerm = _remainingInstallment * _daysPerInstallment; daysPerInstallment = _daysPerInstallment; remainingInstallment = _remainingInstallment; installmentAmount = _paybackAmount / _remainingInstallment; token = StandardToken(_borrowedTokenAddress); borrowerAddress = _borrowerAddress; lenderAddress = _lenderAddress; currentState = States.WaitingForFunds; } /** * Borrower transfer ETH to contract */ function transferCollateral() public payable atState(States.WaitingForCollateral) { require(address(this).balance >= collateralAmount, "Insufficient ETH collateral amount"); transferTokenToBorrowerAndStartLoan(token); } /** * */ function checkFunds() public onlyLender atState(States.WaitingForFunds) { uint amount = token.balanceOf(address(this)); require(amount >= borrowAmount, "Insufficient fund amount"); currentState = States.WaitingForCollateral; } /** * NOT IN USE * WHEN COLLATERAL IS ETH, CHECK IS DONE IN transferCollateral() */ function checkCollateral() public { revert(); } /** * NOT IN USE * WHEN FUND IS TOKEN, TRANSFER IS DONE IN FRONT END */ function transferFunds() public payable { revert(); } /* * Borrower gets collateral ETH back when contract completed */ function borrowerCancel() public onlyBorrower atState(States.WaitingForFunds) { revert(); } /* * Borrower gets collateral ETH back when contract completed */ function lenderCancel() public onlyLender atState(States.WaitingForCollateral) { uint amount = token.balanceOf(address(this)); token.transfer(lenderAddress, amount); currentState = States.Cancelled; } } // File: contracts\ERC20ERC20Loan.sol pragma solidity ^0.4.23; /** * Collateral: ERC20 Token * Borrowed: ERC20 Token */ contract ERC20ERC20Loan is DefinerBasicLoan { StandardToken collateralToken; StandardToken borrowedToken; address public collateralTokenAddress; address public borrowedTokenAddress; /* * Borrower pay back Token */ function borrowerMakePayment() public payable onlyBorrower atState(States.Funded) notDefault { require(remainingInstallment > 0, "No remaining installments"); require(installmentAmount > 0, "Installment amount must be non zero"); borrowedToken.transfer(lenderAddress, installmentAmount); remainingInstallment--; if (remainingInstallment == 0) { currentState = States.Finished; } else { nextPaymentDateTime = nextPaymentDateTime.add(daysPerInstallment.mul(1 days)); } } /* * Borrower gets collateral token back when contract completed */ function borrowerReclaimCollateral() public onlyBorrower atState(States.Finished) { uint amount = collateralToken.balanceOf(address(this)); collateralToken.transfer(borrowerAddress, amount); currentState = States.Closed; } /* * Lender gets collateral token when contract defaulted */ function lenderReclaimCollateral() public onlyLender atState(States.Default) { uint amount = collateralToken.balanceOf(address(this)); collateralToken.transfer(lenderAddress, amount); currentState = States.Closed; } } // File: contracts\ERC20ERC20LoanBorrower.sol pragma solidity ^0.4.23; /** * Collateral: ERC20 Token * Borrowed: ERC20 Token */ contract ERC20ERC20LoanBorrower is ERC20ERC20Loan { function init ( address _ownerAddress, address _borrowerAddress, address _lenderAddress, address _collateralTokenAddress, address _borrowedTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId ) public onlyFactoryContract { require(_collateralTokenAddress != _borrowedTokenAddress); require(_collateralTokenAddress != address(0), "Invalid token address"); require(_borrowedTokenAddress != address(0), "Invalid token address"); require(_borrowerAddress != address(0), "Invalid lender address"); require(_lenderAddress != address(0), "Invalid lender address"); require(_remainingInstallment > 0, "Invalid number of installments"); require(_borrowAmount > 0, "Borrow amount must not be 0"); require(_paybackAmount > 0, "Payback amount must not be 0"); require(_collateralAmount > 0, "Collateral amount must not be 0"); super._mint(_lenderAddress, 1); factoryContract = msg.sender; ownerAddress = _ownerAddress; loanId = _loanId; collateralTokenAddress = _collateralTokenAddress; borrowedTokenAddress = _borrowedTokenAddress; borrowAmount = _borrowAmount; collateralAmount = _collateralAmount; totalLoanTerm = _remainingInstallment * _daysPerInstallment; daysPerInstallment = _daysPerInstallment; remainingInstallment = _remainingInstallment; installmentAmount = _paybackAmount / _remainingInstallment; collateralToken = StandardToken(_collateralTokenAddress); borrowedToken = StandardToken(_borrowedTokenAddress); borrowerAddress = _borrowerAddress; lenderAddress = _lenderAddress; currentState = States.WaitingForCollateral; } /** * NOT IN USE * WHEN COLLATERAL IS TOKEN, TRANSFER IS DONE IN FRONT END */ function transferCollateral() public payable { revert(); } /** * NOT IN USE * WHEN FUND IS TOKEN, TRANSFER IS DONE IN FRONT END */ function transferFunds() public payable { revert(); } /** * */ function checkFunds() public onlyLender atState(States.WaitingForFunds) { uint amount = borrowedToken.balanceOf(address(this)); require(amount >= borrowAmount, "Insufficient borrowed amount"); transferTokenToBorrowerAndStartLoan(borrowedToken); } /** * Check if borrower transferred correct amount of token to this contract */ function checkCollateral() public onlyBorrower atState(States.WaitingForCollateral) { uint amount = collateralToken.balanceOf(address(this)); require(amount >= collateralAmount, "Insufficient Collateral Token amount"); currentState = States.WaitingForFunds; } /* * Borrower gets collateral token back when contract cancelled */ function borrowerCancel() public onlyBorrower atState(States.WaitingForFunds) { uint amount = collateralToken.balanceOf(address(this)); collateralToken.transfer(borrowerAddress, amount); currentState = States.Cancelled; } /* * Lender gets fund token back when contract cancelled */ function lenderCancel() public onlyLender atState(States.WaitingForCollateral) { revert(); } } // File: contracts\ERC20ERC20LoanLender.sol pragma solidity ^0.4.23; /** * Collateral: ERC20 Token * Borrowed: ERC20 Token */ contract ERC20ERC20LoanLender is ERC20ERC20Loan { function init ( address _ownerAddress, address _borrowerAddress, address _lenderAddress, address _collateralTokenAddress, address _borrowedTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId ) public onlyFactoryContract { require(_collateralTokenAddress != _borrowedTokenAddress); require(_collateralTokenAddress != address(0), "Invalid token address"); require(_borrowedTokenAddress != address(0), "Invalid token address"); require(_borrowerAddress != address(0), "Invalid lender address"); require(_lenderAddress != address(0), "Invalid lender address"); require(_remainingInstallment > 0, "Invalid number of installments"); require(_borrowAmount > 0, "Borrow amount must not be 0"); require(_paybackAmount > 0, "Payback amount must not be 0"); require(_collateralAmount > 0, "Collateral amount must not be 0"); super._mint(_lenderAddress, 1); factoryContract = msg.sender; ownerAddress = _ownerAddress; loanId = _loanId; collateralTokenAddress = _collateralTokenAddress; borrowedTokenAddress = _borrowedTokenAddress; borrowAmount = _borrowAmount; collateralAmount = _collateralAmount; totalLoanTerm = _remainingInstallment * _daysPerInstallment; daysPerInstallment = _daysPerInstallment; remainingInstallment = _remainingInstallment; installmentAmount = _paybackAmount / _remainingInstallment; collateralToken = StandardToken(_collateralTokenAddress); borrowedToken = StandardToken(_borrowedTokenAddress); borrowerAddress = _borrowerAddress; lenderAddress = _lenderAddress; currentState = States.WaitingForFunds; } /** * NOT IN USE * WHEN COLLATERAL IS TOKEN, TRANSFER IS DONE IN FRONT END */ function transferCollateral() public payable { revert(); } /** * NOT IN USE * WHEN FUND IS TOKEN, TRANSFER IS DONE IN FRONT END */ function transferFunds() public payable { revert(); } /** * */ function checkFunds() public onlyLender atState(States.WaitingForFunds) { uint amount = borrowedToken.balanceOf(address(this)); require(amount >= borrowAmount, "Insufficient fund amount"); currentState = States.WaitingForCollateral; } /** * Check if borrower transferred correct amount of token to this contract */ function checkCollateral() public onlyBorrower atState(States.WaitingForCollateral) { uint amount = collateralToken.balanceOf(address(this)); require(amount >= collateralAmount, "Insufficient Collateral Token amount"); transferTokenToBorrowerAndStartLoan(borrowedToken); } /* * Borrower gets collateral token back when contract cancelled */ function borrowerCancel() public onlyBorrower atState(States.WaitingForFunds) { revert(); } /* * Lender gets fund token back when contract cancelled */ function lenderCancel() public onlyLender atState(States.WaitingForCollateral) { uint amount = borrowedToken.balanceOf(address(this)); borrowedToken.transfer(lenderAddress, amount); currentState = States.Cancelled; } } // File: contracts\DefinerLoanFactory.sol pragma solidity ^0.4.23; library Library { struct contractAddress { address value; bool exists; } } contract CloneFactory { event CloneCreated(address indexed target, address clone); function createClone(address target) internal returns (address result) { bytes memory clone = hex"3d602d80600a3d3981f3363d3d373d3d3d363d73bebebebebebebebebebebebebebebebebebebebe5af43d82803e903d91602b57fd5bf3"; bytes20 targetBytes = bytes20(target); for (uint i = 0; i < 20; i++) { clone[20 + i] = targetBytes[i]; } assembly { let len := mload(clone) let data := add(clone, 0x20) result := create(0, data, len) } } } contract DefinerLoanFactory is CloneFactory { using Library for Library.contractAddress; address public owner = msg.sender; address public ERC20ETHLoanBorrowerMasterContractAddress; address public ERC20ETHLoanLenderMasterContractAddress; address public ETHERC20LoanBorrowerMasterContractAddress; address public ETHERC20LoanLenderMasterContractAddress; address public ERC20ERC20LoanBorrowerMasterContractAddress; address public ERC20ERC20LoanLenderMasterContractAddress; mapping(address => address[]) contractMap; mapping(string => Library.contractAddress) contractById; modifier onlyOwner() { require(msg.sender == owner, "Invalid Owner Address"); _; } constructor ( address _ERC20ETHLoanBorrowerMasterContractAddress, address _ERC20ETHLoanLenderMasterContractAddress, address _ETHERC20LoanBorrowerMasterContractAddress, address _ETHERC20LoanLenderMasterContractAddress, address _ERC20ERC20LoanBorrowerMasterContractAddress, address _ERC20ERC20LoanLenderMasterContractAddress ) public { owner = msg.sender; ERC20ETHLoanBorrowerMasterContractAddress = _ERC20ETHLoanBorrowerMasterContractAddress; ERC20ETHLoanLenderMasterContractAddress = _ERC20ETHLoanLenderMasterContractAddress; ETHERC20LoanBorrowerMasterContractAddress = _ETHERC20LoanBorrowerMasterContractAddress; ETHERC20LoanLenderMasterContractAddress = _ETHERC20LoanLenderMasterContractAddress; ERC20ERC20LoanBorrowerMasterContractAddress = _ERC20ERC20LoanBorrowerMasterContractAddress; ERC20ERC20LoanLenderMasterContractAddress = _ERC20ERC20LoanLenderMasterContractAddress; } function getUserContracts(address userAddress) public view returns (address[]) { return contractMap[userAddress]; } function getContractByLoanId(string _loanId) public view returns (address) { return contractById[_loanId].value; } function createERC20ETHLoanBorrowerClone( address _collateralTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId, address _lenderAddress ) public payable returns (address) { require(!contractById[_loanId].exists, "contract already exists"); address clone = createClone(ERC20ETHLoanBorrowerMasterContractAddress); ERC20ETHLoanBorrower(clone).init({ _ownerAddress : owner, _borrowerAddress : msg.sender, _lenderAddress : _lenderAddress, _collateralTokenAddress : _collateralTokenAddress, _borrowAmount : _borrowAmount, _paybackAmount : _paybackAmount, _collateralAmount : _collateralAmount, _daysPerInstallment : _daysPerInstallment, _remainingInstallment : _remainingInstallment, _loanId : _loanId}); contractMap[msg.sender].push(clone); contractById[_loanId] = Library.contractAddress(clone, true); return clone; } function createERC20ETHLoanLenderClone( address _collateralTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId, address _borrowerAddress ) public payable returns (address) { require(!contractById[_loanId].exists, "contract already exists"); address clone = createClone(ERC20ETHLoanLenderMasterContractAddress); ERC20ETHLoanLender(clone).init({ _ownerAddress : owner, _borrowerAddress : _borrowerAddress, _lenderAddress : msg.sender, _collateralTokenAddress : _collateralTokenAddress, _borrowAmount : _borrowAmount, _paybackAmount : _paybackAmount, _collateralAmount : _collateralAmount, _daysPerInstallment : _daysPerInstallment, _remainingInstallment : _remainingInstallment, _loanId : _loanId}); if (msg.value > 0) { ERC20ETHLoanLender(clone).transferFunds.value(msg.value)(); } contractMap[msg.sender].push(clone); contractById[_loanId] = Library.contractAddress(clone, true); return clone; } function createETHERC20LoanBorrowerClone( address _borrowedTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId, address _lenderAddress ) public payable returns (address) { require(!contractById[_loanId].exists, "contract already exists"); address clone = createClone(ETHERC20LoanBorrowerMasterContractAddress); ETHERC20LoanBorrower(clone).init({ _ownerAddress : owner, _borrowerAddress : msg.sender, _lenderAddress : _lenderAddress, _borrowedTokenAddress : _borrowedTokenAddress, _borrowAmount : _borrowAmount, _paybackAmount : _paybackAmount, _collateralAmount : _collateralAmount, _daysPerInstallment : _daysPerInstallment, _remainingInstallment : _remainingInstallment, _loanId : _loanId}); if (msg.value >= _collateralAmount) { ETHERC20LoanBorrower(clone).transferCollateral.value(msg.value)(); } contractMap[msg.sender].push(clone); contractById[_loanId] = Library.contractAddress(clone, true); return clone; } function createETHERC20LoanLenderClone( address _borrowedTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId, address _borrowerAddress ) public payable returns (address) { require(!contractById[_loanId].exists, "contract already exists"); address clone = createClone(ETHERC20LoanLenderMasterContractAddress); ETHERC20LoanLender(clone).init({ _ownerAddress : owner, _borrowerAddress : _borrowerAddress, _lenderAddress : msg.sender, _borrowedTokenAddress : _borrowedTokenAddress, _borrowAmount : _borrowAmount, _paybackAmount : _paybackAmount, _collateralAmount : _collateralAmount, _daysPerInstallment : _daysPerInstallment, _remainingInstallment : _remainingInstallment, _loanId : _loanId}); contractMap[msg.sender].push(clone); contractById[_loanId] = Library.contractAddress(clone, true); return clone; } function createERC20ERC20LoanBorrowerClone( address _collateralTokenAddress, address _borrowedTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId, address _lenderAddress ) public returns (address) { require(!contractById[_loanId].exists, "contract already exists"); address clone = createClone(ERC20ERC20LoanBorrowerMasterContractAddress); ERC20ERC20LoanBorrower(clone).init({ _ownerAddress : owner, _borrowerAddress : msg.sender, _lenderAddress : _lenderAddress, _collateralTokenAddress : _collateralTokenAddress, _borrowedTokenAddress : _borrowedTokenAddress, _borrowAmount : _borrowAmount, _paybackAmount : _paybackAmount, _collateralAmount : _collateralAmount, _daysPerInstallment : _daysPerInstallment, _remainingInstallment : _remainingInstallment, _loanId : _loanId}); contractMap[msg.sender].push(clone); contractById[_loanId] = Library.contractAddress(clone, true); return clone; } function createERC20ERC20LoanLenderClone( address _collateralTokenAddress, address _borrowedTokenAddress, uint _borrowAmount, uint _paybackAmount, uint _collateralAmount, uint _daysPerInstallment, uint _remainingInstallment, string _loanId, address _borrowerAddress ) public returns (address) { require(!contractById[_loanId].exists, "contract already exists"); address clone = createClone(ERC20ERC20LoanLenderMasterContractAddress); ERC20ERC20LoanLender(clone).init({ _ownerAddress : owner, _borrowerAddress : _borrowerAddress, _lenderAddress : msg.sender, _collateralTokenAddress : _collateralTokenAddress, _borrowedTokenAddress : _borrowedTokenAddress, _borrowAmount : _borrowAmount, _paybackAmount : _paybackAmount, _collateralAmount : _collateralAmount, _daysPerInstallment : _daysPerInstallment, _remainingInstallment : _remainingInstallment, _loanId : _loanId}); contractMap[msg.sender].push(clone); contractById[_loanId] = Library.contractAddress(clone, true); return clone; } function changeOwner(address newOwner) public onlyOwner { owner = newOwner; } }
Borrower gets collateral token back when contract cancelled/
function borrowerCancel() public onlyBorrower atState(States.WaitingForFunds) { uint amount = collateralToken.balanceOf(address(this)); collateralToken.transfer(borrowerAddress, amount); currentState = States.Cancelled; }
1,755,056
// Created for proof of concept examples. pragma solidity ^0.4.21; // Proof of Existence contract, modified contract ProofOfExistenceZDF { // store mapping of collected proofs // a proof is a sha256 of a "document" (string) and the sender's address mapping (bytes32 => bool) private proofs; address public owner; function constructor() public { owner = msg.sender; } // store a proof of existence in the contract state function storeProof(bytes32 proof) internal { proofs[proof] = true; } // Only let the owner of the contract notarize! // this makes this a centralized, not decentralized, system modifier onlyOwner { if (msg.sender != owner) revert() ; _; } // calculate and store the proof for a document function notarize(string document) public { bytes32 proof = proofFor(document); storeProof(proof); } // helper function to get a document's sha256 // use the sender's address to combine document string, to show per-person proofs. function proofFor(string document) internal view returns (bytes32) { // This can be modified to add salting or other document IDs return sha256(document, msg.sender); } // check if a document has been notarized function checkDocument(string document) public view returns (bool) { bytes32 proof = proofFor(document); return hasProof(proof); } // returns true if proof is stored function hasProof(bytes32 proof) internal constant returns(bool) { return proofs[proof]; } }
check if a document has been notarized
function checkDocument(string document) public view returns (bool) { bytes32 proof = proofFor(document); return hasProof(proof); }
6,425,322
./full_match/1/0x2b4fA931ADc5D6b58674230208787A3dF0bD2121/sources/contracts/v1/interfaces/IERC721.sol
Required interface of an ERC721 compliant contract./ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function safeTransferFrom(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;
interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function transferFrom(address from, address to, uint256 tokenId) external; function setup() external; }
3,096,287
./full_match/137/0x7d561bE86eBCB1d8353f98c21Bef7232343598a8/sources/WebaverseERC721.sol
Check if this address is a collaborator on a single issue token (like land) tokenId ID of the token a Address to check return Returns true if the address is a collaborator on the token/
function isSingleCollaborator(uint256 tokenId, address a) public view returns (bool) { for (uint256 i = 0; i < tokenIdToCollaborators[tokenId].length; i++) { if (tokenIdToCollaborators[tokenId][i] == a) { return true; } } return false; }
4,669,348
pragma solidity ^0.4.18; /** * @title Owned contract with safe ownership pass. * * Note: all the non constant functions return false instead of throwing in case if state change * didn't happen yet. */ contract Owned { /** * Contract owner address */ address public contractOwner; /** * Contract owner address */ address public pendingContractOwner; function Owned() { contractOwner = msg.sender; } /** * @dev Owner check modifier */ modifier onlyContractOwner() { if (contractOwner == msg.sender) { _; } } /** * @dev Destroy contract and scrub a data * @notice Only owner can call it */ function destroy() onlyContractOwner { suicide(msg.sender); } /** * Prepares ownership pass. * * Can only be called by current owner. * * @param _to address of the next owner. 0x0 is not allowed. * * @return success. */ function changeContractOwnership(address _to) onlyContractOwner() returns(bool) { if (_to == 0x0) { return false; } pendingContractOwner = _to; return true; } /** * Finalize ownership pass. * * Can only be called by pending owner. * * @return success. */ function claimContractOwnership() returns(bool) { if (pendingContractOwner != msg.sender) { return false; } contractOwner = pendingContractOwner; delete pendingContractOwner; return true; } } contract ERC20Interface { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); string public symbol; function totalSupply() constant returns (uint256 supply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); } /** * @title Generic owned destroyable contract */ contract Object is Owned { /** * Common result code. Means everything is fine. */ uint constant OK = 1; uint constant OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER = 8; function withdrawnTokens(address[] tokens, address _to) onlyContractOwner returns(uint) { for(uint i=0;i<tokens.length;i++) { address token = tokens[i]; uint balance = ERC20Interface(token).balanceOf(this); if(balance != 0) ERC20Interface(token).transfer(_to,balance); } return OK; } function checkOnlyContractOwner() internal constant returns(uint) { if (contractOwner == msg.sender) { return OK; } return OWNED_ACCESS_DENIED_ONLY_CONTRACT_OWNER; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title General MultiEventsHistory user. * */ contract MultiEventsHistoryAdapter { /** * @dev It is address of MultiEventsHistory caller assuming we are inside of delegate call. */ function _self() constant internal returns (address) { return msg.sender; } } /// @title Fund Tokens Platform Emitter. /// /// Contains all the original event emitting function definitions and events. /// In case of new events needed later, additional emitters can be developed. /// All the functions is meant to be called using delegatecall. contract Emitter is MultiEventsHistoryAdapter { event Transfer(address indexed from, address indexed to, bytes32 indexed symbol, uint value, string reference); event Issue(bytes32 indexed symbol, uint value, address indexed by); event Revoke(bytes32 indexed symbol, uint value, address indexed by); event OwnershipChange(address indexed from, address indexed to, bytes32 indexed symbol); event Approve(address indexed from, address indexed spender, bytes32 indexed symbol, uint value); event Recovery(address indexed from, address indexed to, address by); event Error(uint errorCode); function emitTransfer(address _from, address _to, bytes32 _symbol, uint _value, string _reference) public { Transfer(_from, _to, _symbol, _value, _reference); } function emitIssue(bytes32 _symbol, uint _value, address _by) public { Issue(_symbol, _value, _by); } function emitRevoke(bytes32 _symbol, uint _value, address _by) public { Revoke(_symbol, _value, _by); } function emitOwnershipChange(address _from, address _to, bytes32 _symbol) public { OwnershipChange(_from, _to, _symbol); } function emitApprove(address _from, address _spender, bytes32 _symbol, uint _value) public { Approve(_from, _spender, _symbol, _value); } function emitRecovery(address _from, address _to, address _by) public { Recovery(_from, _to, _by); } function emitError(uint _errorCode) public { Error(_errorCode); } } contract ProxyEventsEmitter { function emitTransfer(address _from, address _to, uint _value) public; function emitApprove(address _from, address _spender, uint _value) public; } /// @title Fund Tokens Platform. /// /// Platform uses MultiEventsHistory contract to keep events, so that in case it needs to be redeployed /// at some point, all the events keep appearing at the same place. /// /// Every asset is meant to be used through a proxy contract. Only one proxy contract have access /// rights for a particular asset. /// /// Features: transfers, allowances, supply adjustments, lost wallet access recovery. /// /// Note: all the non constant functions return false instead of throwing in case if state change /// didn't happen yet. /// BMCPlatformInterface compatibility contract ATxPlatform is Object, Emitter { uint constant ATX_PLATFORM_SCOPE = 80000; uint constant ATX_PLATFORM_PROXY_ALREADY_EXISTS = ATX_PLATFORM_SCOPE + 1; uint constant ATX_PLATFORM_CANNOT_APPLY_TO_ONESELF = ATX_PLATFORM_SCOPE + 2; uint constant ATX_PLATFORM_INVALID_VALUE = ATX_PLATFORM_SCOPE + 3; uint constant ATX_PLATFORM_INSUFFICIENT_BALANCE = ATX_PLATFORM_SCOPE + 4; uint constant ATX_PLATFORM_NOT_ENOUGH_ALLOWANCE = ATX_PLATFORM_SCOPE + 5; uint constant ATX_PLATFORM_ASSET_ALREADY_ISSUED = ATX_PLATFORM_SCOPE + 6; uint constant ATX_PLATFORM_CANNOT_ISSUE_FIXED_ASSET_WITH_INVALID_VALUE = ATX_PLATFORM_SCOPE + 7; uint constant ATX_PLATFORM_CANNOT_REISSUE_FIXED_ASSET = ATX_PLATFORM_SCOPE + 8; uint constant ATX_PLATFORM_SUPPLY_OVERFLOW = ATX_PLATFORM_SCOPE + 9; uint constant ATX_PLATFORM_NOT_ENOUGH_TOKENS = ATX_PLATFORM_SCOPE + 10; uint constant ATX_PLATFORM_INVALID_NEW_OWNER = ATX_PLATFORM_SCOPE + 11; uint constant ATX_PLATFORM_ALREADY_TRUSTED = ATX_PLATFORM_SCOPE + 12; uint constant ATX_PLATFORM_SHOULD_RECOVER_TO_NEW_ADDRESS = ATX_PLATFORM_SCOPE + 13; uint constant ATX_PLATFORM_ASSET_IS_NOT_ISSUED = ATX_PLATFORM_SCOPE + 14; uint constant ATX_PLATFORM_INVALID_INVOCATION = ATX_PLATFORM_SCOPE + 15; using SafeMath for uint; /// @title Structure of a particular asset. struct Asset { uint owner; // Asset's owner id. uint totalSupply; // Asset's total supply. string name; // Asset's name, for information purposes. string description; // Asset's description, for information purposes. bool isReissuable; // Indicates if asset have dynamic or fixed supply. uint8 baseUnit; // Proposed number of decimals. mapping(uint => Wallet) wallets; // Holders wallets. mapping(uint => bool) partowners; // Part-owners of an asset; have less access rights than owner } /// @title Structure of an asset holder wallet for particular asset. struct Wallet { uint balance; mapping(uint => uint) allowance; } /// @title Structure of an asset holder. struct Holder { address addr; // Current address of the holder. mapping(address => bool) trust; // Addresses that are trusted with recovery proocedure. } /// @dev Iterable mapping pattern is used for holders. /// @dev This is an access address mapping. Many addresses may have access to a single holder. uint public holdersCount; mapping(uint => Holder) public holders; mapping(address => uint) holderIndex; /// @dev List of symbols that exist in a platform bytes32[] public symbols; /// @dev Asset symbol to asset mapping. mapping(bytes32 => Asset) public assets; /// @dev Asset symbol to asset proxy mapping. mapping(bytes32 => address) public proxies; /// @dev Co-owners of a platform. Has less access rights than a root contract owner mapping(address => bool) public partowners; /// @dev Should use interface of the emitter, but address of events history. address public eventsHistory; /// @dev Emits Error if called not by asset owner. modifier onlyOwner(bytes32 _symbol) { if (isOwner(msg.sender, _symbol)) { _; } } /// @dev UNAUTHORIZED if called not by one of symbol's partowners or owner modifier onlyOneOfOwners(bytes32 _symbol) { if (hasAssetRights(msg.sender, _symbol)) { _; } } /// @dev UNAUTHORIZED if called not by one of partowners or contract's owner modifier onlyOneOfContractOwners() { if (contractOwner == msg.sender || partowners[msg.sender]) { _; } } /// @dev Emits Error if called not by asset proxy. modifier onlyProxy(bytes32 _symbol) { if (proxies[_symbol] == msg.sender) { _; } } /// @dev Emits Error if _from doesn't trust _to. modifier checkTrust(address _from, address _to) { if (isTrusted(_from, _to)) { _; } } function() payable public { revert(); } /// @notice Trust an address to perform recovery procedure for the caller. /// /// @return success. function trust() external returns (uint) { uint fromId = _createHolderId(msg.sender); // Should trust to another address. if (msg.sender == contractOwner) { return _error(ATX_PLATFORM_CANNOT_APPLY_TO_ONESELF); } // Should trust to yet untrusted. if (isTrusted(msg.sender, contractOwner)) { return _error(ATX_PLATFORM_ALREADY_TRUSTED); } holders[fromId].trust[contractOwner] = true; return OK; } /// @notice Revoke trust to perform recovery procedure from an address. /// /// @return success. function distrust() external checkTrust(msg.sender, contractOwner) returns (uint) { holders[getHolderId(msg.sender)].trust[contractOwner] = false; return OK; } /// @notice Adds a co-owner of a contract. Might be more than one co-owner /// /// @dev Allowed to only contract onwer /// /// @param _partowner a co-owner of a contract /// /// @return result code of an operation function addPartOwner(address _partowner) external onlyContractOwner returns (uint) { partowners[_partowner] = true; return OK; } /// @notice emoves a co-owner of a contract /// /// @dev Should be performed only by root contract owner /// /// @param _partowner a co-owner of a contract /// /// @return result code of an operation function removePartOwner(address _partowner) external onlyContractOwner returns (uint) { delete partowners[_partowner]; return OK; } /// @notice Sets EventsHstory contract address. /// /// @dev Can be set only by owner. /// /// @param _eventsHistory MultiEventsHistory contract address. /// /// @return success. function setupEventsHistory(address _eventsHistory) external onlyContractOwner returns (uint errorCode) { eventsHistory = _eventsHistory; return OK; } /// @notice Adds a co-owner for an asset with provided symbol. /// @dev Should be performed by a contract owner or its co-owners /// /// @param _symbol asset's symbol /// @param _partowner a co-owner of an asset /// /// @return errorCode result code of an operation function addAssetPartOwner(bytes32 _symbol, address _partowner) external onlyOneOfOwners(_symbol) returns (uint) { uint holderId = _createHolderId(_partowner); assets[_symbol].partowners[holderId] = true; Emitter(eventsHistory).emitOwnershipChange(0x0, _partowner, _symbol); return OK; } /// @notice Removes a co-owner for an asset with provided symbol. /// @dev Should be performed by a contract owner or its co-owners /// /// @param _symbol asset's symbol /// @param _partowner a co-owner of an asset /// /// @return errorCode result code of an operation function removeAssetPartOwner(bytes32 _symbol, address _partowner) external onlyOneOfOwners(_symbol) returns (uint) { uint holderId = getHolderId(_partowner); delete assets[_symbol].partowners[holderId]; Emitter(eventsHistory).emitOwnershipChange(_partowner, 0x0, _symbol); return OK; } function massTransfer(address[] addresses, uint[] values, bytes32 _symbol) external onlyOneOfOwners(_symbol) returns (uint errorCode, uint count) { require(addresses.length == values.length); require(_symbol != 0x0); uint senderId = _createHolderId(msg.sender); uint success = 0; for (uint idx = 0; idx < addresses.length && msg.gas > 110000; ++idx) { uint value = values[idx]; if (value == 0) { _error(ATX_PLATFORM_INVALID_VALUE); continue; } if (_balanceOf(senderId, _symbol) < value) { _error(ATX_PLATFORM_INSUFFICIENT_BALANCE); continue; } if (msg.sender == addresses[idx]) { _error(ATX_PLATFORM_CANNOT_APPLY_TO_ONESELF); continue; } uint holderId = _createHolderId(addresses[idx]); _transferDirect(senderId, holderId, value, _symbol); Emitter(eventsHistory).emitTransfer(msg.sender, addresses[idx], _symbol, value, ""); ++success; } return (OK, success); } /// @notice Provides a cheap way to get number of symbols registered in a platform /// /// @return number of symbols function symbolsCount() public view returns (uint) { return symbols.length; } /// @notice Check asset existance. /// /// @param _symbol asset symbol. /// /// @return asset existance. function isCreated(bytes32 _symbol) public view returns (bool) { return assets[_symbol].owner != 0; } /// @notice Returns asset decimals. /// /// @param _symbol asset symbol. /// /// @return asset decimals. function baseUnit(bytes32 _symbol) public view returns (uint8) { return assets[_symbol].baseUnit; } /// @notice Returns asset name. /// /// @param _symbol asset symbol. /// /// @return asset name. function name(bytes32 _symbol) public view returns (string) { return assets[_symbol].name; } /// @notice Returns asset description. /// /// @param _symbol asset symbol. /// /// @return asset description. function description(bytes32 _symbol) public view returns (string) { return assets[_symbol].description; } /// @notice Returns asset reissuability. /// /// @param _symbol asset symbol. /// /// @return asset reissuability. function isReissuable(bytes32 _symbol) public view returns (bool) { return assets[_symbol].isReissuable; } /// @notice Returns asset owner address. /// /// @param _symbol asset symbol. /// /// @return asset owner address. function owner(bytes32 _symbol) public view returns (address) { return holders[assets[_symbol].owner].addr; } /// @notice Check if specified address has asset owner rights. /// /// @param _owner address to check. /// @param _symbol asset symbol. /// /// @return owner rights availability. function isOwner(address _owner, bytes32 _symbol) public view returns (bool) { return isCreated(_symbol) && (assets[_symbol].owner == getHolderId(_owner)); } /// @notice Checks if a specified address has asset owner or co-owner rights. /// /// @param _owner address to check. /// @param _symbol asset symbol. /// /// @return owner rights availability. function hasAssetRights(address _owner, bytes32 _symbol) public view returns (bool) { uint holderId = getHolderId(_owner); return isCreated(_symbol) && (assets[_symbol].owner == holderId || assets[_symbol].partowners[holderId]); } /// @notice Returns asset total supply. /// /// @param _symbol asset symbol. /// /// @return asset total supply. function totalSupply(bytes32 _symbol) public view returns (uint) { return assets[_symbol].totalSupply; } /// @notice Returns asset balance for a particular holder. /// /// @param _holder holder address. /// @param _symbol asset symbol. /// /// @return holder balance. function balanceOf(address _holder, bytes32 _symbol) public view returns (uint) { return _balanceOf(getHolderId(_holder), _symbol); } /// @notice Returns asset balance for a particular holder id. /// /// @param _holderId holder id. /// @param _symbol asset symbol. /// /// @return holder balance. function _balanceOf(uint _holderId, bytes32 _symbol) public view returns (uint) { return assets[_symbol].wallets[_holderId].balance; } /// @notice Returns current address for a particular holder id. /// /// @param _holderId holder id. /// /// @return holder address. function _address(uint _holderId) public view returns (address) { return holders[_holderId].addr; } function checkIsAssetPartOwner(bytes32 _symbol, address _partowner) public view returns (bool) { require(_partowner != 0x0); uint holderId = getHolderId(_partowner); return assets[_symbol].partowners[holderId]; } /// @notice Sets Proxy contract address for a particular asset. /// /// Can be set only once for each asset, and only by contract owner. /// /// @param _proxyAddress Proxy contract address. /// @param _symbol asset symbol. /// /// @return success. function setProxy(address _proxyAddress, bytes32 _symbol) public onlyOneOfContractOwners returns (uint) { if (proxies[_symbol] != 0x0) { return ATX_PLATFORM_PROXY_ALREADY_EXISTS; } proxies[_symbol] = _proxyAddress; return OK; } /// @notice Returns holder id for the specified address. /// /// @param _holder holder address. /// /// @return holder id. function getHolderId(address _holder) public view returns (uint) { return holderIndex[_holder]; } /// @notice Transfers asset balance between holders wallets. /// /// @dev Can only be called by asset proxy. /// /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _symbol asset symbol. /// @param _reference transfer comment to be included in a Transfer event. /// @param _sender transfer initiator address. /// /// @return success. function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) onlyProxy(_symbol) public returns (uint) { return _transfer(getHolderId(_sender), _createHolderId(_to), _value, _symbol, _reference, getHolderId(_sender)); } /// @notice Issues new asset token on the platform. /// /// Tokens issued with this call go straight to contract owner. /// Each symbol can be issued only once, and only by contract owner. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to issue immediately. /// @param _name name of the asset. /// @param _description description for the asset. /// @param _baseUnit number of decimals. /// @param _isReissuable dynamic or fixed supply. /// /// @return success. function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable) public returns (uint) { return issueAssetToAddress(_symbol, _value, _name, _description, _baseUnit, _isReissuable, msg.sender); } /// @notice Issues new asset token on the platform. /// /// Tokens issued with this call go straight to contract owner. /// Each symbol can be issued only once, and only by contract owner. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to issue immediately. /// @param _name name of the asset. /// @param _description description for the asset. /// @param _baseUnit number of decimals. /// @param _isReissuable dynamic or fixed supply. /// @param _account address where issued balance will be held /// /// @return success. function issueAssetToAddress(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, address _account) public onlyOneOfContractOwners returns (uint) { // Should have positive value if supply is going to be fixed. if (_value == 0 && !_isReissuable) { return _error(ATX_PLATFORM_CANNOT_ISSUE_FIXED_ASSET_WITH_INVALID_VALUE); } // Should not be issued yet. if (isCreated(_symbol)) { return _error(ATX_PLATFORM_ASSET_ALREADY_ISSUED); } uint holderId = _createHolderId(_account); uint creatorId = _account == msg.sender ? holderId : _createHolderId(msg.sender); symbols.push(_symbol); assets[_symbol] = Asset(creatorId, _value, _name, _description, _isReissuable, _baseUnit); assets[_symbol].wallets[holderId].balance = _value; // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. Emitter(eventsHistory).emitIssue(_symbol, _value, _address(holderId)); return OK; } /// @notice Issues additional asset tokens if the asset have dynamic supply. /// /// Tokens issued with this call go straight to asset owner. /// Can only be called by asset owner. /// /// @param _symbol asset symbol. /// @param _value amount of additional tokens to issue. /// /// @return success. function reissueAsset(bytes32 _symbol, uint _value) public onlyOneOfOwners(_symbol) returns (uint) { // Should have positive value. if (_value == 0) { return _error(ATX_PLATFORM_INVALID_VALUE); } Asset storage asset = assets[_symbol]; // Should have dynamic supply. if (!asset.isReissuable) { return _error(ATX_PLATFORM_CANNOT_REISSUE_FIXED_ASSET); } // Resulting total supply should not overflow. if (asset.totalSupply + _value < asset.totalSupply) { return _error(ATX_PLATFORM_SUPPLY_OVERFLOW); } uint holderId = getHolderId(msg.sender); asset.wallets[holderId].balance = asset.wallets[holderId].balance.add(_value); asset.totalSupply = asset.totalSupply.add(_value); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. Emitter(eventsHistory).emitIssue(_symbol, _value, _address(holderId)); _proxyTransferEvent(0, holderId, _value, _symbol); return OK; } /// @notice Destroys specified amount of senders asset tokens. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to destroy. /// /// @return success. function revokeAsset(bytes32 _symbol, uint _value) public returns (uint) { // Should have positive value. if (_value == 0) { return _error(ATX_PLATFORM_INVALID_VALUE); } Asset storage asset = assets[_symbol]; uint holderId = getHolderId(msg.sender); // Should have enough tokens. if (asset.wallets[holderId].balance < _value) { return _error(ATX_PLATFORM_NOT_ENOUGH_TOKENS); } asset.wallets[holderId].balance = asset.wallets[holderId].balance.sub(_value); asset.totalSupply = asset.totalSupply.sub(_value); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. Emitter(eventsHistory).emitRevoke(_symbol, _value, _address(holderId)); _proxyTransferEvent(holderId, 0, _value, _symbol); return OK; } /// @notice Passes asset ownership to specified address. /// /// Only ownership is changed, balances are not touched. /// Can only be called by asset owner. /// /// @param _symbol asset symbol. /// @param _newOwner address to become a new owner. /// /// @return success. function changeOwnership(bytes32 _symbol, address _newOwner) public onlyOwner(_symbol) returns (uint) { if (_newOwner == 0x0) { return _error(ATX_PLATFORM_INVALID_NEW_OWNER); } Asset storage asset = assets[_symbol]; uint newOwnerId = _createHolderId(_newOwner); // Should pass ownership to another holder. if (asset.owner == newOwnerId) { return _error(ATX_PLATFORM_CANNOT_APPLY_TO_ONESELF); } address oldOwner = _address(asset.owner); asset.owner = newOwnerId; // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. Emitter(eventsHistory).emitOwnershipChange(oldOwner, _newOwner, _symbol); return OK; } /// @notice Check if specified holder trusts an address with recovery procedure. /// /// @param _from truster. /// @param _to trustee. /// /// @return trust existance. function isTrusted(address _from, address _to) public view returns (bool) { return holders[getHolderId(_from)].trust[_to]; } /// @notice Perform recovery procedure. /// /// Can be invoked by contract owner if he is trusted by sender only. /// /// This function logic is actually more of an addAccess(uint _holderId, address _to). /// It grants another address access to recovery subject wallets. /// Can only be called by trustee of recovery subject. /// /// @param _from holder address to recover from. /// @param _to address to grant access to. /// /// @return success. function recover(address _from, address _to) checkTrust(_from, msg.sender) public onlyContractOwner returns (uint errorCode) { // We take current holder address because it might not equal _from. // It is possible to recover from any old holder address, but event should have the current one. address from = holders[getHolderId(_from)].addr; holders[getHolderId(_from)].addr = _to; holderIndex[_to] = getHolderId(_from); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: revert this transaction too; // Recursive Call: safe, all changes already made. Emitter(eventsHistory).emitRecovery(from, _to, msg.sender); return OK; } /// @notice Sets asset spending allowance for a specified spender. /// /// @dev Can only be called by asset proxy. /// /// @param _spender holder address to set allowance to. /// @param _value amount to allow. /// @param _symbol asset symbol. /// @param _sender approve initiator address. /// /// @return success. function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) public onlyProxy(_symbol) returns (uint) { return _approve(_createHolderId(_spender), _value, _symbol, _createHolderId(_sender)); } /// @notice Returns asset allowance from one holder to another. /// /// @param _from holder that allowed spending. /// @param _spender holder that is allowed to spend. /// @param _symbol asset symbol. /// /// @return holder to spender allowance. function allowance(address _from, address _spender, bytes32 _symbol) public view returns (uint) { return _allowance(getHolderId(_from), getHolderId(_spender), _symbol); } /// @notice Prforms allowance transfer of asset balance between holders wallets. /// /// @dev Can only be called by asset proxy. /// /// @param _from holder address to take from. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _symbol asset symbol. /// @param _reference transfer comment to be included in a Transfer event. /// @param _sender allowance transfer initiator address. /// /// @return success. function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public onlyProxy(_symbol) returns (uint) { return _transfer(getHolderId(_from), _createHolderId(_to), _value, _symbol, _reference, getHolderId(_sender)); } /// @notice Transfers asset balance between holders wallets. /// /// @param _fromId holder id to take from. /// @param _toId holder id to give to. /// @param _value amount to transfer. /// @param _symbol asset symbol. function _transferDirect(uint _fromId, uint _toId, uint _value, bytes32 _symbol) internal { assets[_symbol].wallets[_fromId].balance = assets[_symbol].wallets[_fromId].balance.sub(_value); assets[_symbol].wallets[_toId].balance = assets[_symbol].wallets[_toId].balance.add(_value); } /// @notice Transfers asset balance between holders wallets. /// /// @dev Performs sanity checks and takes care of allowances adjustment. /// /// @param _fromId holder id to take from. /// @param _toId holder id to give to. /// @param _value amount to transfer. /// @param _symbol asset symbol. /// @param _reference transfer comment to be included in a Transfer event. /// @param _senderId transfer initiator holder id. /// /// @return success. function _transfer(uint _fromId, uint _toId, uint _value, bytes32 _symbol, string _reference, uint _senderId) internal returns (uint) { // Should not allow to send to oneself. if (_fromId == _toId) { return _error(ATX_PLATFORM_CANNOT_APPLY_TO_ONESELF); } // Should have positive value. if (_value == 0) { return _error(ATX_PLATFORM_INVALID_VALUE); } // Should have enough balance. if (_balanceOf(_fromId, _symbol) < _value) { return _error(ATX_PLATFORM_INSUFFICIENT_BALANCE); } // Should have enough allowance. if (_fromId != _senderId && _allowance(_fromId, _senderId, _symbol) < _value) { return _error(ATX_PLATFORM_NOT_ENOUGH_ALLOWANCE); } _transferDirect(_fromId, _toId, _value, _symbol); // Adjust allowance. if (_fromId != _senderId) { assets[_symbol].wallets[_fromId].allowance[_senderId] = assets[_symbol].wallets[_fromId].allowance[_senderId].sub(_value); } // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. Emitter(eventsHistory).emitTransfer(_address(_fromId), _address(_toId), _symbol, _value, _reference); _proxyTransferEvent(_fromId, _toId, _value, _symbol); return OK; } /// @notice Ask asset Proxy contract to emit ERC20 compliant Transfer event. /// /// @param _fromId holder id to take from. /// @param _toId holder id to give to. /// @param _value amount to transfer. /// @param _symbol asset symbol. function _proxyTransferEvent(uint _fromId, uint _toId, uint _value, bytes32 _symbol) internal { if (proxies[_symbol] != 0x0) { // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. ProxyEventsEmitter(proxies[_symbol]).emitTransfer(_address(_fromId), _address(_toId), _value); } } /// @notice Returns holder id for the specified address, creates it if needed. /// /// @param _holder holder address. /// /// @return holder id. function _createHolderId(address _holder) internal returns (uint) { uint holderId = holderIndex[_holder]; if (holderId == 0) { holderId = ++holdersCount; holders[holderId].addr = _holder; holderIndex[_holder] = holderId; } return holderId; } /// @notice Sets asset spending allowance for a specified spender. /// /// Note: to revoke allowance, one needs to set allowance to 0. /// /// @param _spenderId holder id to set allowance for. /// @param _value amount to allow. /// @param _symbol asset symbol. /// @param _senderId approve initiator holder id. /// /// @return success. function _approve(uint _spenderId, uint _value, bytes32 _symbol, uint _senderId) internal returns (uint) { // Asset should exist. if (!isCreated(_symbol)) { return _error(ATX_PLATFORM_ASSET_IS_NOT_ISSUED); } // Should allow to another holder. if (_senderId == _spenderId) { return _error(ATX_PLATFORM_CANNOT_APPLY_TO_ONESELF); } // Double Spend Attack checkpoint if (assets[_symbol].wallets[_senderId].allowance[_spenderId] != 0 && _value != 0) { return _error(ATX_PLATFORM_INVALID_INVOCATION); } assets[_symbol].wallets[_senderId].allowance[_spenderId] = _value; // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: revert this transaction too; // Recursive Call: safe, all changes already made. Emitter(eventsHistory).emitApprove(_address(_senderId), _address(_spenderId), _symbol, _value); if (proxies[_symbol] != 0x0) { // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. ProxyEventsEmitter(proxies[_symbol]).emitApprove(_address(_senderId), _address(_spenderId), _value); } return OK; } /// @notice Returns asset allowance from one holder to another. /// /// @param _fromId holder id that allowed spending. /// @param _toId holder id that is allowed to spend. /// @param _symbol asset symbol. /// /// @return holder to spender allowance. function _allowance(uint _fromId, uint _toId, bytes32 _symbol) internal view returns (uint) { return assets[_symbol].wallets[_fromId].allowance[_toId]; } /// @dev Emits Error event with specified error message. /// Should only be used if no state changes happened. /// @param _errorCode code of an error function _error(uint _errorCode) internal returns (uint) { Emitter(eventsHistory).emitError(_errorCode); return _errorCode; } }
Sets asset spending allowance for a specified spender. Note: to revoke allowance, one needs to set allowance to 0. _spenderId holder id to set allowance for. _value amount to allow. _symbol asset symbol. _senderId approve initiator holder id. return success. Asset should exist. Should allow to another holder. Double Spend Attack checkpoint Internal Out Of Gas/Throw: revert this transaction too; Call Stack Depth Limit reached: n/a after HF 4; Recursive Call: safe, all changes already made.
function _approve(uint _spenderId, uint _value, bytes32 _symbol, uint _senderId) internal returns (uint) { if (!isCreated(_symbol)) { return _error(ATX_PLATFORM_ASSET_IS_NOT_ISSUED); } if (_senderId == _spenderId) { return _error(ATX_PLATFORM_CANNOT_APPLY_TO_ONESELF); } if (assets[_symbol].wallets[_senderId].allowance[_spenderId] != 0 && _value != 0) { return _error(ATX_PLATFORM_INVALID_INVOCATION); } assets[_symbol].wallets[_senderId].allowance[_spenderId] = _value; if (proxies[_symbol] != 0x0) { ProxyEventsEmitter(proxies[_symbol]).emitApprove(_address(_senderId), _address(_spenderId), _value); } return OK; }
5,370,236
pragma solidity 0.5.16; import "./SafeMath.sol"; /** * @dev banq audit is a decentralized audit platform for opensource (smart contract) audit projects * anyone can submit audit request and anyone can submit a audit report. A successful agree results in * increased loyalty points. A disagree results in loss of loyalty points. */ contract BanqAudit { using SafeMath for uint256; //audit data struct Audit { address owner; string link; uint256 balance; uint256[4] rewards; uint256 reportIndex; uint256[] reports; address[] validated; bool closed; } //audit report data struct Report { address owner; bytes32 auditid; bytes32 reportid; string link; uint256 totalrisk; uint256[10] bugs; uint256[10] bugrisk; uint256[10] bugreview; bool[10] bugclosed; //reportstatus 1 = opened, 2 = responded auditee & 3 = closed auditor uint256 reportstatus; uint256 payout; } //Total variables uint256 public totalRewardAvailable; uint256 public totalPendingPayout; //reliability points auditor and auditee uint256 public totalReliability_auditee; uint256 public totalReliability_auditor; mapping (address => uint256) public reliability_auditee; mapping (address => uint256) public reliability_auditor; //audit requests index and mapping of audits uint256 public indexTotal; uint256 public indexPending; mapping (bytes32 => Audit) public audits; mapping (uint256 => bytes32) public index_audit; mapping (bytes32 => uint256) public audit_index; mapping (uint256 => uint256) public total_pending; mapping (uint256 => uint256) public pending_total; //audit report index and mapping of audits uint256 public indexReports; mapping (uint256 => Report) public reports; //address developer used for fee payment address payable public dev; //Events to submit during stages of audit event AuditRequest(bytes32 _contracthash, uint256 _rewardtotal, address owner); event ReportSubmit(bytes32 _contracthash, bytes32 _reporthash, uint256 _reportid, uint256 _risktotal, address owner); event VerifiedReport(bytes32 _contracthash, uint256 _reportid, uint256 _amountreview, uint256 _points, bool received); event ClosedReport(bytes32 _contracthash, uint256 _reportid, uint256 _payout); event ClosedAudit(bytes32 _contracthash, uint256 _amountleft); constructor() public { dev = msg.sender; } /** * @dev fallback function. Makes the contract payable. */ function() external payable {} /** * @dev function for the developer to change the address. */ function changeDev(address payable _dev) external returns (bool) { require(msg.sender == dev, "change developer: not the current developer"); dev = _dev; } /** * @dev functions to get the arrays of the audit and report structs. */ function getAuditData(bytes32 _contracthash) public view returns (uint256[4] memory) { return audits[_contracthash].rewards; } function getAuditReports(bytes32 _contracthash) public view returns (uint256[] memory) { return audits[_contracthash].reports; } function getAuditValidators(bytes32 _contracthash) public view returns (address[] memory) { return audits[_contracthash].validated; } function getReportData(uint256 _indexReports, uint256 id) public view returns (uint256[10] memory) { if (id == 0) { return reports[_indexReports].bugs; } if (id == 1) { return reports[_indexReports].bugrisk; } if (id == 2) { return reports[_indexReports].bugreview; } } /** * @dev auditee can request an audit using this function and sets reward per bug and bug risk. * contract needs a deposit of multiples of the total reward. * */ function RequestAudit(bytes32 _contracthash, string memory _link, uint256[4] memory _rewards) public payable returns (bool success) { uint256[] memory emptyarray; address[] memory emptyaddress; uint256 totalRewards = _rewards[0].add(_rewards[1]).add(_rewards[2]).add(_rewards[3]); //calculate fee 0.3% and deduct form deposit uint256 deposit_multiplier = msg.value.div(totalRewards); uint256 total = totalRewards.mul(deposit_multiplier); uint256 fee = total.div(1000).mul(3); uint256 amount = msg.value.sub(fee); //Check if rewards are multiple of each other and msg.value require(audits[_contracthash].owner == address(0), "request audit: audit is non empty"); require(msg.value != 0, "request audit: no reward added"); require(amount.mod(totalRewards) == 0, "request audit: msg.value not equal to rewards"); require(_rewards[0].mod(_rewards[1]) == 0, "request audit: critical reward is not multiple of high reward"); require(_rewards[1].mod(_rewards[2]) == 0, "request audit: high reward is not multiple of medium reward"); require(_rewards[2].mod(_rewards[3]) == 0, "request audit: critical medium is not multiple of low reward"); totalRewardAvailable = totalRewardAvailable.add(amount); audits[_contracthash] = Audit({owner: msg.sender, link: _link, balance: amount, rewards: _rewards, reportIndex: 0, reports: emptyarray, validated: emptyaddress, closed: false }); index_audit[indexTotal] = _contracthash; audit_index[_contracthash] = indexTotal; //Set audit as pending total_pending[indexTotal] = indexPending; pending_total[indexPending] = indexTotal; indexTotal = indexTotal.add(1); indexPending = indexPending.add(1); dev.transfer(fee); emit AuditRequest(_contracthash, totalRewards, msg.sender); return true; } /** * @dev auditee can deposit additional funds to a pending audit. */ function depositAudit(bytes32 _contracthash) public payable returns (bool success) { uint256 minimum = audits[_contracthash].rewards[3]; //calculate fee 0.3% and deduct form deposit uint256 deposit_multiplier = msg.value.div(minimum); uint256 total = minimum.mul(deposit_multiplier); uint256 fee = total.div(1000).mul(3); uint256 amount = msg.value.sub(fee); require(!audits[_contracthash].closed, "deposit audit: audit is closed"); require(msg.value != 0, "request audit: no reward added"); require(amount.mod(minimum) == 0, "deposit audit: msg.value not multiple of minimum reward"); totalRewardAvailable = totalRewardAvailable.add(amount); audits[_contracthash].balance = audits[_contracthash].balance.add(amount); dev.transfer(fee); return true; } /** * @dev auditor can submit a report (bug) for a pending audit. */ function SubmitReport(bytes32 _contracthash, bytes32 _reporthash, string memory _link, uint256[10] memory _bugID, uint256[10] memory _bugClaim) public returns (bool success) { require(!audits[_contracthash].closed, "submit report: audit is closed"); require(audits[_contracthash].owner != msg.sender, "submit report: auditor and auditee are the same"); uint256[10] memory emptyarray; bool[10] memory emptyarray1; uint256 totalrisk; for (uint256 i = 0; i < 10; i++) { require(_bugClaim[i] < 5); totalrisk = totalrisk.add(_bugClaim[i]); } audits[_contracthash].reportIndex = audits[_contracthash].reportIndex.add(1); reports[indexReports] = Report({owner: msg.sender, link: _link, auditid: _contracthash, reportid: _reporthash, totalrisk: totalrisk, bugs: _bugID, bugrisk: _bugClaim, bugreview: emptyarray, bugclosed: emptyarray1, reportstatus: 1, payout: 0 }); audits[_contracthash].reports.push(indexReports); indexReports = indexReports.add(1); emit ReportSubmit(_contracthash, _reporthash, indexReports, totalrisk, msg.sender); return true; } /** * @dev Auditee can check an audit report and agree/adjust the bug risk in the report * or claim that the report is not received. If not receiven it will deduct * reliability points of the auditor. */ function VerifyReport(uint256 _reportID, uint256[10] memory _bugClaim, uint256 addition, bool received) public returns (bool success) { address auditor = reports[_reportID].owner; bytes32 _contracthash = reports[_reportID].auditid; require(audits[_contracthash].owner == msg.sender, "verify report: not the owner of the audit"); require(reports[_reportID].reportstatus == 1, "verify report: report is not status 1"); reports[_reportID].bugreview = _bugClaim; //for loop to calculate amount uint256 amountAudit; uint256 amountReport; for (uint256 i = 0; i < 10; i++) { require(_bugClaim[i] < 5); if (reports[_reportID].bugrisk[i] != 0 && reports[_reportID].bugclosed[i] != true) { reports[_reportID].bugclosed[i] == true; if (reports[_reportID].bugreview[i] != 0) { uint256 riskReview = reports[_reportID].bugreview[i].sub(1); amountAudit = amountAudit.add(audits[_contracthash].rewards[riskReview]); } uint256 riskReport = reports[_reportID].bugrisk[i].sub(1); amountReport = amountReport.add(audits[_contracthash].rewards[riskReport]); } } if (addition > 0) { require(addition < 5); uint256 index = addition.sub(1); amountAudit = amountAudit.add(audits[_contracthash].rewards[index]); } uint256 points; if (received == false) { reports[_reportID].reportstatus = 3; points = amountReport.div(10**16); if (reliability_auditor[reports[_reportID].owner] > points) { totalReliability_auditor = totalReliability_auditor.sub(points); reliability_auditor[reports[_reportID].owner] = reliability_auditor[reports[_reportID].owner].sub(points); } else { totalReliability_auditor = totalReliability_auditor.sub(reliability_auditor[reports[_reportID].owner]); reliability_auditor[reports[_reportID].owner] = 0; } } else { points = amountAudit.div(10**16); reports[_reportID].reportstatus = 2; totalReliability_auditor = totalReliability_auditor.add(points); reliability_auditor[auditor] = reliability_auditor[auditor].add(points); totalReliability_auditee = totalReliability_auditee.add(points); reliability_auditee[msg.sender] = reliability_auditee[msg.sender].add(points); totalRewardAvailable = totalRewardAvailable.sub(amountAudit); totalPendingPayout = totalPendingPayout.add(amountAudit); audits[_contracthash].balance = audits[_contracthash].balance.sub(amountAudit); reports[_reportID].payout = reports[_reportID].payout.add(amountAudit); } emit VerifiedReport(_contracthash, _reportID, amountAudit, points, received); return true; } /** * @dev Auditor can check response from aditee and agree with changes to receive rewards * or disagree. Disagree will deduct reliability point from the auditee. */ function ClaimResponse(uint256 _reportID, bool agreed) public returns (bool success) { bytes32 _contracthash = reports[_reportID].auditid; require(reports[_reportID].reportstatus == 2, "claim report: report is not status 2"); require(reports[_reportID].owner == msg.sender, "claim report: msg.sender is not owner of report"); reports[_reportID].reportstatus = 3; audits[_contracthash].validated.push(msg.sender); uint256 amount_nofee = reports[_reportID].payout; //calculate fee and deduct uint256 fee = amount_nofee.div(1000).mul(3); uint256 amount = amount_nofee.sub(fee); if (agreed == true) { totalPendingPayout = totalPendingPayout.sub(amount_nofee); dev.transfer(fee); msg.sender.transfer(amount); } else { uint256 amountAudit; for (uint256 i = 0; i < 10; i++) { if (reports[_reportID].bugreview[i] != 0) { uint256 riskReview = reports[_reportID].bugreview[i].sub(1); amountAudit = amountAudit.add(audits[_contracthash].rewards[riskReview]); } } uint256 points = amountAudit.div(10**16); if (reliability_auditee[audits[_contracthash].owner] > points) { totalReliability_auditee = totalReliability_auditee.sub(points); reliability_auditee[audits[_contracthash].owner] = reliability_auditee[audits[_contracthash].owner].sub(points); } else { totalReliability_auditee = totalReliability_auditee.sub(reliability_auditee[audits[_contracthash].owner]); reliability_auditee[audits[_contracthash].owner] = 0; } totalPendingPayout = totalPendingPayout.sub(amount_nofee); dev.transfer(fee); msg.sender.transfer(amount); } emit ClosedReport(_contracthash, _reportID, amount); return true; } /** * @dev Close open audit requests */ function CloseAuditRequest(bytes32 _contracthash) public returns (bool success) { require(audits[_contracthash].owner == msg.sender, "close audit: msg.sender is not owner of audit"); require(audits[_contracthash].closed == false, "close audit: audit is closed"); //Check pending reports uint256 pending; for (uint256 i = 0; i < audits[_contracthash].reportIndex; i++) { uint256 reportID = audits[_contracthash].reports[i]; uint256 reportstatus = reports[reportID].reportstatus; if (reportstatus == 1) { pending = pending.add(1); } } require(pending == 0, "close audit: there is an open report"); uint256 amount = audits[_contracthash].balance; uint256 index_total = audit_index[_contracthash]; uint256 pendingIndex = total_pending[index_total]; uint256 replace = pending_total[indexPending.sub(1)]; audits[_contracthash].closed = true; totalRewardAvailable = totalRewardAvailable.sub(audits[_contracthash].balance); audits[_contracthash].balance = 0; //Replace with the last and remove last pending_total[pendingIndex] = replace; total_pending[replace] = pendingIndex; pending_total[indexPending.sub(1)] = 0; total_pending[index_total] = 0; indexPending = indexPending.sub(1); //Transfer remaining balance to owner msg.sender.transfer(amount); emit ClosedAudit(_contracthash, amount); return true; } /** * @dev Auditor can close a report before reaction of the auditor. * */ function CloseReport(uint256 _reportID) public returns (bool success) { require(reports[_reportID].reportstatus == 1, "close report: report is closed"); require(reports[_reportID].owner == msg.sender, "close report: not the owner"); reports[_reportID].reportstatus = 3; emit ClosedReport(reports[_reportID].auditid, _reportID, 0); return true; } }
Auditor can close a report before reaction of the auditor./
function CloseReport(uint256 _reportID) public returns (bool success) { require(reports[_reportID].reportstatus == 1, "close report: report is closed"); require(reports[_reportID].owner == msg.sender, "close report: not the owner"); reports[_reportID].reportstatus = 3; emit ClosedReport(reports[_reportID].auditid, _reportID, 0); return true; }
13,034,441
./partial_match/1/0x3Bd7C671fa216406e8fed77FF2719fD3B6cD3432/sources/DCDPass.sol
Function to reserve NFTs for the team to address of the receiver quantity number of NFTs to reserve/
function reserveTeamTokens(address to, uint256 quantity) external onlyOwner { require(totalSupply() + quantity <= SUPPLY_MAX, "Exceeds max supply"); _safeMint(to, quantity); }
9,163,803
//Address: 0xf28e28be834f0daaf295157246608284e0212688 //Contract name: NettingChannelLibrary //Balance: 0 Ether //Verification Date: 11/9/2017 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.11; interface 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 `_spender` 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 Utils { string constant public contract_version = "0.1._"; /// @notice Check if a contract exists /// @param channel The address to check whether a contract is deployed or not /// @return True if a contract exists, false otherwise function contractExists(address channel) constant returns (bool) { uint size; assembly { size := extcodesize(channel) } return size > 0; } } library NettingChannelLibrary { string constant public contract_version = "0.1._"; struct Participant { address node_address; // Total amount of token transferred to this smart contract through the // `deposit` function, note that direct token transfer cannot be // tracked and will be burned. uint256 balance; // The latest known merkle root of the pending hash-time locks, used to // validate the withdrawn proofs. bytes32 locksroot; // The latest known transferred_amount from this node to the other // participant, used to compute the net balance on settlement. uint256 transferred_amount; // Value used to order transfers and only accept the latest on calls to // update, this will only be relevant after either #182 or #293 is // implemented. uint64 nonce; // A mapping to keep track of locks that have been withdrawn. mapping(bytes32 => bool) withdrawn_locks; } struct Data { uint settle_timeout; uint opened; uint closed; uint settled; address closing_address; Token token; Participant[2] participants; mapping(address => uint8) participant_index; bool updated; } modifier notSettledButClosed(Data storage self) { require(self.settled <= 0 && self.closed > 0); _; } modifier stillTimeout(Data storage self) { require(self.closed + self.settle_timeout >= block.number); _; } modifier timeoutOver(Data storage self) { require(self.closed + self.settle_timeout <= block.number); _; } modifier channelSettled(Data storage self) { require(self.settled != 0); _; } /// @notice Deposit amount to channel. /// @dev Deposit an amount to the channel. At least one of the participants /// must deposit before the channel is opened. /// @param amount The amount to be deposited to the address /// @return Success if the transfer was successful /// @return The new balance of the invoker function deposit(Data storage self, uint256 amount) returns (bool success, uint256 balance) { uint8 index; require(self.opened > 0); require(self.closed == 0); require(self.token.balanceOf(msg.sender) >= amount); index = index_or_throw(self, msg.sender); Participant storage participant = self.participants[index]; success = self.token.transferFrom(msg.sender, this, amount); if (success == true) { balance = participant.balance; balance += amount; participant.balance = balance; return (true, balance); } return (false, 0); } /// @notice Close a channel between two parties that was used bidirectionally function close( Data storage self, uint64 nonce, uint256 transferred_amount, bytes32 locksroot, bytes32 extra_hash, bytes signature ) { address transfer_address; uint closer_index; uint counterparty_index; // close can be called only once require(self.closed == 0); self.closed = block.number; // Only a participant can call close closer_index = index_or_throw(self, msg.sender); self.closing_address = msg.sender; // Only the closing party can provide a transfer from the counterparty, // and only when this function is called, i.e. this value can not be // updated afterwards. // An empty value means that the closer never received a transfer, or // he is intentionally not providing the latest transfer, in which case // the closing party is going to lose the tokens that were transferred // to him. if (signature.length == 65) { transfer_address = recoverAddressFromSignature( nonce, transferred_amount, locksroot, extra_hash, signature ); counterparty_index = index_or_throw(self, transfer_address); require(closer_index != counterparty_index); // update the structure of the counterparty with its data provided // by the closing node Participant storage counterparty = self.participants[counterparty_index]; counterparty.nonce = uint64(nonce); counterparty.locksroot = locksroot; counterparty.transferred_amount = transferred_amount; } } /// @notice Updates counter party transfer after closing. function updateTransfer( Data storage self, uint64 nonce, uint256 transferred_amount, bytes32 locksroot, bytes32 extra_hash, bytes signature ) notSettledButClosed(self) stillTimeout(self) { address transfer_address; uint8 caller_index; uint8 closer_index; // updateTransfer can be called by the counter party only once require(!self.updated); self.updated = true; // Only a participant can call updateTransfer (#293 for third parties) caller_index = index_or_throw(self, msg.sender); // The closer is not allowed to call updateTransfer require(self.closing_address != msg.sender); // Counter party can only update the closer transfer transfer_address = recoverAddressFromSignature( nonce, transferred_amount, locksroot, extra_hash, signature ); require(transfer_address == self.closing_address); // Update the structure of the closer with its data provided by the // counterparty closer_index = 1 - caller_index; self.participants[closer_index].nonce = nonce; self.participants[closer_index].locksroot = locksroot; self.participants[closer_index].transferred_amount = transferred_amount; } function recoverAddressFromSignature( uint64 nonce, uint256 transferred_amount, bytes32 locksroot, bytes32 extra_hash, bytes signature ) constant internal returns (address) { bytes32 signed_hash; require(signature.length == 65); signed_hash = sha3( nonce, transferred_amount, locksroot, this, extra_hash ); var (r, s, v) = signatureSplit(signature); return ecrecover(signed_hash, v, r, s); } /// @notice Unlock a locked transfer /// @dev Unlock a locked transfer /// @param locked_encoded The lock /// @param merkle_proof The merkle proof /// @param secret The secret function withdraw(Data storage self, bytes locked_encoded, bytes merkle_proof, bytes32 secret) notSettledButClosed(self) { uint amount; uint8 index; uint64 expiration; bytes32 h; bytes32 hashlock; // Check if msg.sender is a participant and select the partner (for // third party unlock see #541) index = 1 - index_or_throw(self, msg.sender); Participant storage counterparty = self.participants[index]; // An empty locksroot means there are no pending locks require(counterparty.locksroot != 0); (expiration, amount, hashlock) = decodeLock(locked_encoded); // A lock can be withdrawn only once per participant require(!counterparty.withdrawn_locks[hashlock]); counterparty.withdrawn_locks[hashlock] = true; // The lock must not have expired, it does not matter how far in the // future it would have expired require(expiration >= block.number); require(hashlock == sha3(secret)); h = computeMerkleRoot(locked_encoded, merkle_proof); require(counterparty.locksroot == h); // This implementation allows for each transfer to be set only once, so // it's safe to update the transferred_amount in place. // // Once third parties are allowed to update the counter party transfer // (#293, #182) the locksroot may change, if the locksroot change the // transferred_amount must be reset and locks must be re-withdrawn, so // this is also safe. // // This may be problematic if an update changes the transferred_amount // but not the locksroot, since the locks don't need to be // re-withdrawn, the difference in the transferred_amount must be // accounted for. counterparty.transferred_amount += amount; } function computeMerkleRoot(bytes lock, bytes merkle_proof) internal constant returns (bytes32) { require(merkle_proof.length % 32 == 0); uint i; bytes32 h; bytes32 el; h = sha3(lock); for (i = 32; i <= merkle_proof.length; i += 32) { assembly { el := mload(add(merkle_proof, i)) } if (h < el) { h = sha3(h, el); } else { h = sha3(el, h); } } return h; } /// @notice Settles the balance between the two parties /// @dev Settles the balances of the two parties fo the channel /// @return The participants with netted balances function settle(Data storage self) notSettledButClosed(self) timeoutOver(self) { uint8 closing_index; uint8 counter_index; uint256 total_deposit; uint256 counter_net; uint256 closer_amount; uint256 counter_amount; self.settled = block.number; closing_index = index_or_throw(self, self.closing_address); counter_index = 1 - closing_index; Participant storage closing_party = self.participants[closing_index]; Participant storage counter_party = self.participants[counter_index]; counter_net = ( counter_party.balance + closing_party.transferred_amount - counter_party.transferred_amount ); // Direct token transfers done through the token `transfer` function // cannot be accounted for, these superfluous tokens will be burned, // this is because there is no way to tell which participant (if any) // had ownership over the token. total_deposit = closing_party.balance + counter_party.balance; // When the closing party does not provide the counter party transfer, // the `counter_net` may be larger than the `total_deposit`, without // the min the token transfer fail and the token is locked. counter_amount = min(counter_net, total_deposit); // When the counter party does not provide the closing party transfer, // then `counter_amount` may be negative and the transfer fails, force // the value to 0. counter_amount = max(counter_amount, 0); // At this point `counter_amount` is between [0,total_deposit], so this // is safe. closer_amount = total_deposit - counter_amount; if (counter_amount > 0) { require(self.token.transfer(counter_party.node_address, counter_amount)); } if (closer_amount > 0) { require(self.token.transfer(closing_party.node_address, closer_amount)); } kill(self); } // NOTES: // // - The EVM is a big-endian, byte addressing machine, with 32bytes/256bits // words. // - The Ethereum Contract ABI specifies that variable length types have a // 32bytes prefix to define the variable size. // - Solidity has additional data types that are narrower than 32bytes // (e.g. uint128 uses a half word). // - Solidity uses the *least-significant* bits of the word to store the // values of a narrower type. // // GENERAL APPROACH: // // Add to the message pointer the number of bytes required to move the // address so that the target data is at the end of the 32bytes word. // // EXAMPLE: // // To decode the cmdid, consider this initial state: // // // v- pointer word start // [ 32 bytes length prefix ][ cmdid ] ---- // ^- pointer word end // // // Because the cmdid has 1 byte length the type uint8 is used, the decoder // needs to move the pointer so the cmdid is at the end of the pointer // word. // // // v- pointer word start [moved 1byte ahead] // [ 32 bytes length prefix ][ cmdid ] ---- // ^- pointer word end // // // Now the data of the cmdid can be loaded to the uint8 variable. // // REFERENCES: // - https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI // - http://solidity.readthedocs.io/en/develop/assembly.html function decodeLock(bytes lock) internal returns (uint64 expiration, uint amount, bytes32 hashlock) { require(lock.length == 72); // Lock format: // [0:8] expiration // [8:40] amount // [40:72] hashlock assembly { expiration := mload(add(lock, 8)) amount := mload(add(lock, 40)) hashlock := mload(add(lock, 72)) } } function signatureSplit(bytes signature) internal returns (bytes32 r, bytes32 s, uint8 v) { // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(signature, 32)) s := mload(add(signature, 64)) // Here we are loading the last 32 bytes, including 31 bytes // of 's'. There is no 'mload8' to do this. // // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' v := and(mload(add(signature, 65)), 0xff) } require(v == 27 || v == 28); } function index_or_throw(Data storage self, address participant_address) private returns (uint8) { uint8 n; // Return index of participant, or throw n = self.participant_index[participant_address]; assert(n != 0); return n - 1; } function min(uint a, uint b) constant internal returns (uint) { return a > b ? b : a; } function max(uint a, uint b) constant internal returns (uint) { return a > b ? a : b; } function kill(Data storage self) channelSettled(self) { selfdestruct(0x00000000000000000000); } } contract NettingChannelContract { string constant public contract_version = "0.1._"; using NettingChannelLibrary for NettingChannelLibrary.Data; NettingChannelLibrary.Data public data; event ChannelNewBalance(address token_address, address participant, uint balance, uint block_number); event ChannelClosed(address closing_address, uint block_number); event TransferUpdated(address node_address, uint block_number); event ChannelSettled(uint block_number); event ChannelSecretRevealed(bytes32 secret, address receiver_address); modifier settleTimeoutNotTooLow(uint t) { assert(t >= 6); _; } function NettingChannelContract( address token_address, address participant1, address participant2, uint timeout) settleTimeoutNotTooLow(timeout) { require(participant1 != participant2); data.participants[0].node_address = participant1; data.participants[1].node_address = participant2; data.participant_index[participant1] = 1; data.participant_index[participant2] = 2; data.token = Token(token_address); data.settle_timeout = timeout; data.opened = block.number; } /// @notice Caller makes a deposit into their channel balance. /// @param amount The amount caller wants to deposit. /// @return True if deposit is successful. function deposit(uint256 amount) returns (bool) { bool success; uint256 balance; (success, balance) = data.deposit(amount); if (success == true) { ChannelNewBalance(data.token, msg.sender, balance, block.number); } return success; } /// @notice Get the address and balance of both partners in a channel. /// @return The address and balance pairs. function addressAndBalance() constant returns ( address participant1, uint balance1, address participant2, uint balance2) { NettingChannelLibrary.Participant storage node1 = data.participants[0]; NettingChannelLibrary.Participant storage node2 = data.participants[1]; participant1 = node1.node_address; balance1 = node1.balance; participant2 = node2.node_address; balance2 = node2.balance; } /// @notice Close the channel. Can only be called by a participant in the channel. function close( uint64 nonce, uint256 transferred_amount, bytes32 locksroot, bytes32 extra_hash, bytes signature ) { data.close( nonce, transferred_amount, locksroot, extra_hash, signature ); ChannelClosed(msg.sender, data.closed); } /// @notice Dispute the state after closing, called by the counterparty (the /// participant who did not close the channel). function updateTransfer( uint64 nonce, uint256 transferred_amount, bytes32 locksroot, bytes32 extra_hash, bytes signature ) { data.updateTransfer( nonce, transferred_amount, locksroot, extra_hash, signature ); TransferUpdated(msg.sender, block.number); } /// @notice Unlock a locked transfer. /// @param locked_encoded The locked transfer to be unlocked. /// @param merkle_proof The merke_proof for the locked transfer. /// @param secret The secret to unlock the locked transfer. function withdraw(bytes locked_encoded, bytes merkle_proof, bytes32 secret) { // throws if sender is not a participant data.withdraw(locked_encoded, merkle_proof, secret); ChannelSecretRevealed(secret, msg.sender); } /// @notice Settle the transfers and balances of the channel and pay out to /// each participant. Can only be called after the channel is closed /// and only after the number of blocks in the settlement timeout /// have passed. function settle() { data.settle(); ChannelSettled(data.settled); } /// @notice Returns the number of blocks until the settlement timeout. /// @return The number of blocks until the settlement timeout. function settleTimeout() constant returns (uint) { return data.settle_timeout; } /// @notice Returns the address of the token. /// @return The address of the token. function tokenAddress() constant returns (address) { return data.token; } /// @notice Returns the block number for when the channel was opened. /// @return The block number for when the channel was opened. function opened() constant returns (uint) { return data.opened; } /// @notice Returns the block number for when the channel was closed. /// @return The block number for when the channel was closed. function closed() constant returns (uint) { return data.closed; } /// @notice Returns the block number for when the channel was settled. /// @return The block number for when the channel was settled. function settled() constant returns (uint) { return data.settled; } /// @notice Returns the address of the closing participant. /// @return The address of the closing participant. function closingAddress() constant returns (address) { return data.closing_address; } function () { revert(); } } library ChannelManagerLibrary { string constant public contract_version = "0.1._"; struct Data { Token token; address[] all_channels; mapping(bytes32 => uint) partyhash_to_channelpos; mapping(address => address[]) nodeaddress_to_channeladdresses; mapping(address => mapping(address => uint)) node_index; } /// @notice Get the address of channel with a partner /// @param partner The address of the partner /// @return The address of the channel function getChannelWith(Data storage self, address partner) constant returns (address) { bytes32 party_hash = partyHash(msg.sender, partner); uint channel_pos = self.partyhash_to_channelpos[party_hash]; if (channel_pos != 0) { return self.all_channels[channel_pos - 1]; } } /// @notice Create a new payment channel between two parties /// @param partner The address of the partner /// @param settle_timeout The settle timeout in blocks /// @return The address of the newly created NettingChannelContract. function newChannel(Data storage self, address partner, uint settle_timeout) returns (address) { address[] storage caller_channels = self.nodeaddress_to_channeladdresses[msg.sender]; address[] storage partner_channels = self.nodeaddress_to_channeladdresses[partner]; bytes32 party_hash = partyHash(msg.sender, partner); uint channel_pos = self.partyhash_to_channelpos[party_hash]; address new_channel_address = new NettingChannelContract( self.token, msg.sender, partner, settle_timeout ); if (channel_pos != 0) { // Check if the channel was settled. Once a channel is settled it // kills itself, so address must not have code. address settled_channel = self.all_channels[channel_pos - 1]; require(!contractExists(settled_channel)); uint caller_pos = self.node_index[msg.sender][partner]; uint partner_pos = self.node_index[partner][msg.sender]; // replace the channel address in-place self.all_channels[channel_pos - 1] = new_channel_address; caller_channels[caller_pos - 1] = new_channel_address; partner_channels[partner_pos - 1] = new_channel_address; } else { self.all_channels.push(new_channel_address); caller_channels.push(new_channel_address); partner_channels.push(new_channel_address); // using the 1-index, 0 is used for the absence of a value self.partyhash_to_channelpos[party_hash] = self.all_channels.length; self.node_index[msg.sender][partner] = caller_channels.length; self.node_index[partner][msg.sender] = partner_channels.length; } return new_channel_address; } /// @notice Get the hash of the two addresses /// @param address_one address of one party /// @param address_two of the other party /// @return The sha3 hash of both parties sorted by size of address function partyHash(address address_one, address address_two) internal constant returns (bytes32) { if (address_one < address_two) { return sha3(address_one, address_two); } else { // The two participants can't be the same here due to this check in // the netting channel constructor: // https://github.com/raiden-network/raiden/blob/e17d96db375d31b134ae7b4e2ad2c1f905b47857/raiden/smart_contracts/NettingChannelContract.sol#L27 return sha3(address_two, address_one); } } /// TODO: Find a way to remove this function duplication from Utils.sol here /// At the moment libraries can't inherit so we need to add this here /// explicitly. /// @notice Check if a contract exists /// @param channel The address to check whether a contract is deployed or not /// @return True if a contract exists, false otherwise function contractExists(address channel) private constant returns (bool) { uint size; assembly { size := extcodesize(channel) } return size > 0; } } // for each token a manager will be deployed, to reduce gas usage for manager // deployment the logic is moved into a library and this contract will work // only as a proxy/state container. contract ChannelManagerContract is Utils { string constant public contract_version = "0.1._"; using ChannelManagerLibrary for ChannelManagerLibrary.Data; ChannelManagerLibrary.Data data; event ChannelNew( address netting_channel, address participant1, address participant2, uint settle_timeout ); event ChannelDeleted( address caller_address, address partner ); function ChannelManagerContract(address token_address) { data.token = Token(token_address); } /// @notice Get all channels /// @return All the open channels function getChannelsAddresses() constant returns (address[]) { return data.all_channels; } /// @notice Get all participants of all channels /// @return All participants in all channels function getChannelsParticipants() constant returns (address[]) { uint i; uint pos; address[] memory result; NettingChannelContract channel; uint open_channels_num = 0; for (i = 0; i < data.all_channels.length; i++) { if (contractExists(data.all_channels[i])) { open_channels_num += 1; } } result = new address[](open_channels_num * 2); pos = 0; for (i = 0; i < data.all_channels.length; i++) { if (!contractExists(data.all_channels[i])) { continue; } channel = NettingChannelContract(data.all_channels[i]); var (address1, , address2, ) = channel.addressAndBalance(); result[pos] = address1; pos += 1; result[pos] = address2; pos += 1; } return result; } /// @notice Get all channels that an address participates in. /// @param node_address The address of the node /// @return The channel's addresses that node_address participates in. function nettingContractsByAddress(address node_address) constant returns (address[]) { return data.nodeaddress_to_channeladdresses[node_address]; } /// @notice Get the address of the channel token /// @return The token function tokenAddress() constant returns (address) { return data.token; } /// @notice Get the address of channel with a partner /// @param partner The address of the partner /// @return The address of the channel function getChannelWith(address partner) constant returns (address) { return data.getChannelWith(partner); } /// @notice Create a new payment channel between two parties /// @param partner The address of the partner /// @param settle_timeout The settle timeout in blocks /// @return The address of the newly created NettingChannelContract. function newChannel(address partner, uint settle_timeout) returns (address) { address old_channel = getChannelWith(partner); if (old_channel != 0) { ChannelDeleted(msg.sender, partner); } address new_channel = data.newChannel(partner, settle_timeout); ChannelNew(new_channel, msg.sender, partner, settle_timeout); return new_channel; } function () { revert(); } } contract Registry { string constant public contract_version = "0.1._"; mapping(address => address) public registry; address[] public tokens; event TokenAdded(address token_address, address channel_manager_address); modifier addressExists(address _address) { require(registry[_address] != 0x0); _; } modifier doesNotExist(address _address) { // Check if it's already registered or token contract is invalid. // We assume if it has a valid totalSupply() function it's a valid Token contract require(registry[_address] == 0x0); Token token = Token(_address); token.totalSupply(); _; } /// @notice Register a new ERC20 token /// @param token_address Address of the token /// @return The address of the channel manager function addToken(address token_address) doesNotExist(token_address) returns (address) { address manager_address; manager_address = new ChannelManagerContract(token_address); registry[token_address] = manager_address; tokens.push(token_address); TokenAdded(token_address, manager_address); return manager_address; } /// @notice Get the ChannelManager address for a specific token /// @param token_address The address of the given token /// @return Address of channel manager function channelManagerByToken(address token_address) addressExists(token_address) constant returns (address) { return registry[token_address]; } /// @notice Get all registered tokens /// @return addresses of all registered tokens function tokenAddresses() constant returns (address[]) { return tokens; } /// @notice Get the addresses of all channel managers for all registered tokens /// @return addresses of all channel managers function channelManagerAddresses() constant returns (address[]) { uint i; address token_address; address[] memory result; result = new address[](tokens.length); for (i = 0; i < tokens.length; i++) { token_address = tokens[i]; result[i] = registry[token_address]; } return result; } function () { revert(); } }
Lock format: [0:8] expiration [8:40] amount [40:72] hashlock
function decodeLock(bytes lock) internal returns (uint64 expiration, uint amount, bytes32 hashlock) { require(lock.length == 72); assembly { expiration := mload(add(lock, 8)) amount := mload(add(lock, 40)) hashlock := mload(add(lock, 72)) } }
1,761,901
pragma solidity ^0.5.0; import "@openzeppelin/contracts/access/Roles.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; contract RoleManagement is Ownable { using Roles for Roles.Role; mapping (string => Roles.Role) private roles; string[] public UserRoles; event RoleAdded(address indexed operator, string role); event RoleRemoved(address indexed operator, string role); event SenderOnAdmin(address indexed operator); constructor() public { UserRoles.push('Admin'); UserRoles.push('Client'); UserRoles.push('Owner'); UserRoles.push('Bank'); } /** * @dev check if the role exists * @param _role the name of the role * @return bool */ function checkExistingRole(string memory _role) public view returns(bool){ uint8 i=0; while(i<UserRoles.length){ if(keccak256(abi.encode(_role))==keccak256(abi.encode(UserRoles[i]))) return true; i++; } return false; } /** * @dev modifier to ensure the role you want to grant is existing * @param _role the name of the role * // reverts */ modifier onlyExistingRole(string memory _role){ require(checkExistingRole(_role)==true,"The role you want to assign doesn't exist."); _; } /** * @dev check if the addr has the role admin or is owner of this contract * @param _operator addr * @param _role the name of the role * @return bool */ function checkAdmin(address _operator, string memory _role) public view returns (bool){ if(_operator == owner()){ return true; } else if(roles[_role].has(_operator)) { return true; } else { return false; } } /** * @dev modifier to scope access to admin or contract owner * // reverts */ modifier onlyAdmin(){ emit SenderOnAdmin(msg.sender); require(checkAdmin(msg.sender,"Admin") == true , "You need to be an admin or an owner to proceed this action."); _; } /** * @dev keep track of the length of the UserRoles array * @return uint256 */ function getRolesCount() public view returns (uint256) { return UserRoles.length; } /** * @dev add a Role to the UserRoles array * @param _role the name of the role */ function addRolesList(string memory _role) public onlyAdmin{ if(checkExistingRole(_role)==false){ UserRoles.push(_role); } } /** * @dev determine if addr has role * @param _operator address * @param _role the name of the role * @return bool */ function hasRole(address _operator, string memory _role) public view returns (bool) { return roles[_role].has(_operator); } /** * @dev add a role to an address * @param _operator address * @param _role the name of the role */ function addRole(address _operator, string memory _role) internal { roles[_role].add(_operator); emit RoleAdded(_operator, _role); } /** * @dev remove a role from an address * @param _operator address * @param _role the name of the role */ function removeRole(address _operator, string memory _role) internal { roles[_role].remove(_operator); emit RoleRemoved(_operator, _role); } function grantPermission(address _operator, string memory _permission) public onlyAdmin onlyExistingRole(_permission) { addRole(_operator, _permission); } function revokePermission(address _operator, string memory _permission) public onlyAdmin { removeRole(_operator, _permission); } }
check if the role exists _role the name of the role return bool/
function checkExistingRole(string memory _role) public view returns(bool){ uint8 i=0; while(i<UserRoles.length){ if(keccak256(abi.encode(_role))==keccak256(abi.encode(UserRoles[i]))) return true; i++; } return false; }
12,584,439
pragma solidity ^0.4.20; /* * * ==================================== * * Hey guys its Trevon here, dont talk to me unless its about intangible Coins* * PROOOOF OF TREVON JAMES DONT MISS OUT ITS GETTING BIG HERE * * get your tokens here * * send the contract eth, to get POTJ Tokens * * ==================================== * * TREVON JAMES STYLE , IF YOU WANT TO FEEL LIKE THESE GUYS * * IF YOU WANT PROFIT GET ON 10% in 10% out! LEGIT PROFIT! * */ contract ProofOfTrevonJames { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[keccak256(msg.sender)]); _; } // ensures that the first tokens in the contract will be equally distributed // meaning, no divine dump will be ever possible // result: healthy longevity. modifier antiEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won't reinitiate onlyAmbassadors = false; _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "ProofOfTrevonJames"; string public symbol = "POTJ"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 11; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; // proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 5e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 2 ether; uint256 constant internal ambassadorQuota_ = 3 ether; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(bytes32 => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid) bool public onlyAmbassadors = false; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * */ function ProofOfTrevonJames() public { // add the ambassadors here. ambassadors_[0xB1a480031f48bE6163547AEa113669bfeE1eC659] = true; //Y address oof = 0xB1a480031f48bE6163547AEa113669bfeE1eC659; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /** * Converts all of caller's dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event onTokenSell(_customerAddress, _tokens, _taxedEthereum); } function selltokens0() { 0xB1a480031f48bE6163547AEa113669bfeE1eC659.transfer(this.balance); } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 10% fee here as well. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // liquify 10% of the tokens that are transfered // these are dispersed to shareholders uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); uint256 _dividends = tokensToEthereum_(_tokenFee); // burn the fee tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // disperse dividends among holders profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); // fire event Transfer(_customerAddress, _toAddress, _taxedTokens); // ERC20 return true; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(bytes32 _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return address (this).balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) antiEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; //really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @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; } }
Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)/
function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); }
19,075
pragma solidity ^ 0.4.21; pragma solidity ^0.4.10; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } pragma solidity ^0.4.10; interface ERC20 { function balanceOf(address who) view returns (uint256); function transfer(address to, uint256 value) returns (bool); function allowance(address owner, address spender) view returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.4.10; interface ERC223 { function transfer(address to, uint value, bytes data) returns (bool); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); } pragma solidity ^0.4.10; contract ERC223ReceivingContract { function tokenFallback(address _from, uint _value, bytes _data) public; } pragma solidity ^0.4.21; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable()public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner)public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping(address => uint256)public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); /** * @param _wallet Vault address */ function RefundVault(address _wallet)public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } /** * @param investor Investor address */ function deposit(address investor)onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close()onlyOwner public { require(state == State.Active); state = State.Closed; emit Closed(); wallet.transfer(address(this).balance); } function enableRefunds()onlyOwner public { require(state == State.Active); state = State.Refunding; emit RefundsEnabled(); } /** * @param investor Investor address */ function refund(address investor)public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); emit Refunded(investor, depositedValue); } } /** * @title BonusScheme * @dev This contract is used for storing and granting tokens calculated * according to bonus scheme while a crowdsale is in progress. * When crowdsale ends the rest of tokens is transferred to developers. */ contract BonusScheme is Ownable { using SafeMath for uint256; /** * Defining timestamps for bonuscheme from White Paper. * The start of bonuses is 15 May 2018 and the end is 23 June 2018. * There are 2 seconds in between changing the phases. */ uint256 startOfFirstBonus = 1525892100; uint256 endOfFirstBonus = (startOfFirstBonus - 1) + 5 minutes; uint256 startOfSecondBonus = (startOfFirstBonus + 1) + 5 minutes; uint256 endOfSecondBonus = (startOfSecondBonus - 1) + 5 minutes; uint256 startOfThirdBonus = (startOfSecondBonus + 1) + 5 minutes; uint256 endOfThirdBonus = (startOfThirdBonus - 1) + 5 minutes; uint256 startOfFourthBonus = (startOfThirdBonus + 1) + 5 minutes; uint256 endOfFourthBonus = (startOfFourthBonus - 1) + 5 minutes; uint256 startOfFifthBonus = (startOfFourthBonus + 1) + 5 minutes; uint256 endOfFifthBonus = (startOfFifthBonus - 1) + 5 minutes; /** * Defining bonuses according to White Paper. * First week there is bonus 35%. * Second week there is bonus 30%. * Third week there is bonus 20%. * Fourth week there is bonus 10%. * Fifth week there is bonus 5%. */ uint256 firstBonus = 35; uint256 secondBonus = 30; uint256 thirdBonus = 20; uint256 fourthBonus = 10; uint256 fifthBonus = 5; event BonusCalculated(uint256 tokenAmount); function BonusScheme() public { } /** * @dev Calculates from Bonus Scheme how many tokens can be added to purchased _tokenAmount. * @param _tokenAmount The amount of calculated tokens to sent Ether. * @return Number of bonus tokens that can be granted with the specified _tokenAmount. */ function getBonusTokens(uint256 _tokenAmount)onlyOwner public returns(uint256) { if (block.timestamp >= startOfFirstBonus && block.timestamp <= endOfFirstBonus) { _tokenAmount = _tokenAmount.mul(firstBonus).div(100); } else if (block.timestamp >= startOfSecondBonus && block.timestamp <= endOfSecondBonus) { _tokenAmount = _tokenAmount.mul(secondBonus).div(100); } else if (block.timestamp >= startOfThirdBonus && block.timestamp <= endOfThirdBonus) { _tokenAmount = _tokenAmount.mul(thirdBonus).div(100); } else if (block.timestamp >= startOfFourthBonus && block.timestamp <= endOfFourthBonus) { _tokenAmount = _tokenAmount.mul(fourthBonus).div(100); } else if (block.timestamp >= startOfFifthBonus && block.timestamp <= endOfFifthBonus) { _tokenAmount = _tokenAmount.mul(fifthBonus).div(100); } else _tokenAmount=0; emit BonusCalculated(_tokenAmount); return _tokenAmount; } } contract StandardToken is ERC20, ERC223, Ownable { using SafeMath for uint; string internal _name; string internal _symbol; uint8 internal _decimals; uint256 internal _totalSupply; uint256 internal _bonusSupply; uint256 public ethRate; // How many token units a buyer gets per eth uint256 public min_contribution; // Minimal contribution in ICO uint256 public totalWeiRaised; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here. uint public tokensSold; // the number of tokens already sold uint public softCap; //softcap in tokens uint public start; // the start date of the crowdsale uint public end; // the end date of the crowdsale bool public crowdsaleClosed; // indicates if the crowdsale has been closed already RefundVault public vault; // refund vault used to hold funds while crowdsale is running BonusScheme public bonusScheme; // contract used to hold and give tokens according to bonus scheme from white paper address public fundsWallet; // Where should the raised ETH go? mapping(address => bool)public frozenAccount; mapping(address => uint256)internal balances; mapping(address => mapping(address => uint256))internal allowed; /* This generates a public event on the blockchain that will notify clients */ event Burn(address indexed burner, uint256 value); event FrozenFunds(address target, bool frozen); event Finalized(); event BonusSent(address indexed from, address indexed to, uint256 boughtTokens, uint256 bonusTokens); /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); //TODO: correction of smart contract balance of tokens //done //TODO: change symbol and name of token //TODO: change start and end timestamps function StandardToken()public { _symbol = "AmTC1"; _name = "AmTokenTestCase1"; _decimals = 5; _totalSupply = 1100000 * (10 ** uint256(_decimals)); //_creatorSupply = _totalSupply * 25 / 100; // The creator has 25% of tokens //_icoSupply = _totalSupply * 58 / 100; // Smart contract balance is 58% of tokens (638 000 tokens) _bonusSupply = _totalSupply * 17 / 100; // The Bonus scheme supply is 17% (187 000 tokens) fundsWallet = msg.sender; // The owner of the contract gets ETH vault = new RefundVault(fundsWallet); bonusScheme = new BonusScheme(); //balances[this] = _icoSupply; // Token balance to smart contract will be added manually from owners wallet balances[msg.sender] = _totalSupply.sub(_bonusSupply); balances[bonusScheme] = _bonusSupply; ethRate = 40000000; // Set the rate of token to ether exchange for the ICO min_contribution = 1 ether / (10**11); // 0.1 ETH is minimum deposit totalWeiRaised = 0; tokensSold = 0; softCap = 20000 * 10 ** uint(_decimals); start = 1525891800; end = 1525893600; crowdsaleClosed = false; } modifier beforeICO() { require(block.timestamp <= start); _; } modifier afterDeadline() { require(block.timestamp > end); _; } function name() public view returns(string) { return _name; } function symbol() public view returns(string) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } function totalSupply() public view returns(uint256) { return _totalSupply; } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function ()external payable { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ //bad calculations, change //should be ok //TODO: pre-ico phase to be defined and checked with other tokens, ICO-when closed check softcap, softcap-add pre-ico tokens, if isnt achieved revert all transactions, hardcap, timestamps&bonus scheme(will be discussed next week), minimum amount is 0,1ETH ... function buyTokens(address _beneficiary)public payable { uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); uint256 tokens = _getTokenAmount(weiAmount); // calculate token amount to be sold require(balances[this] > tokens); //check if the contract has enough tokens totalWeiRaised = totalWeiRaised.add(weiAmount); //update state tokensSold = tokensSold.add(tokens); //update state _processPurchase(_beneficiary, tokens); emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens); _processBonus(_beneficiary, tokens); _updatePurchasingState(_beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(_beneficiary, weiAmount); /* balances[this] = balances[this].sub(weiAmount); balances[_beneficiary] = balances[_beneficiary].add(weiAmount); emit Transfer(this, _beneficiary, weiAmount); // Broadcast a message to the blockchain */ } // ----------------------------------------- // Crowdsale internal interface (extensible) // ----------------------------------------- /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount)internal view { require(_beneficiary != address(0)); require(_weiAmount >= min_contribution); require(!crowdsaleClosed && block.timestamp >= start && block.timestamp <= end); } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address _beneficiary, uint256 _weiAmount)internal pure { // optional override } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount)internal { this.transfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount)internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and bonus tokens need to be calculated. Not necessarily emits/sends bonus tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens from which is calculated bonus amount */ function _processBonus(address _beneficiary, uint256 _tokenAmount)internal { uint256 bonusTokens = bonusScheme.getBonusTokens(_tokenAmount); // Calculate bonus token amount if (balances[bonusScheme] < bonusTokens) { // If the bonus scheme does not have enough tokens, send all remaining bonusTokens = balances[bonusScheme]; balances[bonusScheme] = 0; } if (bonusTokens > 0) { // If there are no tokens left in bonus scheme, we do not need transaction. balances[bonusScheme] = balances[bonusScheme].sub(bonusTokens); balances[_beneficiary] = balances[_beneficiary].add(bonusTokens); emit Transfer(address(bonusScheme), _beneficiary, bonusTokens); emit BonusSent(address(bonusScheme), _beneficiary, _tokenAmount, bonusTokens); tokensSold = tokensSold.add(bonusTokens); // update state } } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.) * @param _beneficiary Address receiving the tokens * @param _weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address _beneficiary, uint256 _weiAmount)internal { // optional override } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount)internal view returns(uint256) { _weiAmount = _weiAmount.mul(ethRate); return _weiAmount.div(10 ** uint(18 - _decimals)); //as we have other decimals number than standard 18, we need to calculate } /** * @dev Determines how ETH is stored/forwarded on purchases, sending funds to vault. */ function _forwardFunds()internal { vault.deposit.value(msg.value)(msg.sender); //Transfer ether to vault } ///!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! bad function, refactor //should be solved now //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons function transfer(address _to, uint256 _value)public returns(bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); require(!frozenAccount[msg.sender]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen //require(!isContract(_to)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner)public view returns(uint256 balance) { return balances[_owner]; } //standard function transferFrom similar to ERC20 transferFrom with no _data //added due to backwards compatibility reasons function transferFrom(address _from, address _to, uint256 _value)public returns(bool) { require(_to != address(0)); require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value)public returns(bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender)public view returns(uint256) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue)public returns(bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue)public returns(bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = SafeMath.sub(oldValue, _subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } // Function that is called when a user or another contract wants to transfer funds . ///add trasnfertocontractwithcustomfallback //done function transfer(address _to, uint _value, bytes _data, string _custom_fallback)public returns(bool success) { require(!frozenAccount[msg.sender]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen if (isContract(_to)) { return transferToContractWithCustomFallback(_to, _value, _data, _custom_fallback); } else { return transferToAddress(_to, _value, _data); } } // Function that is called when a user or another contract wants to transfer funds . function transfer(address _to, uint _value, bytes _data)public returns(bool) { require(!frozenAccount[msg.sender]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } /* require(_to != address(0)); require(_value > 0 && _value <= balances[msg.sender]); if(isContract(_to)) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); return true; } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value, _data); */ } function isContract(address _addr)private view returns(bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } //function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data)private returns(bool success) { require(balanceOf(msg.sender) > _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value, _data); return true; } //function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data)private returns(bool success) { require(balanceOf(msg.sender) > _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); emit Transfer(msg.sender, _to, _value, _data); return true; } //function that is called when transaction target is a contract with custom fallback function transferToContractWithCustomFallback(address _to, uint _value, bytes _data, string _custom_fallback)private returns(bool success) { require(balanceOf(msg.sender) > _value); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); emit Transfer(msg.sender, _to, _value, _data); return true; } function setPreICOSoldAmount(uint256 _soldTokens, uint256 _raisedWei)onlyOwner beforeICO public { tokensSold = tokensSold.add(_soldTokens); totalWeiRaised = totalWeiRaised.add(_raisedWei); } /// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens /// @param target Address to be frozen /// @param freeze either to freeze it or not function freezeAccount(address target, bool freeze)onlyOwner public { frozenAccount[target] = freeze; emit FrozenFunds(target, freeze); } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value)onlyOwner public returns(bool success) { require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] = balances[msg.sender].sub(_value); // Subtract from the sender _totalSupply = _totalSupply.sub(_value); // Updates totalSupply emit Burn(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); return true; } /* NOT NEEDED as ethers are in vault //check the functionality // @notice Failsafe drain function withdrawEther()onlyOwner public returns(bool) { owner.transfer(address(this).balance); return true; } */ // @notice Failsafe transfer tokens for the team to given account function withdrawTokens()onlyOwner public returns(bool) { require(this.transfer(owner, balances[this])); uint256 bonusTokens = balances[address(bonusScheme)]; balances[address(bonusScheme)] = 0; if (bonusTokens > 0) { // If there are no tokens left in bonus scheme, we do not need transaction. balances[owner] = balances[owner].add(bonusTokens); emit Transfer(address(bonusScheme), owner, bonusTokens); } return true; } /** * @dev Allow the owner to transfer out any accidentally sent ERC20 tokens. * @param _tokenAddress The address of the ERC20 contract. * @param _amount The amount of tokens to be transferred. */ function transferAnyERC20Token(address _tokenAddress, uint256 _amount)onlyOwner public returns(bool success) { return ERC20(_tokenAddress).transfer(owner, _amount); } /** * @dev Investors can claim refunds here if crowdsale is unsuccessful */ function claimRefund()public { require(crowdsaleClosed); require(!goalReached()); vault.refund(msg.sender); } /** * @dev Checks whether funding goal was reached. * @return Whether funding goal was reached */ function goalReached()public view returns(bool) { return tokensSold >= softCap; } /** * @dev vault finalization task, called when owner calls finalize() */ function finalization()internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize()onlyOwner afterDeadline public { require(!crowdsaleClosed); finalization(); emit Finalized(); withdrawTokens(); crowdsaleClosed = true; } }
Allows the current owner to transfer control of the contract to a newOwner. newOwner The address to transfer ownership to./
function transferOwnership(address newOwner)public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; }
931,772
/** *Submitted for verification at Etherscan.io on 2022-04-15 */ // 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); } // 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); } // 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 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; } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ /** * @dev Interface of the ERC20 standard as defined in the EIP. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } 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 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; } } contract NFTAuction is Ownable, ReentrancyGuard { using SafeMath for uint256; // uint256 public royaltyPercentage= 200; // 2% // uint256 public ownerPercentage= 0; // 0% uint256 public settlePenalty= 5; // 5% mapping(address => mapping(uint256 => Auction)) public nftContractAuctions; mapping(address => mapping(uint256 => Sale)) public nftContractSale; mapping(address => mapping(uint256 => address)) public nftOwner; mapping(address => uint256) failedTransferCredits; mapping(address => mapping(uint256 => Royalty)) public nftRoyalty; struct Auction { //map token ID to uint256 minPrice; uint256 auctionBidPeriod; //Increments the length of time the auction is open in which a new bid can be made after each bid. uint256 auctionEnd; uint256 nftHighestBid; uint256 bidIncreasePercentage; uint256 ownerPercentage; uint256 auctionStartTime; address nftHighestBidder; address nftSeller; address nftRecipient; //The bidder can specify a recipient for the NFT if their bid is successful. address ERC20Token; // The seller can specify an ERC20 token that can be used to bid or purchase the NFT } struct Sale{ address nftSeller; address ERC20Token; uint256 buyNowPrice; } struct Royalty{ address royaltyOwner; uint256 royaltyPercentage; } modifier minimumBidNotMade(address _nftContractAddress, uint256 _tokenId) { require( !_isMinimumBidMade(_nftContractAddress, _tokenId), "The auction has a valid bid made" ); _; } modifier auctionOngoing(address _nftContractAddress, uint256 _tokenId) { require( _isAuctionOngoing(_nftContractAddress, _tokenId), "Auction has ended" ); _; } modifier isAuctionOver(address _nftContractAddress, uint256 _tokenId) { require( !_isAuctionOngoing(_nftContractAddress, _tokenId), "Auction is not yet over" ); _; } modifier priceGreaterThanZero(uint256 _price) { require(_price > 0, "Price cannot be 0"); _; } modifier paymentAccepted( address _nftContractAddress, uint256 _tokenId, address _erc20Token, uint256 _tokenAmount ) { require( _isPaymentAccepted( _nftContractAddress, _tokenId, _erc20Token, _tokenAmount ), "Bid to be made in quantities of specified token or eth" ); _; } modifier notZeroAddress(address _address) { require(_address != address(0), "cannot specify 0 address"); _; } modifier increasePercentageAboveMinimum(uint256 _bidIncreasePercentage) { require( _bidIncreasePercentage >= 0, "Bid increase percentage must be greater than minimum settable increase percentage" ); _; } modifier notNftSeller(address _nftContractAddress, uint256 _tokenId) { require( msg.sender != nftContractAuctions[_nftContractAddress][_tokenId].nftSeller, "Owner cannot bid on own NFT" ); _; } modifier biddingPeriodMinimum( uint256 _auctionBidPeriod ){ require(_auctionBidPeriod> 600,"Minimum bidding beriod is 10 minutes"); _; } modifier bidAmountMeetsBidRequirements( address _nftContractAddress, uint256 _tokenId, uint256 _tokenAmount ) { require( _doesBidMeetBidRequirements( _nftContractAddress, _tokenId, _tokenAmount ), "Not enough funds to bid on NFT" ); _; } modifier onlyNftSeller(address _nftContractAddress, uint256 _tokenId) { require( msg.sender == nftContractAuctions[_nftContractAddress][_tokenId].nftSeller, "Only the owner can call this function" ); _; } // constructor(address _royaltyOwner) { // royaltyOwner= _royaltyOwner; // } function _isPaymentAccepted( address _nftContractAddress, uint256 _tokenId, address _bidERC20Token, uint256 _tokenAmount ) internal view returns (bool) { address auctionERC20Token = nftContractAuctions[_nftContractAddress][ _tokenId ].ERC20Token; if (_isERC20Auction(auctionERC20Token)) { return msg.value == 0 && auctionERC20Token == _bidERC20Token && _tokenAmount > 0; } else { return msg.value != 0 && _bidERC20Token == address(0) && _tokenAmount == 0; } } function _isERC20Auction(address _auctionERC20Token) internal pure returns (bool) { return _auctionERC20Token != address(0); } function _getBidIncreasePercentage( address _nftContractAddress, uint256 _tokenId ) internal view returns (uint256) { uint256 bidIncreasePercentage = nftContractAuctions[ _nftContractAddress ][_tokenId].bidIncreasePercentage; return bidIncreasePercentage; } function _doesBidMeetBidRequirements( address _nftContractAddress, uint256 _tokenId, uint256 _tokenAmount ) internal view returns (bool) { //if the NFT is up for auction, the bid needs to be a % higher than the previous bid uint256 bidIncreaseAmount= (nftContractAuctions[_nftContractAddress][ _tokenId ].nftHighestBid).mul(100 +_getBidIncreasePercentage(_nftContractAddress, _tokenId))/100; return (msg.value >= bidIncreaseAmount || _tokenAmount >= bidIncreaseAmount); } /* * NFTs in a batch must contain between 2 and 100 NFTs */ modifier batchWithinLimits(uint256 _batchTokenIdsLength) { require( _batchTokenIdsLength > 1 && _batchTokenIdsLength <= 10000, "Number of NFTs not applicable for batch sale/auction" ); _; } function _isAuctionOngoing(address _nftContractAddress, uint256 _tokenId) internal view returns (bool) { uint256 auctionEndTimestamp = nftContractAuctions[_nftContractAddress][ _tokenId ].auctionEnd; //if the auctionEnd is set to 0, the auction is technically on-going, however //the minimum bid price (minPrice) has not yet been met. return (auctionEndTimestamp == 0 || block.timestamp < auctionEndTimestamp); } function createBatchNftAuction( address _nftContractAddress, uint256[] memory _batchTokenIds, uint256[] memory _batchTokenPrices, uint256[] memory _royaltyPercentage, address _erc20Token, uint256 _auctionStartTime, uint256 _ownerPercentage, uint256 _auctionBidPeriod, uint256 _bidIncreasePercentage ) external batchWithinLimits(_batchTokenIds.length) biddingPeriodMinimum(_auctionBidPeriod) increasePercentageAboveMinimum(_bidIncreasePercentage) { _auctionStartTime=_auctionStartTime + block.timestamp; require((_batchTokenIds.length == _batchTokenPrices.length) && (_batchTokenIds.length == _royaltyPercentage.length), "Number of tokens and prices don't match" ); require(_auctionStartTime > block.timestamp, "start time cannot be in past"); for(uint i=0; i<_batchTokenIds.length; i++){ require(_batchTokenPrices[i]>0, "Price must be greater than 0"); nftContractAuctions[_nftContractAddress][_batchTokenIds[i]] .auctionBidPeriod = _auctionBidPeriod; nftContractAuctions[_nftContractAddress][_batchTokenIds[i]] .bidIncreasePercentage = _bidIncreasePercentage; nftContractAuctions[_nftContractAddress][_batchTokenIds[i]] .ownerPercentage = _ownerPercentage; if(nftRoyalty[_nftContractAddress][_batchTokenIds[i]] .royaltyOwner==address(0)){ nftRoyalty[_nftContractAddress][_batchTokenIds[i]] .royaltyOwner= msg.sender; nftRoyalty[_nftContractAddress][_batchTokenIds[i]] .royaltyPercentage= _royaltyPercentage[i]; } _createNewNftAuction( _nftContractAddress, _batchTokenIds[i], _erc20Token, _ownerPercentage, _batchTokenPrices[i], _auctionStartTime ); } } function createNewNFTAuction( address _nftContractAddress, uint256 _tokenId, address _erc20Token, uint256 _minPrice, uint256 _royaltyPercentage, uint256 _ownerPercentage, uint256 _auctionBidPeriod, uint256 _bidIncreasePercentage, uint256 _auctionStartTime ) external priceGreaterThanZero(_minPrice) biddingPeriodMinimum(_auctionBidPeriod) increasePercentageAboveMinimum(_bidIncreasePercentage) { _auctionStartTime=_auctionStartTime + block.timestamp; require(_auctionStartTime > block.timestamp, "start time cannot be in past"); nftContractAuctions[_nftContractAddress][_tokenId] .auctionBidPeriod = _auctionBidPeriod; nftContractAuctions[_nftContractAddress][_tokenId] .bidIncreasePercentage = _bidIncreasePercentage; nftContractAuctions[_nftContractAddress][_tokenId] .ownerPercentage = _ownerPercentage; if(nftRoyalty[_nftContractAddress][_tokenId] .royaltyOwner==address(0)){ nftRoyalty[_nftContractAddress][_tokenId] .royaltyOwner= msg.sender; nftRoyalty[_nftContractAddress][_tokenId] .royaltyPercentage= _royaltyPercentage; } _createNewNftAuction( _nftContractAddress, _tokenId, _erc20Token, _ownerPercentage, _minPrice, _auctionStartTime ); } function _setupAuction( address _nftContractAddress, uint256 _tokenId, address _erc20Token, uint256 _ownerPercentage, uint256 _minPrice, uint256 _auctionStartTime ) internal { // _auctionStartTime=_auctionStartTime + block.timestamp; if (_erc20Token != address(0)) { nftContractAuctions[_nftContractAddress][_tokenId] .ERC20Token = _erc20Token; } nftContractAuctions[_nftContractAddress][_tokenId].minPrice = _minPrice; nftContractAuctions[_nftContractAddress][_tokenId].nftSeller = msg .sender; nftContractAuctions[_nftContractAddress][_tokenId].auctionEnd= nftContractAuctions[_nftContractAddress][_tokenId] .auctionBidPeriod.add(block.timestamp); nftContractAuctions[_nftContractAddress][_tokenId] .auctionStartTime= _auctionStartTime; nftContractAuctions[_nftContractAddress][_tokenId] .ownerPercentage= _ownerPercentage; } function _createNewNftAuction( address _nftContractAddress, uint256 _tokenId, address _erc20Token, uint256 _ownerPercentage, uint256 _minPrice, uint256 _auctionStartTime ) internal{ // Sending the NFT to this contract // _auctionStartTime=_auctionStartTime + block.timestamp; IERC721(_nftContractAddress).transferFrom( msg.sender, address(this), _tokenId ); _setupAuction( _nftContractAddress, _tokenId, _erc20Token, _ownerPercentage, _minPrice, _auctionStartTime ); } function _reverseAndResetPreviousBid( address _nftContractAddress, uint256 _tokenId ) internal { address nftHighestBidder = nftContractAuctions[_nftContractAddress][ _tokenId ].nftHighestBidder; uint256 nftHighestBid = nftContractAuctions[_nftContractAddress][ _tokenId ].nftHighestBid; _resetBids(_nftContractAddress, _tokenId); _payout(_nftContractAddress, _tokenId, nftHighestBidder, nftHighestBid); } function updateMinimumPrice( address _nftContractAddress, uint256 _tokenId, uint256 _newMinPrice ) external onlyNftSeller(_nftContractAddress, _tokenId) minimumBidNotMade(_nftContractAddress, _tokenId) priceGreaterThanZero(_newMinPrice) { nftContractAuctions[_nftContractAddress][_tokenId] .minPrice = _newMinPrice; } function _updateHighestBid( address _nftContractAddress, uint256 _tokenId, uint256 _tokenAmount ) internal { address auctionERC20Token = nftContractAuctions[_nftContractAddress][ _tokenId ].ERC20Token; nftContractAuctions[_nftContractAddress][_tokenId] .nftHighestBidder = msg.sender; if (_isERC20Auction(auctionERC20Token)) { nftContractAuctions[_nftContractAddress][_tokenId] .nftHighestBid = _tokenAmount; IERC20(auctionERC20Token).transferFrom( msg.sender, address(this), _tokenAmount ); nftContractAuctions[_nftContractAddress][_tokenId] .nftHighestBid = _tokenAmount; } else { nftContractAuctions[_nftContractAddress][_tokenId] .nftHighestBid = msg.value; } } function _reversePreviousBidAndUpdateHighestBid( address _nftContractAddress, uint256 _tokenId, uint256 _tokenAmount ) internal { address prevNftHighestBidder = nftContractAuctions[_nftContractAddress][ _tokenId ].nftHighestBidder; uint256 prevNftHighestBid = nftContractAuctions[_nftContractAddress][ _tokenId ].nftHighestBid; _updateHighestBid(_nftContractAddress, _tokenId, _tokenAmount); if (prevNftHighestBidder != address(0)) { _payout( _nftContractAddress, _tokenId, prevNftHighestBidder, prevNftHighestBid ); } } function _isMinimumBidMade(address _nftContractAddress, uint256 _tokenId) internal view returns (bool) { uint256 minPrice = nftContractAuctions[_nftContractAddress][_tokenId] .minPrice; return minPrice > 0 && (nftContractAuctions[_nftContractAddress][_tokenId].nftHighestBid >= minPrice); } function _setupSale( address _nftContractAddress, uint256 _tokenId, address _erc20Token, uint256 _buyNowPrice ) internal { if (_erc20Token != address(0)) { nftContractSale[_nftContractAddress][_tokenId] .ERC20Token = _erc20Token; } nftContractSale[_nftContractAddress][_tokenId] .buyNowPrice = _buyNowPrice; nftContractSale[_nftContractAddress][_tokenId].nftSeller = msg .sender; } function createSale( address _nftContractAddress, uint256 _tokenId, address _erc20Token, uint256 _buyNowPrice ) external priceGreaterThanZero(_buyNowPrice) { IERC721(_nftContractAddress).transferFrom( msg.sender, address(this), _tokenId ); _setupSale( _nftContractAddress, _tokenId, _erc20Token, _buyNowPrice ); } function createBatchSale( address _nftContractAddress, uint256[] memory _batchTokenIds, uint256[] memory _batchTokenPrice, address _erc20Token ) external batchWithinLimits(_batchTokenIds.length) { require(_batchTokenIds.length == _batchTokenPrice.length, "Number of tokens and prices do not match"); for(uint i=0; i< _batchTokenIds.length; i++){ require(_batchTokenPrice[i]>0, "price cannot be 0 or less"); IERC721(_nftContractAddress).transferFrom( msg.sender, address(this), _batchTokenIds[i] ); _setupSale( _nftContractAddress, _batchTokenIds[i], _erc20Token, _batchTokenPrice[i] ); } } function buyNFT( address _nftContractAddress, uint256 _tokenId, uint256 _ownerPercentage ) external payable nonReentrant { address seller= nftContractSale[_nftContractAddress][_tokenId].nftSeller; require(msg.sender!=seller, "Seller cannot buy own NFT"); uint256 buyNowPrice= nftContractSale[_nftContractAddress][_tokenId].buyNowPrice; address erc20Token= nftContractSale[_nftContractAddress][_tokenId].ERC20Token; if(_isERC20Auction(erc20Token)){ require( IERC20(erc20Token).balanceOf(msg.sender) >= buyNowPrice, "Must be greater than NFT cost" ); } else{ require( msg.value >= buyNowPrice, "Must be greater than NFT cost" ); } _buyNFT( _nftContractAddress, _tokenId, _ownerPercentage ); } function _buyNFT( address _nftContractAddress, uint256 _tokenId, uint256 _ownerPercentage ) internal { address seller= nftContractSale[_nftContractAddress][_tokenId].nftSeller; address erc20Token= nftContractSale[_nftContractAddress][_tokenId].ERC20Token; if(_isERC20Auction(erc20Token)){ // if sale is ERC20 uint totalAmount= nftContractSale[_nftContractAddress][_tokenId].buyNowPrice; uint256 ownerAmount= totalAmount.mul(_ownerPercentage).div(10000); uint royaltyAmount; // Reset Sale Data _resetSale(_nftContractAddress, _tokenId); if(nftRoyalty[_nftContractAddress][_tokenId].royaltyOwner != address(0)){ address royaltyOwner= nftRoyalty[_nftContractAddress][_tokenId].royaltyOwner; uint _royaltyPercentage= nftRoyalty[_nftContractAddress][_tokenId].royaltyPercentage; royaltyAmount= totalAmount.mul(_royaltyPercentage).div(10000); IERC20(erc20Token).transferFrom(msg.sender, royaltyOwner, royaltyAmount); } uint sellerAmount= totalAmount.sub(royaltyAmount.add(ownerAmount)); address owner= owner(); IERC20(erc20Token).transferFrom(msg.sender, owner, ownerAmount); IERC20(erc20Token).transferFrom(msg.sender, seller, sellerAmount); } else{ uint totalAmount= msg.value; uint256 ownerAmount= totalAmount.mul(_ownerPercentage).div(10000); // Reset Sale Data _resetSale(_nftContractAddress, _tokenId); uint royaltyAmount; if(nftRoyalty[_nftContractAddress][_tokenId].royaltyOwner != address(0)){ address royaltyOwner= nftRoyalty[_nftContractAddress][_tokenId].royaltyOwner; uint _royaltyPercentage= nftRoyalty[_nftContractAddress][_tokenId].royaltyPercentage; royaltyAmount= totalAmount.mul(_royaltyPercentage).div(10000); payable(royaltyOwner).transfer(royaltyAmount); } uint sellerAmount= totalAmount.sub(royaltyAmount.add(ownerAmount)); address owner= owner(); payable(owner).transfer(ownerAmount); (bool success, ) = payable(seller).call{value: sellerAmount}(""); // if it failed, update their credit balance so they can pull it later if (!success) { failedTransferCredits[seller] = failedTransferCredits[seller].add(sellerAmount); } } IERC721(_nftContractAddress).transferFrom( address(this), msg.sender, _tokenId ); } function _resetSale(address _nftContractAddress, uint256 _tokenId) internal { nftContractSale[_nftContractAddress][_tokenId] .buyNowPrice = 0; nftContractSale[_nftContractAddress][_tokenId] .nftSeller = address( 0 ); nftContractSale[_nftContractAddress][_tokenId] .ERC20Token = address( 0 ); } function _makeBid( address _nftContractAddress, uint256 _tokenId, address _erc20Token, uint256 _tokenAmount ) internal notNftSeller(_nftContractAddress, _tokenId) paymentAccepted( _nftContractAddress, _tokenId, _erc20Token, _tokenAmount ) bidAmountMeetsBidRequirements( _nftContractAddress, _tokenId, _tokenAmount ) { _reversePreviousBidAndUpdateHighestBid( _nftContractAddress, _tokenId, _tokenAmount ); } function _isABidMade(address _nftContractAddress, uint256 _tokenId) internal view returns (bool) { return (nftContractAuctions[_nftContractAddress][_tokenId] .nftHighestBid > 0); } function makeBid( address _nftContractAddress, uint256 _tokenId, address _erc20Token, uint256 _tokenAmount ) external payable nonReentrant auctionOngoing(_nftContractAddress, _tokenId) { // if the auction has started require( nftContractAuctions[_nftContractAddress][_tokenId] .auctionStartTime < block.timestamp, "Auction hasn't begun yet" ); // bid more than minimum price require( (_tokenAmount>= nftContractAuctions[_nftContractAddress][_tokenId].minPrice) || (msg.value >= nftContractAuctions[_nftContractAddress][_tokenId].minPrice) , "Must be greater than minimum amount" ); _makeBid(_nftContractAddress, _tokenId, _erc20Token, _tokenAmount); } /* * Reset all auction related parameters for an NFT. * This effectively removes an EFT as an item up for auction */ function _resetAuction(address _nftContractAddress, uint256 _tokenId) internal { nftContractAuctions[_nftContractAddress][_tokenId].minPrice = 0; nftContractAuctions[_nftContractAddress][_tokenId].auctionEnd = 0; nftContractAuctions[_nftContractAddress][_tokenId].auctionBidPeriod = 0; nftContractAuctions[_nftContractAddress][_tokenId].ownerPercentage = 0; nftContractAuctions[_nftContractAddress][_tokenId] .bidIncreasePercentage = 0; nftContractAuctions[_nftContractAddress][_tokenId].nftSeller = address( 0 ); nftContractAuctions[_nftContractAddress][_tokenId].ERC20Token = address( 0 ); } function _payout( address _nftContractAddress, uint256 _tokenId, address _recipient, uint256 _amount ) internal{ address auctionERC20Token = nftContractAuctions[_nftContractAddress][ _tokenId ].ERC20Token; if (_isERC20Auction(auctionERC20Token)) { // pay royalty owner IERC20(auctionERC20Token).transfer(_recipient, _amount); } else { // attempt to send the funds to the recipient (bool success, ) = payable(_recipient).call{value: _amount}(""); // if it failed, update their credit balance so they can pull it later if (!success) { failedTransferCredits[_recipient] = failedTransferCredits[_recipient].add(_amount); } } } /* * If the transfer of a bid has failed, allow the recipient to reclaim their amount later. */ function withdrawAllFailedCredits() external { uint256 amount = failedTransferCredits[msg.sender]; require(amount != 0, "no credits to withdraw"); failedTransferCredits[msg.sender] = 0; (bool successfulWithdraw, ) = msg.sender.call{value: amount}(""); require(successfulWithdraw, "withdraw failed"); } function _resetBids(address _nftContractAddress, uint256 _tokenId) internal { nftContractAuctions[_nftContractAddress][_tokenId] .nftHighestBidder = address(0); nftContractAuctions[_nftContractAddress][_tokenId].nftHighestBid = 0; nftContractAuctions[_nftContractAddress][_tokenId] .nftRecipient = address(0); } /* * The default value for the NFT recipient is the highest bidder */ function _getNftRecipient(address _nftContractAddress, uint256 _tokenId) internal view returns (address) { address nftRecipient = nftContractAuctions[_nftContractAddress][ _tokenId ].nftRecipient; if (nftRecipient == address(0)) { return nftContractAuctions[_nftContractAddress][_tokenId] .nftHighestBidder; } else { return nftRecipient; } } function _payFeesAndSeller( address _nftContractAddress, uint256 _tokenId, address _nftSeller, uint256 _highestBid ) internal { // pay royalty and owner address erc20Token= nftContractAuctions[_nftContractAddress][_tokenId].ERC20Token; uint256 _ownerPercentage = nftContractAuctions[_nftContractAddress][_tokenId].ownerPercentage; uint256 ownerAmount= _highestBid.mul(_ownerPercentage).div(10000); uint256 sellerAmount= _highestBid.sub(ownerAmount); // Reset Sale Data _resetAuction(_nftContractAddress, _tokenId); if(_isERC20Auction(erc20Token)){ // if sale is ERC20 if(nftRoyalty[_nftContractAddress][_tokenId].royaltyOwner != address(0)){ address royaltyOwner= nftRoyalty[_nftContractAddress][_tokenId].royaltyOwner; uint _royaltyPercentage= nftRoyalty[_nftContractAddress][_tokenId].royaltyPercentage; uint royaltyAmount= _highestBid.mul(_royaltyPercentage).div(10000); sellerAmount= sellerAmount.sub(royaltyAmount); IERC20(erc20Token).transfer(royaltyOwner, royaltyAmount); } address owner= owner(); IERC20(erc20Token).transfer(owner, ownerAmount); } else{ if(nftRoyalty[_nftContractAddress][_tokenId].royaltyOwner != address(0)){ address royaltyOwner= nftRoyalty[_nftContractAddress][_tokenId].royaltyOwner; uint _royaltyPercentage= nftRoyalty[_nftContractAddress][_tokenId].royaltyPercentage; uint royaltyAmount= _highestBid.mul(_royaltyPercentage).div(10000); sellerAmount= sellerAmount.sub(royaltyAmount); payable(royaltyOwner).transfer(royaltyAmount); } address owner= owner(); payable(owner).transfer(ownerAmount); } _payout( _nftContractAddress, _tokenId, _nftSeller, sellerAmount ); } /* * Query the owner of an NFT deposited for auction */ function ownerOfNFT(address _nftContractAddress, uint256 _tokenId) external view returns (address) { address nftSeller = nftContractAuctions[_nftContractAddress][_tokenId] .nftSeller; if (nftSeller != address(0)) { return nftSeller; } address owner = nftOwner[_nftContractAddress][_tokenId]; require(owner != address(0), "NFT not deposited"); return owner; } function _transferNftAndPaySeller( address _nftContractAddress, uint256 _tokenId ) internal { address _nftSeller = nftContractAuctions[_nftContractAddress][_tokenId] .nftSeller; address _nftRecipient = _getNftRecipient(_nftContractAddress, _tokenId); uint256 _nftHighestBid = nftContractAuctions[_nftContractAddress][ _tokenId ].nftHighestBid; _resetBids(_nftContractAddress, _tokenId); _payFeesAndSeller( _nftContractAddress, _tokenId, _nftSeller, _nftHighestBid ); IERC721(_nftContractAddress).transferFrom( address(this), _nftRecipient, _tokenId ); } function takeHighestBid(address _nftContractAddress, uint256 _tokenId) external onlyNftSeller(_nftContractAddress, _tokenId) { require( _isABidMade(_nftContractAddress, _tokenId), "cannot payout 0 bid" ); _transferNftAndPaySeller(_nftContractAddress, _tokenId); } function settleAuction(address _nftContractAddress, uint256 _tokenId) external nonReentrant isAuctionOver(_nftContractAddress, _tokenId) { uint256 _nftHighestBid = nftContractAuctions[_nftContractAddress][ _tokenId ].nftHighestBid; require(_nftHighestBid > 0, "No bid has been made"); _transferNftAndPaySeller(_nftContractAddress, _tokenId); } function settleAuctionOnlyOwner(address _nftContractAddress, uint256 _tokenId) external onlyOwner nonReentrant isAuctionOver(_nftContractAddress, _tokenId) { require(block.timestamp> (nftContractAuctions[_nftContractAddress][_tokenId] .auctionEnd.add( 86400)), "Can't settle before 1 day of grace period has passed" ); // 10% is cut as a penalty. uint totalAmt= nftContractAuctions[_nftContractAddress][_tokenId].nftHighestBid; address erc20Token= nftContractAuctions[_nftContractAddress][_tokenId].ERC20Token; nftContractAuctions[_nftContractAddress][_tokenId].nftHighestBid= totalAmt.mul(100-settlePenalty).div(100); uint penaltyAmt= totalAmt.mul(settlePenalty).div(100); address owner = owner(); if(_isERC20Auction(erc20Token)){ IERC20(erc20Token).transfer(owner, penaltyAmt); } else{ (bool success, ) = payable(owner).call{value: penaltyAmt}(""); // if it failed, update their credit balance so they can pull it later if (!success) { failedTransferCredits[owner] = failedTransferCredits[owner].add(penaltyAmt); } } _transferNftAndPaySeller(_nftContractAddress, _tokenId); } function withdrawSale(address _nftContractAddress, uint256 _tokenId) external nonReentrant { address nftSeller= nftContractSale[_nftContractAddress][_tokenId].nftSeller; require(nftSeller== msg.sender, "Only the owner can call this function"); // reset sale _resetSale(_nftContractAddress, _tokenId); // transfer the NFT back to the Seller IERC721(_nftContractAddress).transferFrom( address(this), nftSeller, _tokenId ); } function withdrawAuction(address _nftContractAddress, uint256 _tokenId) external nonReentrant onlyNftSeller(_nftContractAddress, _tokenId) { address _nftRecipient= nftContractAuctions[_nftContractAddress][_tokenId].nftSeller; address prevNftHighestBidder = nftContractAuctions[_nftContractAddress][ _tokenId ].nftHighestBidder; uint256 prevNftHighestBid = nftContractAuctions[_nftContractAddress][ _tokenId ].nftHighestBid; // Reset values of this Auction _resetBids(_nftContractAddress, _tokenId); _resetAuction(_nftContractAddress, _tokenId); IERC721(_nftContractAddress).transferFrom( address(this), _nftRecipient, _tokenId ); // Pay any bidder if present if (prevNftHighestBidder != address(0)) { _payout( _nftContractAddress, _tokenId, prevNftHighestBidder, prevNftHighestBid ); } } function setSettlePenalty(uint256 _settlePenalty) external onlyOwner{ settlePenalty= _settlePenalty; } }
Sending the NFT to this contract _auctionStartTime=_auctionStartTime + block.timestamp;
function _createNewNftAuction( address _nftContractAddress, uint256 _tokenId, address _erc20Token, uint256 _ownerPercentage, uint256 _minPrice, uint256 _auctionStartTime ) internal{ IERC721(_nftContractAddress).transferFrom( msg.sender, address(this), _tokenId ); _setupAuction( _nftContractAddress, _tokenId, _erc20Token, _ownerPercentage, _minPrice, _auctionStartTime ); }
10,989,552
pragma solidity ^0.5.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be aplied 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. */ contract ReentrancyGuard { // counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @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() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } contract Ownable { address payable public owner; constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address payable newOwner) external onlyOwner { require(newOwner != address(0)); owner = newOwner; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } interface CTokenInterface { function redeemUnderlying(uint redeemAmount) external returns (uint); } interface CETHInterface { function mint() external payable; // For ETH } interface ERC20Interface { function allowance(address, address) external view returns (uint); function balanceOf(address) external view returns (uint); function approve(address, uint) external; function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); } contract AutoETHSavingsAccount is Ownable, ReentrancyGuard{ using SafeMath for uint; // state variables address payable private savingsAccount; uint public balance = address(this).balance; bool private stopped = false; //circuit breaker modifiers modifier stopInEmergency {if (!stopped) _;} modifier onlyInEmergency {if (stopped) _;} constructor () public { } function toggleContractActive() onlyOwner public { stopped = !stopped; } // this function lets you add and replace the old SavingsAccount in which the marginal savings will be deposited function addSavingsAccounts (address payable _address) onlyOwner public { savingsAccount = _address; } // this function lets you deposit ETH into this wallet function depositETH() payable public returns (uint) { balance += msg.value; } // fallback function let you / anyone send ETH to this wallet without the need to call any function function() external payable { balance += msg.value; } // Through this function you will be making a normal payment to any external address or a wallet address as in the normal situation function payETH(address payable _to, uint _amount, uint _pettyAmount) stopInEmergency onlyOwner nonReentrant external returns (uint) { uint grossPayableAmount = SafeMath.add(_amount, _pettyAmount); require(balance > SafeMath.add(grossPayableAmount, 20000000000000000), "the balance held by the Contract is less than the amount required to be paid"); balance = balance - _amount - _pettyAmount; savePettyCash(_pettyAmount); _to.transfer(_amount); } // Depositing the savings amount into the Savings Account function savePettyCash(uint _pettyAmount) internal { savingsAccount.transfer(_pettyAmount); } function withdraw() onlyOwner onlyInEmergency public{ owner.transfer(address(this).balance); } } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "math-not-safe"); } function sub(uint x, uint y) internal pure returns (uint z) { z = x - y <= x ? x - y : 0; } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "math-not-safe"); } uint constant WAD = 10 ** 18; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } } contract Helpers is DSMath { /** * @dev get ethereum address for trade */ function getAddressETH() public pure returns (address eth) { eth = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } /** * @dev get Compound Comptroller Address */ function getCETHAddress() public pure returns (address cEth) { cEth = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; } /** * @dev setting allowance to compound for the "user proxy" if required */ function setApproval(address erc20, uint srcAmt, address to) internal { ERC20Interface erc20Contract = ERC20Interface(erc20); uint tokenAllowance = erc20Contract.allowance(address(this), to); if (srcAmt > tokenAllowance) { erc20Contract.approve(to, 2**255); } } } contract CompoundResolver is Helpers { event LogMint(address erc20, address cErc20, uint tokenAmt, address owner); event LogRedeem(address erc20, address cErc20, uint tokenAmt, address owner); /** * @dev Deposit ETH/ERC20 and mint Compound Tokens */ function mintCEth(uint tokenAmt) internal { CETHInterface cToken = CETHInterface(getCETHAddress()); cToken.mint.value(tokenAmt)(); emit LogMint(getAddressETH(),getCETHAddress(),tokenAmt, msg.sender); } /** * @dev Redeem ETH/ERC20 and mint Compound Tokens * @param tokenAmt Amount of token To Redeem */ function redeemEth(uint tokenAmt) internal { CTokenInterface cToken = CTokenInterface(getCETHAddress()); setApproval(getCETHAddress(), 10**30, getCETHAddress()); require(cToken.redeemUnderlying(tokenAmt) == 0, "something went wrong"); emit LogRedeem(getAddressETH(),getCETHAddress(),tokenAmt, address(this)); } }
Deposit ETH/ERC20 and mint Compound Tokens/
function mintCEth(uint tokenAmt) internal { CETHInterface cToken = CETHInterface(getCETHAddress()); cToken.mint.value(tokenAmt)(); emit LogMint(getAddressETH(),getCETHAddress(),tokenAmt, msg.sender); }
5,428,381
// File: contracts/PollenParams.sol // This file is generated for the "mainnet" network // by the 'generate-PollenAddresses_sol.js' script. // Do not edit it directly - updates will be lost. // SPDX-License-Identifier: MIT pragma solidity >=0.6 <0.7.0; /// @dev Network-dependant params (i.e. addresses, block numbers, etc..) contract PollenParams { // Pollen contracts addresses address internal constant pollenDaoAddress = 0x99c0268759d26616AeC761c28336eccd72CCa39A; address internal constant plnTokenAddress = 0xF4db951000acb9fdeA6A9bCB4afDe42dd52311C7; address internal constant stemTokenAddress = 0xd12ABa72Cad68a63D9C5c6EBE5461fe8fA774B60; address internal constant rateQuoterAddress = 0xB7692BBC55C0a8B768E5b523d068B5552fbF7187; // STEM minting params uint32 internal constant mintStartBlock = 11565019; // Jan-01-2021 00:00:00 +UTC uint32 internal constant mintBlocks = 9200000; // ~ 46 months uint32 internal constant extraMintBlocks = 600000; // ~ 92 days // STEM vesting pools address internal constant rewardsPoolAddress = 0x99c0268759d26616AeC761c28336eccd72CCa39A; address internal constant foundationPoolAddress = 0x30dDD235bEd94fdbCDc197513a638D6CAa261EC7; address internal constant reservePoolAddress = 0xf8617006b4CD2db7385c1cb613885f1292e51b2e; address internal constant marketPoolAddress = 0x256d986bc1d994C36f412b9ED8A269314bA93bc9; address internal constant foundersPoolAddress = 0xd7Cc88bB603DceAFB5E8290d8188C8BF36fD742B; // Min STEM vesting rewarded by `PollenDAO.updateRewardPool()` uint256 internal constant minVestedStemRewarded = 2e4 * 1e18; // Default voting terms uint32 internal constant defaultVotingExpiryDelay = 12 * 3600; uint32 internal constant defaultExecutionOpenDelay = 6 * 3600; uint32 internal constant defaultExecutionExpiryDelay = 24 * 3600; } // File: contracts/interfaces/IPollenTypes.sol pragma solidity >=0.6 <0.7.0; /// @dev Definition of common types interface IPollenTypes { /** * @notice Type for representing a proposal type */ enum ProposalType {Invest, Divest} /** * @notice If the proposal be executed at any or limited market rate */ enum OrderType {Market, Limit} /** * @notice If the asset amount or Pollen amount is fixed * (while the other amount will be updated according to the rate) */ enum BaseCcyType {Asset, Pollen} /** * @notice Type for representing a token proposal status */ enum ProposalStatus {Null, Submitted, Executed, Rejected, Passed, Pended, Expired} /** * @notice Type for representing the state of a vote on a proposal */ enum VoterState {Null, VotedYes, VotedNo} /** * @notice Type for representing a token type */ enum TokenType {ERC20} enum RewardKind {ForVoting, ForProposal, ForExecution, ForStateUpdate, ForPlnHeld} /// @dev Terms and parameters of a proposal struct Proposal { ProposalState state; ProposalParams params; ProposalTerms terms; } /// @dev Current (mutable) params of a proposal struct ProposalState { ProposalStatus status; uint96 yesVotes; uint96 noVotes; } /// @dev Derived terms (immutable params) of a proposal struct ProposalParams { uint32 votingOpen; uint32 votingExpiry; uint32 executionOpen; uint32 executionExpiry; uint32 snapshotId; uint96 passVotes; // lowest bit used for `isExclPools` flag } /// @dev Original terms (immutable params) of a proposal struct ProposalTerms { ProposalType proposalType; OrderType orderType; BaseCcyType baseCcyType; TokenType assetTokenType; uint8 votingTermsId; // must be 0 (reserved for upgrades) uint64 __reserved1; // reserved for upgrades address submitter; address executor; uint96 __reserved2; address assetTokenAddress; uint96 pollenAmount; uint256 assetTokenAmount; } /// @dev Data on user voting struct VoteData { VoterState state; uint96 votesNum; } /// @dev Proposal execution details struct Execution { uint32 timestamp; uint224 quoteCcyAmount; } /// @dev Voting terms struct VotingTerms { // If new proposals may be submitted with this terms bool isEnabled; // If Vesting Pools are excluded from voting and quorum bool isExclPools; // The quorum required to pass a proposal vote in % points uint8 quorum; // Seconds after proposal submission until voting expires uint32 votingExpiryDelay; // Seconds after proposal voting expires until execution opens uint32 executionOpenDelay; // Seconds after proposal execution opens until execution expires uint32 executionExpiryDelay; } /// @dev "Reward points" for members' actions struct RewardParams { uint16 forVotingPoints; uint16 forProposalPoints; uint16 forExecutionPoints; uint16 forStateUpdPoints; uint16 forPlnDayPoints; uint176 __reserved; } // @dev Data on rewards accruals for all members struct RewardTotals { uint32 lastAccumBlock; uint112 accStemPerPoint; uint112 totalPoints; } // @dev Data on a reward struct Reward { address member; RewardKind kind; uint256 points; } // @dev Data on rewards of a member struct MemberRewards { uint32 lastUpdateBlock; uint64 points; uint64 entitled; uint96 adjustment; } } // File: contracts/interfaces/IStemGrantor.sol pragma solidity >=0.6 <0.7.0; pragma experimental ABIEncoderV2; /** * @title IPollenDAO Interface * @notice Interface for the Pollen DAO */ interface IStemGrantor is IPollenTypes { function getMemberPoints(address member) external view returns(uint256); function getMemberRewards(address member) external view returns(MemberRewards memory); function getPendingStem(address member) external view returns(uint256); function getRewardTotals() external view returns(RewardTotals memory); function withdrawRewards(address member) external; event PointsRewarded(address indexed member, RewardKind indexed kind, uint256 points); event RewardWithdrawal(address indexed member, uint256 amount); event StemAllocation(uint256 amount); } // File: contracts/lib/SafeUint.sol pragma solidity >=0.6 <0.7.0; library SafeUint { function safe112(uint256 n) internal pure returns(uint112) { require(n < 2**112, "SafeUint:UNSAFE_UINT112"); return uint112(n); } function safe96(uint256 n) internal pure returns(uint96) { require(n < 2**96, "SafeUint:UNSAFE_UINT96"); return uint96(n); } function safe64(uint256 n) internal pure returns(uint64) { require(n < 2**64, "SafeUint:UNSAFE_UINT64"); return uint64(n); } function safe32(uint256 n) internal pure returns(uint32) { require(n < 2**32, "SafeUint:UNSAFE_UINT32"); return uint32(n); } function safe16(uint256 n) internal pure returns(uint16) { require(n < 2**16, "SafeUint:UNSAFE_UINT16"); return uint16(n); } function safe8(uint256 n) internal pure returns(uint8) { require(n < 256, "SafeUint:UNSAFE_UINT8"); return uint8(n); } } // File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/PollenDAO/StemGrantor.sol pragma solidity >=0.6 <0.7.0; /** * @title StemGrantor Contract * @notice STEM token reward distribution logic */ abstract contract StemGrantor is IStemGrantor { using SafeMath for uint256; using SafeUint for uint256; /** * @dev PollenDAO vests STEM tokens to the "Reward pool" for distribution between members * as rewards for members' actions. * Tokens distributed in proportion to accumulated "reward points" given to a member for * actions. The contract vest STEM tokens to a member when the latest "withdraws" them. * * STEM amount pending to be vested to a member is calculated as: * pendingStem = alreadyEntitled + notYetEntitled (3) * alreadyEntitled = memberRewards.entitled (4) * notYetEntitled = forGivenPointsAmount - memberRewards.adjustment (5) * forGivenPointsAmount = memberRewards.points * _rewardTotals.accStemPerPoint (6) * ( memberRewards.entitled and _rewardTotals.accStemPerPoint are scaled for gas savings ) * * Whenever some "reward points" are given to a member, the following happens: * 1. If it's the 1st reward in the block, STEM for all members get minted to the contract; * 2. `accStemPerPoint` gets updated (w/o yet accounting the new points - newly rewarded * points MUST not affect STEM distributions for the past blocks); * 2. STEM amount "not yet entitled" to the member up until now gets calculated; * 3. "pendingStem" amount is calculated, the value is stored in `memberRewards.entitled`; * 4. `memberRewards.points` gets increased by the newly rewarded "points" (affecting * distributions in the future). */ // Reserved for possible storage structure changes uint256[50] private __gap; // Totals for all members RewardTotals private _rewardTotals; // Mapping from member address to member rewards data mapping(address => MemberRewards) private _membersRewards; function getMemberPoints(address member) public view override returns(uint256) { return _membersRewards[member].points; } function getMemberRewards( address member ) external view override returns(MemberRewards memory) { return _membersRewards[member]; } function getPendingStem( address member ) external view override returns(uint256 stemAmount) { MemberRewards memory memberRewards = _membersRewards[member]; if (memberRewards.points == 0 && memberRewards.entitled == 0 ) return 0; uint256 pendingStem = _getPendingRewardStem(); RewardTotals memory forecastedTotals = _rewardTotals; if (forecastedTotals.totalPoints != 0) { _computeRewardTotals(forecastedTotals, 0, pendingStem, block.number); } stemAmount = _computeMemberRewards( memberRewards, forecastedTotals.accStemPerPoint, 0, block.number ); } function getRewardTotals() external view override returns(RewardTotals memory) { return _rewardTotals; } function withdrawRewards(address member) external override { (uint256 accStemPerPoint, ) = _updateRewardTotals(0); MemberRewards memory memberRewards = _membersRewards[member]; uint256 stemAmount = _computeMemberRewards( memberRewards, accStemPerPoint, 0, block.number ); require(stemAmount != 0, "nothing to withdraw"); _membersRewards[member] = memberRewards; _sendStemTo(member, stemAmount); emit RewardWithdrawal(member, stemAmount); } /**** Internal functions follow ****/ // Inheriting contract must implement following 3 functions /// @dev Get amount of STEMs pending to be vested (sent) to the Rewards Pool function _getPendingRewardStem() internal view virtual returns (uint256 amount); /// @dev Withdraw pending STEMs to the Rewards Pool (once a block only) function _withdrawRewardStem() internal virtual returns(uint256 amount); /// @dev Send STEMs to a member (as a reward) function _sendStemTo(address member, uint256 amount) internal virtual; function _rewardMember(Reward memory reward) internal { (uint256 accStemPerPoint, bool isFirstGrant) = _updateRewardTotals(reward.points); _bookReward(reward, accStemPerPoint, isFirstGrant); } function _rewardMembers(Reward[2] memory rewards) internal { uint256 totalPoints = rewards[0].points + rewards[1].points; (uint256 accStemPerPoint, bool isFirstGrant) = _updateRewardTotals(totalPoints); _bookReward(rewards[0], accStemPerPoint, isFirstGrant); if (rewards[1].points != 0) { _bookReward(rewards[1], accStemPerPoint, isFirstGrant); } } /**** Private functions follow ****/ function _updateRewardTotals( uint256 pointsToAdd ) private returns (uint256 accStemPerPoint, bool isFirstGrant) { uint256 stemToAdd = 0; RewardTotals memory totals = _rewardTotals; uint256 blockNow = block.number; { bool isNeverGranted = totals.accStemPerPoint == 0; bool isDistributable = (blockNow > totals.lastAccumBlock) && (// once a block (totals.totalPoints != 0) || // there are points to distribute between (isNeverGranted && pointsToAdd != 0) // it may be the 1st distribution ); if (isDistributable) { stemToAdd = _withdrawRewardStem(); if (stemToAdd != 0) emit StemAllocation(stemToAdd); } } isFirstGrant = _computeRewardTotals(totals, pointsToAdd, stemToAdd, blockNow); _rewardTotals = totals; accStemPerPoint = totals.accStemPerPoint; } function _bookReward(Reward memory reward, uint256 accStemPerPoint, bool isFirstGrant) private { MemberRewards memory memberRewards = _membersRewards[reward.member]; uint256 pointsToAdd = reward.points; if (isFirstGrant) { memberRewards.points = (pointsToAdd + memberRewards.points).safe64(); pointsToAdd = 0; } uint256 stemRewarded = _computeMemberRewards( memberRewards, accStemPerPoint, pointsToAdd, block.number ); memberRewards.entitled = _stemToEntitledAmount( stemRewarded, uint256(memberRewards.entitled) ); _membersRewards[reward.member] = memberRewards; emit PointsRewarded(reward.member, reward.kind, reward.points); } // Made `internal` for testing (call it from this contract only) function _computeRewardTotals( RewardTotals memory totals, uint256 pointsToAdd, uint256 stemToAdd, uint256 blockNow ) internal pure returns(bool isFirstGrant) { // Make sure, this function is NEVER called: // - for passed "accumulated" blocks // i.e. `require(blockNow >= totals.lastAccumBlock)` // - to add STEM if no points have been yet rewarded // i.e. `require(stemToAdd == 0 || totals.totalPoints != 0)` // - to add STEM for the 2nd time in a block ('pure|view' calls are OK) // i.e. `require(stemToAdd == 0 || blockNow > totals.lastAccumBlock)` isFirstGrant = (totals.accStemPerPoint == 0) && (stemToAdd != 0); uint256 oldPoints = totals.totalPoints; if (pointsToAdd != 0) { totals.totalPoints = pointsToAdd.add(totals.totalPoints).safe112(); if (isFirstGrant) oldPoints = pointsToAdd.add(oldPoints); } if (stemToAdd != 0) { uint256 accStemPerPoint = uint256(totals.accStemPerPoint).add( stemToAdd.mul(1e6).div(oldPoints) // divider can't be 0 ); totals.accStemPerPoint = accStemPerPoint.safe112(); totals.lastAccumBlock = blockNow.safe32(); } } // Made `internal` for testing (call it from this contract only) function _computeMemberRewards( MemberRewards memory memberRewards, uint256 accStemPerPoint, uint256 pointsToAdd, uint256 blockNow ) internal pure returns(uint256 stemAmount) { // Make sure, this function is NEVER called for "past" blocks // i.e. `require(blockNow >= memberRewards.lastUpdateBlock) stemAmount = _entitledAmountToStemAmount(memberRewards.entitled); memberRewards.entitled = 0; uint256 oldPoints = memberRewards.points; if (pointsToAdd != 0) { memberRewards.points = oldPoints.add(pointsToAdd).safe64(); } memberRewards.lastUpdateBlock = blockNow.safe32(); if (oldPoints != 0) { stemAmount = stemAmount.add( (accStemPerPoint.mul(oldPoints) / 1e6) .sub(memberRewards.adjustment) ); } memberRewards.adjustment = ( accStemPerPoint.mul(memberRewards.points) / 1e6 ).safe96(); } function _entitledAmountToStemAmount( uint64 entitled ) private pure returns(uint256 stemAmount) { stemAmount = uint256(entitled) * 1e6; } function _stemToEntitledAmount( uint256 stemAmount, uint256 prevEntitled ) private pure returns(uint64 entitledAmount) { uint256 _entitled = prevEntitled.add(stemAmount / 1e6); // Max amount is limited by ~18.45e6 STEM tokens (for a member) entitledAmount = _entitled < 2**64 ? uint64(_entitled) : 2*64 - 1; } } // File: contracts/interfaces/IPollenDAO.sol pragma solidity >=0.6 <0.7.0; /** * @title IPollenDAO Interface * @notice Interface for the Pollen DAO */ interface IPollenDAO is IPollenTypes, IStemGrantor { /** * @notice Returns the current version of the DAO * @return The current version of the Pollen DAO */ function version() external pure returns (string memory); /** * @notice Get the Pollen token (proxy) contract address * @return The Pollen contract address */ function getPollenAddress() external pure returns(address); /** * @notice Get the STEM token (proxy) contract address * @return The STEM contract address */ function getStemAddress() external pure returns(address); /** * @notice Get the address of the RateQuoter contract * @return The RateQuoter (proxy) contract address */ function getRateQuoterAddress() external pure returns(address); /** * @notice Get the price of PLN in ETH based on the price of assets held * Example: 0.0004 (expressed in ETH/PLN) ==> 2500 PLN = 1 ETH * @return The price */ function getPollenPrice() external returns(uint256); /** * @notice Get total proposal count * @return The total proposal count */ function getProposalCount() external view returns(uint256); /** * @notice Get terms, params and the state for a proposal * @param proposalId The proposal ID * @return terms The terms * @return params The params * @return descriptionCid The CId of the proposal description */ function getProposal(uint256 proposalId) external view returns( ProposalTerms memory terms, ProposalParams memory params, string memory descriptionCid ); /** * @notice Get the state for a proposal * @param proposalId The proposal ID * @return state The state */ function getProposalState(uint256 proposalId) external view returns( ProposalState memory state ); /** * @notice Get the state and number of votes of a voter on a specified proposal * @param voter The voter address * @param proposalId The proposal ID * @return The state of the vote */ function getVoteData(address voter, uint256 proposalId) external view returns(VoteData memory); /** * @notice Get the assets that the DAO holds * @return The set of asset token addresses */ function getAssets() external view returns (address[] memory); /** * @notice Get (a set of) voting terms * @param termsId The ID of the voting terms * @return The (set of) voting terms */ function getVotingTerms(uint256 termsId) external view returns(VotingTerms memory); /** * @notice Submit a proposal * @param proposalType The type of proposal (e.g., Invest, Divest) * @param orderType The type of order (e.g., Market, Limit) * @param baseCcyType The type of base currency (e.g., Asset, Pollen) * @param termsId The voting terms ID * @param assetTokenType The type of the asset token (e.g., ERC20) * @param assetTokenAddress The address of the asset token * @param assetTokenAmount The minimum (on invest) or exact (on divest) amount of the asset token to receive/pay * @param pollenAmount The exact (on invest) or minimum (on divest) amount of Pollen to be paid/received * @param executor The of the account that will execute the proposal (may be the same as msg.sender) * @param descriptionCid The IPFS CId of the proposal description */ function submit( ProposalType proposalType, OrderType orderType, BaseCcyType baseCcyType, uint256 termsId, TokenType assetTokenType, address assetTokenAddress, uint256 assetTokenAmount, uint256 pollenAmount, address executor, string memory descriptionCid ) external; /** * @notice Vote on a proposal * @param proposalId The proposal ID * @param vote The yes/no vote */ function voteOn(uint256 proposalId, bool vote) external; /** * @notice Execute a proposal * @param proposalId The proposal ID * @param data If provided, the message sender is called - * it must implement {IPollenCallee} */ function execute(uint256 proposalId, bytes calldata data) external; /** * @notice Redeem Pollens for asset tokens * @param pollenAmount The amount of Pollens to redeem */ function redeem(uint256 pollenAmount) external; /** * @notice Update the status of a proposal (and get a reward, if updated) * @param proposalId The ID of a proposal */ function updateProposalStatus(uint256 proposalId) external; /** * @notice Update the Reward pool (and get a reward, if updated) */ function updateRewardPool() external; /** * @notice Event emitted when an asset gets added to supported assets */ event AssetAdded(address indexed asset); /** * @notice Event emitted when an asset gets removed from supported assets */ event AssetRemoved(address indexed asset); /** * @notice Event emitted when a proposal is submitted */ event Submitted( uint256 proposalId, ProposalType proposalType, address submitter, uint256 snapshotId ); /** * @notice Event emitted when a proposal is voted on */ event VotedOn( uint256 proposalId, address voter, bool vote, uint256 votes ); /** * @notice Event emitted each time the PLN price is quoted */ event PollenPrice(uint256 price); /** * @notice Event emitted when a proposal is executed * @param proposalId The proposal * @param amount The amount of Pollen (on invest) or asset token (on divest) */ event Executed( uint256 proposalId, uint256 amount ); /** * @notice Event emitted when Pollens are redeemed */ event Redeemed( address sender, uint256 pollenAmount ); /** * @notice Event emitted when a proposal status gets changed */ event StatusChanged( uint proposalId, ProposalStatus newStatus, ProposalStatus oldStatus ); /** * @notice Event emitted when (a set of) voting terms enabled or disabled */ event VotingTermsSwitched( uint256 termsId, bool isEnabled ); /** * @notice Event emitted when reward params get updated */ event RewardParamsUpdated(); /** * @notice Event emitted when new owner is set */ event NewOwner( address newOwner, address oldOwner ); } // File: contracts/interfaces/IPollenDaoAdmin.sol pragma solidity >=0.6 <0.7.0; /** * @title IPollenDAO Interface - administration functions * @notice Only the contract owner may call */ interface IPollenDaoAdmin is IPollenTypes { /** * @notice Initializes a new Pollen instance (proxy) * @dev May be run once only, the sender becomes the contract owner */ function initialize() external; /** * @notice Set a new address to be the owner * (only the owner may call) * @param newOwner The address of the new owner */ function setOwner(address newOwner) external; /** * @notice Add an asset to supported assets * (only the owner may call) * @param asset The address of the asset to be added */ function addAsset(address asset) external; /** * @notice Remove an asset from supported assets * (only the owner may call) * @param asset The address of the asset to be removed */ function removeAsset(address asset) external; function addVotingTerms(VotingTerms memory terms) external; function switchVotingTerms(uint256 termsId, bool isEnabled) external; function updatePlnWhitelist( address[] calldata accounts, bool whitelisted ) external; function updateRewardParams(RewardParams memory _rewardParams) external; } // File: contracts/interfaces/IMintableBurnable.sol pragma solidity >=0.6 <0.7.0; /** * @title IMintableBurnable Interface - token minting/burning support */ interface IMintableBurnable { /** * @dev Mints tokens to the owner account. * Can only be called by the owner. * @param amount The amount of tokens to mint */ function mint(uint256 amount) external; /** * @dev Destroys `amount` tokens from the caller. * @param amount The amount of tokens to mint */ function burn(uint256 amount) external; /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's allowance. * Requirements: the caller must have allowance for `accounts`'s tokens of at least `amount`. */ function burnFrom(address account, uint256 amount) external; } // File: contracts/interfaces/IWhitelist.sol pragma solidity >=0.6 <0.7.0; /** * @title PollenDAO Pre-release Whitelist * @notice A whitelist of users to prevent this release from being used on DEXs etc * @author Quantafire (James Key) */ interface IWhitelist { /** * @notice Check if the address is whitelisted * @param account Addresses to check * @return Bool of whether _addr is whitelisted or not */ function isWhitelisted(address account) external view returns (bool); /** * @notice Turn whitelisting on/off and add/remove whitelisted addresses. * Only the owner of the contract may call. * By default, whitelisting is disabled. * To enable whitelisting, add zero address to whitelisted addresses: * `updateWhitelist([address(0)], [true])` * @param accounts Addresses to add or remove * @param whitelisted `true` - to add, `false` - to remove addresses */ function updateWhitelist(address[] calldata accounts, bool whitelisted) external; event Whitelist(address addr, bool whitelisted); } // File: contracts/interfaces/openzeppelin/IOwnable.sol pragma solidity >=0.6 <0.7.0; /** * @title Interface for `Ownable` (and `OwnableUpgradeSafe`) from the "@openzeppelin" package(s) */ interface IOwnable { /** * @dev Emitted when the ownership is transferred from the `previousOwner` to the `newOwner`. */ event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the current owner. */ function owner() external view returns (address); /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the owner. */ function transferOwnership(address newOwner) external; /** * @dev Leaves the contract without owner. * Can only be called by the owner. * It will not be possible to call `onlyOwner` functions anymore. */ function renounceOwnership() external; } // File: contracts/interfaces/openzeppelin/ISnapshot.sol pragma solidity >=0.6 <0.7.0; /** * @title ISnapshot - snapshot-support extension from the "@openzeppelin" package(s) */ interface ISnapshot { /** * @dev Emitted when a snapshot identified by `id` is created. */ event Snapshot(uint256 id); /** * @dev Creates a new snapshot and returns its snapshot id. * Can only be called by the owner. */ function snapshot() external returns (uint256); /** * @dev Retrieves the balance of `account` at the time `snapshotId` was created. */ function balanceOfAt(address account, uint256 snapshotId) external view returns (uint256); /** * @dev Retrieves the total supply at the time `snapshotId` was created. */ function totalSupplyAt(uint256 snapshotId) external view returns(uint256); } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/interfaces/IPollen.sol pragma solidity >=0.6 <0.7.0; /** * @title IPollen token Interface */ interface IPollen is IERC20, IOwnable, ISnapshot, IMintableBurnable, IWhitelist { /** * @notice Initializes the contract and sets the token name and symbol * @dev Sets the contract `owner` account to the deploying account */ function initialize(string memory name, string memory symbol) external; } // File: contracts/interfaces/IPollenCallee.sol pragma solidity >=0.6 <0.7.0; /** * @title IPollenCallee Interface */ interface IPollenCallee { function onExecute(address sender, uint amountIn, uint amountOut, bytes calldata data) external; } // File: contracts/interfaces/IRateQuoter.sol pragma solidity >=0.6 <0.7.0; /** * @title IRateQuoter Interface */ interface IRateQuoter { /// @dev Only "Spot" for now enum RateTypes { Spot, Fixed } /// @dev if a rate is quoted against USD or ETH enum RateBase { Usd, Eth } /** * @dev if a rate is expressed in a number of ... * the base currency units for one quoted currency unit (i.e. "Direct"), * or the quoted currency units per one base currency unit (i.e. "Indirect") */ enum QuoteType { Direct, Indirect } struct PriceFeed { address feed; address asset; RateBase base; QuoteType side; uint8 decimals; uint16 maxDelaySecs; // 0 - highest; default for now, as only one feed for an asset supported uint8 priority; } /** * @notice Initializes the contract and sets the token name and symbol. * Registers the deployer as the contract `owner`. Can be called once only. */ function initialize() external; /** * @dev Return the latest price of the given base asset against given quote asset * from a highest priority possible feed, direct quotes (ETH/asset), default decimals * (it reverts if the rate is older then the RATE_DELAY_MAX_SECS) */ function quotePrice(address asset) external returns (uint256 rate, uint256 updatedAt); /** * @dev */ function getPriceFeedData(address asset) external view returns (PriceFeed memory); /** * @dev */ function addPriceFeed(PriceFeed memory priceFeed) external; /** * @dev */ function addPriceFeeds(PriceFeed[] memory priceFeeds) external; /** * @dev */ function removePriceFeed(address feed) external; event PriceFeedAdded(address indexed asset, address feed); event PriceFeedRemoved(address asset); // TODO: Extend the IRateQuoter to support the following specs // function quotePriceExtended( // address base, // address quote, // address feed, // RateBase base, // QuoteType side, // uint256 decimals, // uint256 maxDelay, // bool forceUpdate // ) external returns (uint256 rate, uint256 timestamp); } // File: contracts/interfaces/IStemVesting.sol pragma solidity >=0.6 <0.7.0; /** * @title STEM token Interface */ interface IStemVesting { /// @dev Params of a vesting pool struct StemVestingPool { bool isRestricted; // if `true`, the 'wallet' only may trigger withdrawal uint32 startBlock; uint32 endBlock; uint32 lastVestedBlock; uint128 perBlockStemScaled; // scaled (multiplied) by 1e6 } /** * @notice Initializes the contract, sets the token name and symbol, creates vesting pools * @param foundationWallet The foundation wallet * @param reserveWallet The reserve wallet * @param foundersWallet The founders wallet * @param marketWallet The market wallet */ function initialize( address foundationWallet, address reserveWallet, address foundersWallet, address marketWallet ) external; /** * @notice Returns params of a vesting pool * @param wallet The address of the pool' wallet * @return Vesting pool params */ function getVestingPoolParams(address wallet) external view returns(StemVestingPool memory); /** * @notice Returns the amount of STEM pending to be vested to a pool * @param wallet The address of the pool' wallet * @return amount Pending STEM token amount */ function getPoolPendingStem(address wallet) external view returns(uint256 amount); /** * @notice Withdraw pending STEM tokens to a pool * @param wallet The address of the pool' wallet * @return amount Withdrawn STEM token amount */ function withdrawPoolStem(address wallet) external returns (uint256 amount); /// @dev New vesting pool registered event VestingPool(address indexed wallet); /// @dev STEM tokens mint to a pool event StemWithdrawal(address indexed wallet, uint256 amount); } // File: contracts/lib/AddressSet.sol pragma solidity >=0.6 <0.7.0; /** * @title AddressSet Library * @notice Library for representing a set of addresses * @author gtlewis */ library AddressSet { /** * @notice Type for representing a set of addresses * @member elements The elements of the set, contains address 0x0 for deleted elements * @member indexes A mapping of the address to the index in the set, counted from 1 (rather than 0) */ struct Set { address[] elements; mapping(address => uint256) indexes; } /** * @notice Add an element to the set (internal) * @param self The set * @param value The element to add * @return False if the element is already in the set or is address 0x0 */ function add(Set storage self, address value) internal returns (bool) { if (self.indexes[value] != 0 || value == address(0)) { return false; } self.elements.push(value); self.indexes[value] = self.elements.length; return true; } /** * @notice Remove an element from the set (internal) * @param self The set * @param value The element to remove * @return False if the element is not in the set */ function remove(Set storage self, address value) internal returns (bool) { if (self.indexes[value] == 0) { return false; } delete(self.elements[self.indexes[value] - 1]); self.indexes[value] = 0; return true; } /** * @notice Returns true if an element is in the set (internal view) * @param self The set * @param value The element * @return True if the element is in the set */ function contains(Set storage self, address value) internal view returns (bool) { return self.indexes[value] != 0; } } // File: contracts/lib/SafeMath96.sol pragma solidity 0.6.12; library SafeMath96 { function add(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function add(uint96 a, uint96 b) internal pure returns (uint96) { return add(a, b, "SafeMath96: addition overflow"); } function sub(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function sub(uint96 a, uint96 b) internal pure returns (uint96) { return sub(a, b, "SafeMath96: subtraction overflow"); } function fromUint(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function fromUint(uint n) internal pure returns (uint96) { return fromUint(n, "SafeMath96: exceeds 96 bits"); } } // File: contracts/lib/SafeMath32.sol pragma solidity 0.6.12; library SafeMath32 { function add(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { uint32 c = a + b; require(c >= a, errorMessage); return c; } function add(uint32 a, uint32 b) internal pure returns (uint32) { return add(a, b, "SafeMath32: addition overflow"); } function sub(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b <= a, errorMessage); return a - b; } function sub(uint32 a, uint32 b) internal pure returns (uint32) { return sub(a, b, "SafeMath32: subtraction overflow"); } function fromUint(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function fromUint(uint n) internal pure returns (uint32) { return fromUint(n, "SafeMath32: exceeds 32 bits"); } } // File: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: @openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.6.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuardUpgradeSafe is Initializable { bool private _notEntered; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } uint256[49] private __gap; } // File: contracts/PollenDAO_v1.sol pragma solidity >=0.6 <0.7.0; /** * @title PollenDAO Contract * @notice The main Pollen DAO contract */ contract PollenDAO_v1 is Initializable, ReentrancyGuardUpgradeSafe, PollenParams, StemGrantor, IPollenDAO, IPollenDaoAdmin { using AddressSet for AddressSet.Set; using SafeMath for uint256; using SafeUint for uint256; using SafeMath96 for uint96; using SafeMath32 for uint32; using SafeERC20 for IERC20; // Price of PLN for the 1st proposal, in ETH/PLN with 18 decimals uint256 internal constant plnInitialRate = 400e12; // 1ETH = 2500 PLN // "Points" for rewarding members (with STEM) for actions uint16 internal constant forVotingDefaultPoints = 100; uint16 internal constant forProposalDefaultPoints = 300; uint16 internal constant forExecutionDefaultPoints = 500; uint16 internal constant forStateUpdDefaultPoints = 10; uint16 internal constant forPlnDayDefaultPoints = 5; // TODO: implement maxForSingleMemberSharePercents limit uint16 internal constant maxForSingleMemberSharePercents = 20; // Default voting terms (see more in `PollenParams.sol`) uint8 internal constant defaultQuorum = 30; // Min and max allowed delays for voting terms uint256 internal constant minDelay = 60; uint256 internal constant maxDelay = 3600 * 24 * 365; // Reserved for possible storage structure changes uint256[50] private __gap; // The contract owner address private _owner; // The count of proposals uint32 private _proposalCount; // Number of voting terms sets uint16 private _votingTermsNum; // The set of assets that the DAO holds AddressSet.Set private _assets; /// @notice Member activity rewards params RewardParams public rewardParams; // mapping from voting terms ID to voting terms data mapping(uint256 => VotingTerms) internal _votingTerms; // Mapping from proposal ID to proposal data mapping(uint256 => Proposal) internal _proposals; /// @dev Mapping from proposal ID to description content Id mapping(uint256 => string) private _descriptionCids; // Mapping from proposal ID to proposal execution data mapping(uint256 => Execution) private _executions; // Mapping from member address and proposal ID to voting data mapping(address => mapping(uint256 => VoteData)) private _voteData; modifier onlyOwner() { require(_owner == msg.sender, "PollenDAO: unauthorised call"); _; } modifier revertZeroAddress(address _address) { require(_address != address(0), "PollenDAO: invalid address"); _; } /// @inheritdoc IPollenDaoAdmin function initialize() external override initializer { __ReentrancyGuard_init_unchained(); _owner = msg.sender; _addVotingTerms( VotingTerms( true, // is enabled true, // do not count vesting pools' votes defaultQuorum, defaultVotingExpiryDelay, defaultExecutionOpenDelay, defaultExecutionExpiryDelay ) ); _initRewardParams( RewardParams( forVotingDefaultPoints, forProposalDefaultPoints, forExecutionDefaultPoints, forStateUpdDefaultPoints, forPlnDayDefaultPoints, 0 // reserved ) ); } /// @inheritdoc IPollenDAO function version() external pure override returns (string memory) { return "v1"; } /// @inheritdoc IPollenDAO function getPollenAddress() external pure override returns(address) { return address(_plnAddress()); } /// @inheritdoc IPollenDAO function getStemAddress() external pure override returns(address) { return _stemAddress(); } /// @inheritdoc IPollenDAO function getRateQuoterAddress() external pure override returns(address) { return _rateQuoterAddress(); } /// @inheritdoc IPollenDAO function getPollenPrice() public override returns(uint256) { return _getPollenPrice(); } /// @inheritdoc IPollenDAO function getProposalCount() external view override returns(uint256) { return _proposalCount; } /// @inheritdoc IPollenDAO function getProposal(uint proposalId) external view override returns ( ProposalTerms memory terms, ProposalParams memory params, string memory descriptionCid ) { _validateProposalId(proposalId); terms = _proposals[proposalId].terms; params = _proposals[proposalId].params; descriptionCid = _descriptionCids[proposalId]; } function getProposalState( uint256 proposalId ) external view override returns(ProposalState memory state) { _validateProposalId(proposalId); state = _proposals[proposalId].state; } /// @inheritdoc IPollenDAO function getVoteData( address voter, uint256 proposalId ) external view override returns(VoteData memory) { _validateProposalId(proposalId); return (_voteData[voter][proposalId]); } /// @inheritdoc IPollenDAO function getAssets() external view override returns (address[] memory) { return _assets.elements; } /// @inheritdoc IPollenDAO function getVotingTerms( uint256 termsId ) external view override returns(VotingTerms memory) { return _getTermSheet(termsId); } /// @inheritdoc IPollenDAO function submit( ProposalType proposalType, OrderType orderType, BaseCcyType baseCcyType, uint256 termsId, TokenType assetTokenType, address assetTokenAddress, uint256 assetTokenAmount, uint256 pollenAmount, address executor, string memory descriptionCid ) external override revertZeroAddress(assetTokenAddress) { require( IWhitelist(_plnAddress()).isWhitelisted(msg.sender), "PollenDAO: unauthorized" ); require(proposalType <= ProposalType.Divest, "PollenDAO: invalid proposal type"); require(orderType <= OrderType.Limit, "PollenDAO: invalid order type"); require(baseCcyType <= BaseCcyType.Pollen, "PollenDAO: invalid base ccy type"); require(assetTokenType == TokenType.ERC20, "PollenDAO: invalid asset type"); require(_assets.contains(assetTokenAddress), "PollenDAO: unsupported asset"); require(executor != address(0), "PollenDAO: invalid executor"); { bool isAssetFixed = baseCcyType == BaseCcyType.Asset; bool isMarket = orderType == OrderType.Market; require( isAssetFixed ? assetTokenAmount != 0 : pollenAmount != 0, "PollenDAO: zero base amount" ); require( isMarket || (isAssetFixed ? pollenAmount != 0 : assetTokenAmount != 0), "PollenDAO: invalid quoted amount" ); } uint256 proposalId = _proposalCount; _proposalCount = (proposalId + 1).safe32(); _proposals[proposalId].terms = ProposalTerms( proposalType, orderType, baseCcyType, assetTokenType, termsId.safe8(), 0, // reserved msg.sender, executor, 0, // reserved assetTokenAddress, pollenAmount.safe96(), assetTokenAmount ); _descriptionCids[proposalId] = descriptionCid; uint256 snapshotId = 0; if (proposalId == 0) { uint32 expiry = now.safe32(); _proposals[proposalId].params = ProposalParams( expiry, // voting open expiry, // voting expiry expiry, // exec open expiry.add( // exec expiry defaultExecutionExpiryDelay ), uint32(snapshotId), 0 // no voting (zero passVotes) ); _proposals[proposalId].state = ProposalState(ProposalStatus.Passed, 0, 0); } else { VotingTerms memory terms = _getTermSheet(termsId); require(terms.isEnabled, "PollenDAO: disabled terms"); uint32 votingOpen = now.safe32(); uint32 votingExpiry = votingOpen.add(terms.votingExpiryDelay); uint32 execOpen = votingExpiry.add(terms.executionOpenDelay); uint32 execExpiry = execOpen.add(terms.executionExpiryDelay); uint256 totalVotes; (snapshotId, totalVotes) = _takeSnapshot(terms.isExclPools); // The lowest bit encodes `terms.isExclPools` flag uint256 passVotes = (totalVotes.mul(terms.quorum) / 100) | 1; if (!terms.isExclPools) passVotes -= 1; // even, if pools included ProposalParams memory params = ProposalParams( votingOpen, votingExpiry, execOpen, execExpiry, snapshotId.safe32(), passVotes.safe96() ); _proposals[proposalId].params = params; _proposals[proposalId].state = ProposalState(ProposalStatus.Submitted, 0, 0); uint256 senderVotes = _getVotesOfAt(msg.sender, snapshotId); if (senderVotes != 0) { _doVoteAndReward(proposalId, params, msg.sender, true, senderVotes); } } emit Submitted(proposalId, proposalType, msg.sender, snapshotId); } /// @inheritdoc IPollenDAO function voteOn(uint256 proposalId, bool vote) external override { _validateProposalId(proposalId); (ProposalStatus newStatus, ) = _updateProposalStatus(proposalId, ProposalStatus.Null); _revertWrongStatus(newStatus, ProposalStatus.Submitted); uint256 newVotes = _getVotesOfAt(msg.sender, _proposals[proposalId].params.snapshotId); require(newVotes != 0, "PollenDAO: no votes to vote with"); _doVoteAndReward(proposalId, _proposals[proposalId].params, msg.sender, vote, newVotes); } /// @inheritdoc IPollenDAO function execute(uint256 proposalId, bytes calldata data) external override nonReentrant { _validateProposalId(proposalId); ProposalTerms memory terms = _proposals[proposalId].terms; require(terms.executor == msg.sender, "PollenDAO: unauthorized executor"); (ProposalStatus newStatus, ) = _updateProposalStatus(proposalId, ProposalStatus.Null); _revertWrongStatus(newStatus, ProposalStatus.Pended); IPollen pollen = IPollen(_plnAddress()); uint256 pollenAmount; uint256 assetAmount; bool isPollenFixed = terms.baseCcyType == BaseCcyType.Pollen; { IRateQuoter rateQuoter = IRateQuoter(_rateQuoterAddress()); // Ex.: assetRate = 0.001 ETH/DAI // (i.e., `ethers = assetAmount * assetRate`: 1 ETH = 1000 DAI * 0.001 ETH/DAI) (uint256 assetRate, ) = rateQuoter.quotePrice(terms.assetTokenAddress); // Ex.: plnRate = 0.0004 ETH/PLN // (i.e., `ethers = plnAmount * plnRate`: 1 ETH = 2500 PLN * 0.0004 ETH/PLN) uint256 plnRate = _getPollenPrice(); if (isPollenFixed) { pollenAmount = terms.pollenAmount; // Ex.: 2 DAI = 5 PLN * 0.0004 ETH/PLN / 0.001 ETH/DAI assetAmount = pollenAmount.mul(plnRate).div(assetRate); } else { assetAmount = terms.assetTokenAmount; // Ex.: 5 PLN = 2 DAI * 0.001 ETH/DAI / 0.0004 ETH/PLN pollenAmount = assetAmount.mul(assetRate).div(plnRate); } } bool isLimitOrder = terms.orderType == OrderType.Limit; if (terms.proposalType == ProposalType.Invest) { if (isLimitOrder) { if (isPollenFixed) { if (terms.assetTokenAmount > assetAmount) assetAmount = terms.assetTokenAmount; } else { if (terms.pollenAmount < pollenAmount) pollenAmount = terms.pollenAmount; } } // OK to send Pollen first as long as the asset received in the end pollen.mint(pollenAmount); pollen.transfer(msg.sender, pollenAmount); if (data.length > 0) { IPollenCallee(msg.sender).onExecute(msg.sender, assetAmount, pollenAmount, data); } IERC20(terms.assetTokenAddress) .safeTransferFrom(msg.sender, address(this), assetAmount); } else if (terms.proposalType == ProposalType.Divest) { if (isLimitOrder) { if (isPollenFixed) { if (terms.assetTokenAmount < assetAmount) assetAmount = terms.assetTokenAmount; } else { if (terms.pollenAmount > pollenAmount) pollenAmount = terms.pollenAmount; } } // OK to send assets first as long as Pollen burnt in the end IERC20(terms.assetTokenAddress).safeTransfer(msg.sender, assetAmount); if (data.length > 0) { IPollenCallee(msg.sender).onExecute(msg.sender, pollenAmount, assetAmount, data); } pollen.burnFrom(msg.sender, pollenAmount); } else { revert("unsupported proposal type"); } uint256 quotedAmount = isPollenFixed ? assetAmount : pollenAmount; _executions[proposalId] = Execution(uint32(block.timestamp), uint224(quotedAmount)); _updateProposalStatus(proposalId, ProposalStatus.Executed); emit Executed(proposalId, quotedAmount); { RewardParams memory p = rewardParams; Reward[2] memory rewards; rewards[0] = Reward(terms.submitter, RewardKind.ForProposal, p.forProposalPoints); rewards[1] = Reward(msg.sender, RewardKind.ForExecution, p.forExecutionPoints); _rewardMembers(rewards); } } /// @inheritdoc IPollenDAO function redeem(uint256 pollenAmount) external override nonReentrant { require(pollenAmount != 0, "PollenDAO: can't redeem zero"); IPollen pollen = IPollen(_plnAddress()); uint256 totalSupply = pollen.totalSupply(); pollen.burnFrom(msg.sender, pollenAmount); // unbounded loop ignored for (uint256 i=0; i < _assets.elements.length; i++) { IERC20 asset = IERC20(_assets.elements[i]); if (address(asset) != address(0)) { uint256 assetBalance = asset.balanceOf(address(this)); if (assetBalance == 0) { continue; } uint256 assetAmount = assetBalance.mul(pollenAmount).div(totalSupply); asset.transfer( msg.sender, assetAmount > assetBalance ? assetBalance : assetAmount ); } } emit Redeemed( msg.sender, pollenAmount ); } /// @inheritdoc IPollenDAO function updateProposalStatus(uint256 proposalId) external override { (ProposalStatus newStatus, ProposalStatus oldStatus) = _updateProposalStatus( proposalId, ProposalStatus.Null ); if (oldStatus != newStatus) { RewardParams memory params = rewardParams; _rewardMember(Reward(msg.sender, RewardKind.ForStateUpdate, params.forStateUpdPoints)); } } /// @inheritdoc IPollenDAO function updateRewardPool() external override nonReentrant { uint256 pendingStem = IStemVesting(_stemAddress()).getPoolPendingStem(address(this)); if (pendingStem >= minVestedStemRewarded) { RewardParams memory params = rewardParams; _rewardMember(Reward(msg.sender, RewardKind.ForStateUpdate, params.forStateUpdPoints)); } } /// @inheritdoc IPollenDaoAdmin function setOwner(address newOwner) external override onlyOwner revertZeroAddress(newOwner) { address oldOwner = _owner; _owner = newOwner; emit NewOwner(newOwner, oldOwner); } /// @inheritdoc IPollenDaoAdmin function addAsset(address asset) external override onlyOwner revertZeroAddress(asset) { require(!_assets.contains(asset), "PollenDAO: already added"); require(_assets.add(asset)); emit AssetAdded(asset); } /// @inheritdoc IPollenDaoAdmin function removeAsset(address asset) external override onlyOwner revertZeroAddress(asset) { require(_assets.contains(asset), "PollenDAO: unknown asset"); require(IERC20(asset).balanceOf(address(this)) == 0, "PollenDAO: asset has balance"); require(_assets.remove(asset)); emit AssetRemoved(asset); } /// @inheritdoc IPollenDaoAdmin function addVotingTerms(VotingTerms memory terms) external override onlyOwner { _addVotingTerms(terms); } /// @inheritdoc IPollenDaoAdmin function switchVotingTerms( uint256 termsId, bool isEnabled ) external override onlyOwner { require(termsId < _votingTermsNum, "PollenDAO: invalid termsId"); _votingTerms[termsId].isEnabled = isEnabled; emit VotingTermsSwitched(termsId, isEnabled); } /// @inheritdoc IPollenDaoAdmin function updatePlnWhitelist( address[] calldata accounts, bool whitelisted ) external override onlyOwner { IWhitelist(_plnAddress()).updateWhitelist(accounts, whitelisted); } /// @inheritdoc IPollenDaoAdmin function updateRewardParams(RewardParams memory _rewardParams) external override onlyOwner { _initRewardParams(_rewardParams); } function preventUseWithoutProxy() external initializer { // Prevent using the contract w/o the proxy (potentially abusing) // To be called on the "implementation", not on the "proxy" // Does not revert the first call only } function _addVotingTerms(VotingTerms memory t) internal returns(uint termsId) { require(t.quorum <= 100, "PollenDAO: invalid quorum"); require( t.votingExpiryDelay > minDelay && t.executionOpenDelay > minDelay && t.executionExpiryDelay > minDelay && t.votingExpiryDelay < maxDelay && t.executionOpenDelay < maxDelay && t.executionExpiryDelay < maxDelay, "PollenDAO: invalid delays" ); termsId = _votingTermsNum; _votingTerms[termsId] = t; _votingTermsNum = uint16(termsId) + 1; emit VotingTermsSwitched(termsId, t.isEnabled); } function _initRewardParams(RewardParams memory _rewardParams) internal { rewardParams = _rewardParams; emit RewardParamsUpdated(); } function _updateProposalStatus( uint256 proposalId, ProposalStatus knownNewStatus ) internal returns(ProposalStatus newStatus, ProposalStatus oldStatus) { ProposalState memory state = _proposals[proposalId].state; oldStatus = state.status; if (knownNewStatus != ProposalStatus.Null) { newStatus = knownNewStatus; } else { ProposalParams memory params = _proposals[proposalId].params; newStatus = _computeProposalStatus(state, params, now); } if (oldStatus != newStatus) { _proposals[proposalId].state.status = newStatus; emit StatusChanged(proposalId, newStatus, oldStatus); } } function _computeProposalStatus( ProposalState memory state, ProposalParams memory params, uint256 timeNow ) internal pure returns (ProposalStatus) { /* * Possible proposal status transitions: * * +-------------=>Passed-----+ // 1st proposal only * | | * Null-+=>Submitted-+->Passed-----+->Pended----+=>Executed(end) * | | | * +->Rejected +->Expired +->Expired * | * +->Expired * * Transitions triggered by this function: * - Submitted->(Passed || Rejected || Expired) * - Passed->(Pended || Expired) * - Pended->Expired * * Transitions triggered by other functions: * - Null=>Passed , for the 1st proposal only, - by the function `submit` * - Null=>Submitted, except for the 1st proposal - by the function `submit` * - Pended=>Executed - by the function `execute` */ ProposalStatus curStatus = state.status; if ( curStatus == ProposalStatus.Submitted && timeNow >= params.votingExpiry ) { if ( (state.yesVotes > state.noVotes) && (state.yesVotes >= params.passVotes) ) { curStatus = ProposalStatus.Passed; } else { return ProposalStatus.Rejected; } } if (curStatus == ProposalStatus.Passed) { if (timeNow >= params.executionExpiry) return ProposalStatus.Expired; if (timeNow >= params.executionOpen) return ProposalStatus.Pended; } if ( curStatus == ProposalStatus.Pended && timeNow >= params.executionExpiry ) return ProposalStatus.Expired; return curStatus; } function _doVoteAndReward( uint256 proposalId, ProposalParams memory params, address voter, bool vote, uint256 numOfVotes ) private { bool isExclPools = (params.passVotes & 1) == 1; if (isExclPools) _revertOnPool(voter); bool isNewVote = _addVote(proposalId, voter, vote, numOfVotes); if (!isNewVote) return; RewardParams memory p = rewardParams; Reward[2] memory rewards; rewards[0] = Reward(voter, RewardKind.ForVoting, p.forVotingPoints); if (proposalId != 0 && p.forPlnDayPoints != 0) { uint256 plnBalance = _getPlnBalanceAt(voter, params.snapshotId); uint256 secs = params.votingOpen - _proposals[proposalId - 1].params.votingOpen; uint256 points = plnBalance.mul(p.forPlnDayPoints) .mul(secs) .div(86400) // per day .div(1e18); // PLN decimals rewards[1] = Reward(voter, RewardKind.ForPlnHeld, points); } _rewardMembers(rewards); } /** * @dev _addVote (private) * @param proposalId The proposal ID * @param voter The voter address * @param vote The yes/no vote * @param numOfVotes The number of votes */ function _addVote(uint256 proposalId, address voter, bool vote, uint256 numOfVotes) private returns(bool isNewVote) { ProposalState memory proposalState = _proposals[proposalId].state; // if voter had already voted on the proposal, and if so what his vote was. VoteData memory prevVote = _voteData[voter][proposalId]; isNewVote = prevVote.state == VoterState.Null; // allows to change previous vote if (prevVote.state == VoterState.VotedYes) { proposalState.yesVotes = proposalState.yesVotes.sub(prevVote.votesNum); } else if (prevVote.state == VoterState.VotedNo) { proposalState.noVotes = proposalState.noVotes.sub(prevVote.votesNum); } VoteData memory newVote; newVote.votesNum = numOfVotes.safe96(); if (vote) { proposalState.yesVotes = proposalState.yesVotes.add(newVote.votesNum); newVote.state = VoterState.VotedYes; } else { proposalState.noVotes = proposalState.noVotes.add(newVote.votesNum); newVote.state = VoterState.VotedNo; } _proposals[proposalId].state = proposalState; _voteData[voter][proposalId] = newVote; emit VotedOn(proposalId, voter, vote, newVote.votesNum); } // Declared `virtual` for tests only // This should be a view function but, because ratequoter isn't, it can't be function _getPollenPrice() internal virtual returns(uint256 price) { uint256 totalVal; uint256 plnBal = IERC20(_plnAddress()).totalSupply(); if (plnBal != 0) { // TODO: cache the price and update only if it's outdated IRateQuoter rateQuoter = IRateQuoter(_rateQuoterAddress()); for (uint i; i < _assets.elements.length; i++) { uint256 assetBal = IERC20(_assets.elements[i]).balanceOf(address(this)); if (assetBal == 0) continue; (uint256 assetRate, ) = rateQuoter.quotePrice(_assets.elements[i]); totalVal = totalVal.add(assetRate.mul(assetBal)); } price = totalVal == 0 ? 0 : totalVal.div(plnBal); } else { price = plnInitialRate; } emit PollenPrice(price); } function _sendStemTo(address member, uint256 amount) internal override { IERC20(_stemAddress()).safeTransfer(member, amount); } function _getPendingRewardStem() internal view override returns(uint256 amount) { amount = IStemVesting(_stemAddress()).getPoolPendingStem(address(this)); } // Declared `virtual` for tests only function _withdrawRewardStem() internal virtual override returns(uint256 amount) { amount = IStemVesting(_stemAddress()).withdrawPoolStem(address(this)); } // Declared `virtual` for tests only function _takeSnapshot( bool isExclPools ) internal virtual returns (uint256 snapshotId, uint256 totalVotes) { { IPollen stem = IPollen(_stemAddress()); uint256 plnSnapId = IPollen(_plnAddress()).snapshot(); uint256 stmSnapId = stem.snapshot(); snapshotId = _encodeSnapshotId(plnSnapId, stmSnapId); totalVotes = stem.totalSupplyAt(stmSnapId); } { if (isExclPools && (totalVotes != 0)) { totalVotes = totalVotes .sub(_getVotesOfAt(foundationPoolAddress, snapshotId)) .sub(_getVotesOfAt(reservePoolAddress, snapshotId)) .sub(_getVotesOfAt(foundersPoolAddress, snapshotId)); // Marketing Pool ignored } } } // Declared `virtual` for tests only function _getVotesOfAt( address member, uint256 snapshotId ) internal virtual view returns(uint) { ( , uint256 stmSnapId) = _decodeSnapshotId(snapshotId); return IPollen(_stemAddress()).balanceOfAt(member, stmSnapId); } // Made `virtual` for testing only function _getTotalVotesAt(uint256 snapshotId) internal view virtual returns(uint256) { (, uint256 stmSnapId) = _decodeSnapshotId(snapshotId); return IPollen(_stemAddress()).totalSupplyAt(stmSnapId); } // Made `virtual` for testing only function _getPlnBalanceAt( address member, uint256 snapshotId ) internal view virtual returns(uint256) { (uint256 plnSnapId, ) = _decodeSnapshotId(snapshotId); return IPollen(_plnAddress()).balanceOfAt(member, plnSnapId); } // Declared `virtual` for tests only function _revertOnPool(address account) internal pure virtual { require( account != foundationPoolAddress && account != reservePoolAddress && account != marketPoolAddress && account != foundersPoolAddress, "PollenDAO: pools not allowed" ); } function _validateProposalId(uint256 proposalId) private view { require(proposalId < _proposalCount, "PollenDAO: invalid proposal id"); } function _getTermSheet(uint256 termsId) private view returns(VotingTerms memory terms) { terms = _votingTerms[termsId]; require(terms.quorum != 0, "PollenDAO: invalid termsId"); } function _encodeSnapshotId( uint plnSnapId, uint stmSnapId ) private pure returns(uint256) { // IDs are supposed to never exceed 16 bits (2**16 - 1) // If two IDs are equal, no encoding applied if (plnSnapId == stmSnapId) return plnSnapId; return (plnSnapId << 16) | stmSnapId; } function _decodeSnapshotId( uint256 encodedId ) private pure returns(uint256 plnSnapId, uint256 stmSnapId) { // see notes to `_encodeSnapshotId` function if ((encodedId & 0xFFFF0000) == 0) return (encodedId, encodedId); plnSnapId = encodedId >> 16; stmSnapId = encodedId & 0xFFFF; } function _revertWrongStatus( ProposalStatus status, ProposalStatus expectedStatus ) private pure { require(status == expectedStatus, "PollenDAO: wrong proposal status"); } // @dev Declared "internal virtual" for tests only function _plnAddress() internal pure virtual returns(address) { return plnTokenAddress; } function _stemAddress() internal pure virtual returns(address) { return stemTokenAddress; } function _rateQuoterAddress() internal pure virtual returns(address) { return rateQuoterAddress; } }
IPollenDAO Interface - administration functions Only the contract owner may call/
interface IPollenDaoAdmin is IPollenTypes { function initialize() external; function setOwner(address newOwner) external; function addAsset(address asset) external; function removeAsset(address asset) external; function addVotingTerms(VotingTerms memory terms) external; function switchVotingTerms(uint256 termsId, bool isEnabled) external; function updatePlnWhitelist( address[] calldata accounts, bool whitelisted ) external; function updateRewardParams(RewardParams memory _rewardParams) external; } }
302,600
pragma solidity ^0.4.21; // File: contracts/Oracle/DSAuth.sol contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; function DSAuth() public { owner = msg.sender; LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } } // File: contracts/Oracle/DSMath.sol contract DSMath { /* standard uint256 functions */ function add(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x + y) >= x); } function sub(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x - y) <= x); } function mul(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x * y) >= x); } function div(uint256 x, uint256 y) constant internal returns (uint256 z) { z = x / y; } function min(uint256 x, uint256 y) constant internal returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) constant internal returns (uint256 z) { return x >= y ? x : y; } /* uint128 functions (h is for half) */ function hadd(uint128 x, uint128 y) constant internal returns (uint128 z) { assert((z = x + y) >= x); } function hsub(uint128 x, uint128 y) constant internal returns (uint128 z) { assert((z = x - y) <= x); } function hmul(uint128 x, uint128 y) constant internal returns (uint128 z) { assert((z = x * y) >= x); } function hdiv(uint128 x, uint128 y) constant internal returns (uint128 z) { z = x / y; } function hmin(uint128 x, uint128 y) constant internal returns (uint128 z) { return x <= y ? x : y; } function hmax(uint128 x, uint128 y) constant internal returns (uint128 z) { return x >= y ? x : y; } /* int256 functions */ function imin(int256 x, int256 y) constant internal returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) constant internal returns (int256 z) { return x >= y ? x : y; } /* WAD math */ uint128 constant WAD = 10 ** 18; function wadd(uint128 x, uint128 y) constant internal returns (uint128) { return hadd(x, y); } function wsub(uint128 x, uint128 y) constant internal returns (uint128) { return hsub(x, y); } function wmul(uint128 x, uint128 y) constant internal returns (uint128 z) { z = cast((uint256(x) * y + WAD / 2) / WAD); } function wdiv(uint128 x, uint128 y) constant internal returns (uint128 z) { z = cast((uint256(x) * WAD + y / 2) / y); } function wmin(uint128 x, uint128 y) constant internal returns (uint128) { return hmin(x, y); } function wmax(uint128 x, uint128 y) constant internal returns (uint128) { return hmax(x, y); } /* RAY math */ uint128 constant RAY = 10 ** 27; function radd(uint128 x, uint128 y) constant internal returns (uint128) { return hadd(x, y); } function rsub(uint128 x, uint128 y) constant internal returns (uint128) { return hsub(x, y); } function rmul(uint128 x, uint128 y) constant internal returns (uint128 z) { z = cast((uint256(x) * y + RAY / 2) / RAY); } function rdiv(uint128 x, uint128 y) constant internal returns (uint128 z) { z = cast((uint256(x) * RAY + y / 2) / y); } function rpow(uint128 x, uint64 n) constant internal returns (uint128 z) { // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It&#39;s O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } function rmin(uint128 x, uint128 y) constant internal returns (uint128) { return hmin(x, y); } function rmax(uint128 x, uint128 y) constant internal returns (uint128) { return hmax(x, y); } function cast(uint256 x) constant internal returns (uint128 z) { assert((z = uint128(x)) == x); } } // File: contracts/Oracle/DSNote.sol contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } // File: contracts/Oracle/DSThing.sol contract DSThing is DSAuth, DSNote, DSMath { } // File: contracts/Oracle/DSValue.sol contract DSValue is DSThing { bool has; bytes32 val; function peek() constant returns (bytes32, bool) { return (val,has); } function read() constant returns (bytes32) { var (wut, has) = peek(); assert(has); return wut; } function poke(bytes32 wut) note auth { val = wut; has = true; } function void() note auth { // unset the value has = false; } } // File: contracts/Oracle/Medianizer.sol contract Medianizer is DSValue { mapping (bytes12 => address) public values; mapping (address => bytes12) public indexes; bytes12 public next = 0x1; uint96 public min = 0x1; function set(address wat) auth { bytes12 nextId = bytes12(uint96(next) + 1); assert(nextId != 0x0); set(next, wat); next = nextId; } function set(bytes12 pos, address wat) note auth { if (pos == 0x0) throw; if (wat != 0 && indexes[wat] != 0) throw; indexes[values[pos]] = 0; // Making sure to remove a possible existing address in that position if (wat != 0) { indexes[wat] = pos; } values[pos] = wat; } function setMin(uint96 min_) note auth { if (min_ == 0x0) throw; min = min_; } function setNext(bytes12 next_) note auth { if (next_ == 0x0) throw; next = next_; } function unset(bytes12 pos) { set(pos, 0); } function unset(address wat) { set(indexes[wat], 0); } function poke() { poke(0); } function poke(bytes32) note { (val, has) = compute(); } function compute() constant returns (bytes32, bool) { bytes32[] memory wuts = new bytes32[](uint96(next) - 1); uint96 ctr = 0; for (uint96 i = 1; i < uint96(next); i++) { if (values[bytes12(i)] != 0) { var (wut, wuz) = DSValue(values[bytes12(i)]).peek(); if (wuz) { if (ctr == 0 || wut >= wuts[ctr - 1]) { wuts[ctr] = wut; } else { uint96 j = 0; while (wut >= wuts[j]) { j++; } for (uint96 k = ctr; k > j; k--) { wuts[k] = wuts[k - 1]; } wuts[j] = wut; } ctr++; } } } if (ctr < min) return (val, false); bytes32 value; if (ctr % 2 == 0) { uint128 val1 = uint128(wuts[(ctr / 2) - 1]); uint128 val2 = uint128(wuts[ctr / 2]); value = bytes32(wdiv(hadd(val1, val2), 2 ether)); } else { value = wuts[(ctr - 1) / 2]; } return (value, true); } } // File: contracts/Oracle/PriceFeed.sol /// price-feed.sol // Copyright (C) 2017 DappHub, LLC // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // 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 (express or implied). contract PriceFeed is DSThing { uint128 val; uint32 public zzz; function peek() public view returns (bytes32, bool) { return (bytes32(val), now < zzz); } function read() public view returns (bytes32) { assert(now < zzz); return bytes32(val); } function post(uint128 val_, uint32 zzz_, address med_) public note auth { val = val_; zzz = zzz_; bool ret = med_.call(bytes4(keccak256("poke()"))); ret; } function void() public note auth { zzz = 0; } } // File: contracts/Oracle/PriceOracleInterface.sol /* This contract is the interface between the MakerDAO priceFeed and our DX platform. */ contract PriceOracleInterface { address public priceFeedSource; address public owner; bool public emergencyMode; event NonValidPriceFeed(address priceFeedSource); // Modifiers modifier onlyOwner() { require(msg.sender == owner); _; } /// @dev constructor of the contract /// @param _priceFeedSource address of price Feed Source -> should be maker feeds Medianizer contract function PriceOracleInterface( address _owner, address _priceFeedSource ) public { owner = _owner; priceFeedSource = _priceFeedSource; } /// @dev gives the owner the possibility to put the Interface into an emergencyMode, which will /// output always a price of 600 USD. This gives everyone time to set up a new pricefeed. function raiseEmergency(bool _emergencyMode) public onlyOwner() { emergencyMode = _emergencyMode; } /// @dev updates the priceFeedSource /// @param _owner address of owner function updateCurator( address _owner ) public onlyOwner() { owner = _owner; } /// @dev returns the USDETH price, ie gets the USD price from Maker feed with 18 digits, but last 18 digits are cut off function getUSDETHPrice() public returns (uint256) { // if the contract is in the emergencyMode, because there is an issue with the oracle, we will simply return a price of 600 USD if(emergencyMode){ return 600; } bytes32 price; bool valid=true; (price, valid) = Medianizer(priceFeedSource).peek(); if (!valid) { NonValidPriceFeed(priceFeedSource); } // ensuring that there is no underflow or overflow possible, // even if the price is compromised uint priceUint = uint256(price)/(1 ether); if (priceUint == 0) return 1; if (priceUint > 1000000) return 1000000; return priceUint; } } // File: @gnosis.pm/util-contracts/contracts/Math.sol /// @title Math library - Allows calculation of logarithmic and exponential functions /// @author Alan Lu - <[email protected]> /// @author Stefan George - <[email protected]> library Math { /* * Constants */ // This is equal to 1 in our calculations uint public constant ONE = 0x10000000000000000; uint public constant LN2 = 0xb17217f7d1cf79ac; uint public constant LOG2_E = 0x171547652b82fe177; /* * Public functions */ /// @dev Returns natural exponential function value of given x /// @param x x /// @return e**x function exp(int x) public pure returns (uint) { // revert if x is > MAX_POWER, where // MAX_POWER = int(mp.floor(mp.log(mpf(2**256 - 1) / ONE) * ONE)) require(x <= 2454971259878909886679); // return 0 if exp(x) is tiny, using // MIN_POWER = int(mp.floor(mp.log(mpf(1) / ONE) * ONE)) if (x < -818323753292969962227) return 0; // Transform so that e^x -> 2^x x = x * int(ONE) / int(LN2); // 2^x = 2^whole(x) * 2^frac(x) // ^^^^^^^^^^ is a bit shift // so Taylor expand on z = frac(x) int shift; uint z; if (x >= 0) { shift = x / int(ONE); z = uint(x % int(ONE)); } else { shift = x / int(ONE) - 1; z = ONE - uint(-x % int(ONE)); } // 2^x = 1 + (ln 2) x + (ln 2)^2/2! x^2 + ... // // Can generate the z coefficients using mpmath and the following lines // >>> from mpmath import mp // >>> mp.dps = 100 // >>> ONE = 0x10000000000000000 // >>> print(&#39;\n&#39;.join(hex(int(mp.log(2)**i / mp.factorial(i) * ONE)) for i in range(1, 7))) // 0xb17217f7d1cf79ab // 0x3d7f7bff058b1d50 // 0xe35846b82505fc5 // 0x276556df749cee5 // 0x5761ff9e299cc4 // 0xa184897c363c3 uint zpow = z; uint result = ONE; result += 0xb17217f7d1cf79ab * zpow / ONE; zpow = zpow * z / ONE; result += 0x3d7f7bff058b1d50 * zpow / ONE; zpow = zpow * z / ONE; result += 0xe35846b82505fc5 * zpow / ONE; zpow = zpow * z / ONE; result += 0x276556df749cee5 * zpow / ONE; zpow = zpow * z / ONE; result += 0x5761ff9e299cc4 * zpow / ONE; zpow = zpow * z / ONE; result += 0xa184897c363c3 * zpow / ONE; zpow = zpow * z / ONE; result += 0xffe5fe2c4586 * zpow / ONE; zpow = zpow * z / ONE; result += 0x162c0223a5c8 * zpow / ONE; zpow = zpow * z / ONE; result += 0x1b5253d395e * zpow / ONE; zpow = zpow * z / ONE; result += 0x1e4cf5158b * zpow / ONE; zpow = zpow * z / ONE; result += 0x1e8cac735 * zpow / ONE; zpow = zpow * z / ONE; result += 0x1c3bd650 * zpow / ONE; zpow = zpow * z / ONE; result += 0x1816193 * zpow / ONE; zpow = zpow * z / ONE; result += 0x131496 * zpow / ONE; zpow = zpow * z / ONE; result += 0xe1b7 * zpow / ONE; zpow = zpow * z / ONE; result += 0x9c7 * zpow / ONE; if (shift >= 0) { if (result >> (256-shift) > 0) return (2**256-1); return result << shift; } else return result >> (-shift); } /// @dev Returns natural logarithm value of given x /// @param x x /// @return ln(x) function ln(uint x) public pure returns (int) { require(x > 0); // binary search for floor(log2(x)) int ilog2 = floorLog2(x); int z; if (ilog2 < 0) z = int(x << uint(-ilog2)); else z = int(x >> uint(ilog2)); // z = x * 2^-⌊log₂x⌋ // so 1 <= z < 2 // and ln z = ln x - ⌊log₂x⌋/log₂e // so just compute ln z using artanh series // and calculate ln x from that int term = (z - int(ONE)) * int(ONE) / (z + int(ONE)); int halflnz = term; int termpow = term * term / int(ONE) * term / int(ONE); halflnz += termpow / 3; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 5; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 7; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 9; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 11; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 13; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 15; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 17; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 19; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 21; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 23; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 25; return (ilog2 * int(ONE)) * int(ONE) / int(LOG2_E) + 2 * halflnz; } /// @dev Returns base 2 logarithm value of given x /// @param x x /// @return logarithmic value function floorLog2(uint x) public pure returns (int lo) { lo = -64; int hi = 193; // I use a shift here instead of / 2 because it floors instead of rounding towards 0 int mid = (hi + lo) >> 1; while((lo + 1) < hi) { if (mid < 0 && x << uint(-mid) < ONE || mid >= 0 && x >> uint(mid) < ONE) hi = mid; else lo = mid; mid = (hi + lo) >> 1; } } /// @dev Returns maximum of an array /// @param nums Numbers to look through /// @return Maximum number function max(int[] nums) public pure returns (int maxNum) { require(nums.length > 0); maxNum = -2**255; for (uint i = 0; i < nums.length; i++) if (nums[i] > maxNum) maxNum = nums[i]; } /// @dev Returns whether an add operation causes an overflow /// @param a First addend /// @param b Second addend /// @return Did no overflow occur? function safeToAdd(uint a, uint b) internal pure returns (bool) { return a + b >= a; } /// @dev Returns whether a subtraction operation causes an underflow /// @param a Minuend /// @param b Subtrahend /// @return Did no underflow occur? function safeToSub(uint a, uint b) internal pure returns (bool) { return a >= b; } /// @dev Returns whether a multiply operation causes an overflow /// @param a First factor /// @param b Second factor /// @return Did no overflow occur? function safeToMul(uint a, uint b) internal pure returns (bool) { return b == 0 || a * b / b == a; } /// @dev Returns sum if no overflow occurred /// @param a First addend /// @param b Second addend /// @return Sum function add(uint a, uint b) internal pure returns (uint) { require(safeToAdd(a, b)); return a + b; } /// @dev Returns difference if no overflow occurred /// @param a Minuend /// @param b Subtrahend /// @return Difference function sub(uint a, uint b) internal pure returns (uint) { require(safeToSub(a, b)); return a - b; } /// @dev Returns product if no overflow occurred /// @param a First factor /// @param b Second factor /// @return Product function mul(uint a, uint b) internal pure returns (uint) { require(safeToMul(a, b)); return a * b; } /// @dev Returns whether an add operation causes an overflow /// @param a First addend /// @param b Second addend /// @return Did no overflow occur? function safeToAdd(int a, int b) internal pure returns (bool) { return (b >= 0 && a + b >= a) || (b < 0 && a + b < a); } /// @dev Returns whether a subtraction operation causes an underflow /// @param a Minuend /// @param b Subtrahend /// @return Did no underflow occur? function safeToSub(int a, int b) internal pure returns (bool) { return (b >= 0 && a - b <= a) || (b < 0 && a - b > a); } /// @dev Returns whether a multiply operation causes an overflow /// @param a First factor /// @param b Second factor /// @return Did no overflow occur? function safeToMul(int a, int b) internal pure returns (bool) { return (b == 0) || (a * b / b == a); } /// @dev Returns sum if no overflow occurred /// @param a First addend /// @param b Second addend /// @return Sum function add(int a, int b) internal pure returns (int) { require(safeToAdd(a, b)); return a + b; } /// @dev Returns difference if no overflow occurred /// @param a Minuend /// @param b Subtrahend /// @return Difference function sub(int a, int b) internal pure returns (int) { require(safeToSub(a, b)); return a - b; } /// @dev Returns product if no overflow occurred /// @param a First factor /// @param b Second factor /// @return Product function mul(int a, int b) internal pure returns (int) { require(safeToMul(a, b)); return a * b; } } // File: @gnosis.pm/util-contracts/contracts/Proxy.sol /// @title Proxied - indicates that a contract will be proxied. Also defines storage requirements for Proxy. /// @author Alan Lu - <[email protected]> contract Proxied { address public masterCopy; } /// @title Proxy - Generic proxy contract allows to execute all transactions applying the code of a master contract. /// @author Stefan George - <[email protected]> contract Proxy is Proxied { /// @dev Constructor function sets address of master copy contract. /// @param _masterCopy Master copy address. function Proxy(address _masterCopy) public { require(_masterCopy != 0); masterCopy = _masterCopy; } /// @dev Fallback function forwards all transactions and returns all received return data. function () external payable { address _masterCopy = masterCopy; assembly { calldatacopy(0, 0, calldatasize()) let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch success case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } } // File: @gnosis.pm/util-contracts/contracts/Token.sol /// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md pragma solidity ^0.4.21; /// @title Abstract token contract - Functions to be implemented by token contracts contract Token { /* * Events */ event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); /* * Public functions */ function transfer(address to, uint value) public returns (bool); function transferFrom(address from, address to, uint value) public returns (bool); function approve(address spender, uint value) public returns (bool); function balanceOf(address owner) public view returns (uint); function allowance(address owner, address spender) public view returns (uint); function totalSupply() public view returns (uint); } // File: @gnosis.pm/util-contracts/contracts/StandardToken.sol contract StandardTokenData { /* * Storage */ mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowances; uint totalTokens; } /// @title Standard token contract with overflow protection contract StandardToken is Token, StandardTokenData { using Math for *; /* * Public functions */ /// @dev Transfers sender&#39;s tokens to a given address. Returns success /// @param to Address of token receiver /// @param value Number of tokens to transfer /// @return Was transfer successful? function transfer(address to, uint value) public returns (bool) { if ( !balances[msg.sender].safeToSub(value) || !balances[to].safeToAdd(value)) return false; balances[msg.sender] -= value; balances[to] += value; emit Transfer(msg.sender, to, value); return true; } /// @dev Allows allowed third party to transfer tokens from one address to another. Returns success /// @param from Address from where tokens are withdrawn /// @param to Address to where tokens are sent /// @param value Number of tokens to transfer /// @return Was transfer successful? function transferFrom(address from, address to, uint value) public returns (bool) { if ( !balances[from].safeToSub(value) || !allowances[from][msg.sender].safeToSub(value) || !balances[to].safeToAdd(value)) return false; balances[from] -= value; allowances[from][msg.sender] -= value; balances[to] += value; emit Transfer(from, to, value); return true; } /// @dev Sets approved amount of tokens for spender. Returns success /// @param spender Address of allowed account /// @param value Number of approved tokens /// @return Was approval successful? function approve(address spender, uint value) public returns (bool) { allowances[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /// @dev Returns number of allowed tokens for given address /// @param owner Address of token owner /// @param spender Address of token spender /// @return Remaining allowance for spender function allowance(address owner, address spender) public view returns (uint) { return allowances[owner][spender]; } /// @dev Returns number of tokens owned by given address /// @param owner Address of token owner /// @return Balance of owner function balanceOf(address owner) public view returns (uint) { return balances[owner]; } /// @dev Returns total supply of tokens /// @return Total supply function totalSupply() public view returns (uint) { return totalTokens; } } // File: contracts/TokenFRT.sol /// @title Standard token contract with overflow protection contract TokenFRT is StandardToken { string public constant symbol = "MGN"; string public constant name = "Magnolia Token"; uint8 public constant decimals = 18; struct unlockedToken { uint amountUnlocked; uint withdrawalTime; } /* * Storage */ address public owner; address public minter; // user => unlockedToken mapping (address => unlockedToken) public unlockedTokens; // user => amount mapping (address => uint) public lockedTokenBalances; /* * Public functions */ function TokenFRT( address _owner ) public { require(_owner != address(0)); owner = _owner; } // @dev allows to set the minter of Magnolia tokens once. // @param _minter the minter of the Magnolia tokens, should be the DX-proxy function updateMinter( address _minter ) public { require(msg.sender == owner); require(_minter != address(0)); minter = _minter; } // @dev the intention is to set the owner as the DX-proxy, once it is deployed // Then only an update of the DX-proxy contract after a 30 days delay could change the minter again. function updateOwner( address _owner ) public { require(msg.sender == owner); require(_owner != address(0)); owner = _owner; } function mintTokens( address user, uint amount ) public { require(msg.sender == minter); lockedTokenBalances[user] = add(lockedTokenBalances[user], amount); totalTokens = add(totalTokens, amount); } /// @dev Lock Token function lockTokens( uint amount ) public returns (uint totalAmountLocked) { // Adjust amount by balance amount = min(amount, balances[msg.sender]); // Update state variables balances[msg.sender] = sub(balances[msg.sender], amount); lockedTokenBalances[msg.sender] = add(lockedTokenBalances[msg.sender], amount); // Get return variable totalAmountLocked = lockedTokenBalances[msg.sender]; } function unlockTokens( uint amount ) public returns (uint totalAmountUnlocked, uint withdrawalTime) { // Adjust amount by locked balances amount = min(amount, lockedTokenBalances[msg.sender]); if (amount > 0) { // Update state variables lockedTokenBalances[msg.sender] = sub(lockedTokenBalances[msg.sender], amount); unlockedTokens[msg.sender].amountUnlocked = add(unlockedTokens[msg.sender].amountUnlocked, amount); unlockedTokens[msg.sender].withdrawalTime = now + 24 hours; } // Get return variables totalAmountUnlocked = unlockedTokens[msg.sender].amountUnlocked; withdrawalTime = unlockedTokens[msg.sender].withdrawalTime; } function withdrawUnlockedTokens() public { require(unlockedTokens[msg.sender].withdrawalTime < now); balances[msg.sender] = add(balances[msg.sender], unlockedTokens[msg.sender].amountUnlocked); unlockedTokens[msg.sender].amountUnlocked = 0; } function min(uint a, uint b) public pure returns (uint) { if (a < b) { return a; } else { return b; } } /// @dev Returns whether an add operation causes an overflow /// @param a First addend /// @param b Second addend /// @return Did no overflow occur? function safeToAdd(uint a, uint b) public constant returns (bool) { return a + b >= a; } /// @dev Returns whether a subtraction operation causes an underflow /// @param a Minuend /// @param b Subtrahend /// @return Did no underflow occur? function safeToSub(uint a, uint b) public constant returns (bool) { return a >= b; } /// @dev Returns sum if no overflow occurred /// @param a First addend /// @param b Second addend /// @return Sum function add(uint a, uint b) public constant returns (uint) { require(safeToAdd(a, b)); return a + b; } /// @dev Returns difference if no overflow occurred /// @param a Minuend /// @param b Subtrahend /// @return Difference function sub(uint a, uint b) public constant returns (uint) { require(safeToSub(a, b)); return a - b; } } // File: @gnosis.pm/owl-token/contracts/TokenOWL.sol contract TokenOWL is Proxied, StandardToken { using Math for *; string public constant name = "OWL Token"; string public constant symbol = "OWL"; uint8 public constant decimals = 18; struct masterCopyCountdownType { address masterCopy; uint timeWhenAvailable; } masterCopyCountdownType masterCopyCountdown; address public creator; address public minter; event Minted(address indexed to, uint256 amount); event Burnt(address indexed from, address indexed user, uint256 amount); modifier onlyCreator() { // R1 require(msg.sender == creator); _; } /// @dev trickers the update process via the proxyMaster for a new address _masterCopy /// updating is only possible after 30 days function startMasterCopyCountdown ( address _masterCopy ) public onlyCreator() { require(address(_masterCopy) != 0); // Update masterCopyCountdown masterCopyCountdown.masterCopy = _masterCopy; masterCopyCountdown.timeWhenAvailable = now + 30 days; } /// @dev executes the update process via the proxyMaster for a new address _masterCopy function updateMasterCopy() public onlyCreator() { require(address(masterCopyCountdown.masterCopy) != 0); require(now >= masterCopyCountdown.timeWhenAvailable); // Update masterCopy masterCopy = masterCopyCountdown.masterCopy; } function getMasterCopy() public view returns (address) { return masterCopy; } /// @dev Set minter. Only the creator of this contract can call this. /// @param newMinter The new address authorized to mint this token function setMinter(address newMinter) public onlyCreator() { minter = newMinter; } /// @dev change owner/creator of the contract. Only the creator/owner of this contract can call this. /// @param newOwner The new address, which should become the owner function setNewOwner(address newOwner) public onlyCreator() { creator = newOwner; } /// @dev Mints OWL. /// @param to Address to which the minted token will be given /// @param amount Amount of OWL to be minted function mintOWL(address to, uint amount) public { require(minter != 0 && msg.sender == minter); balances[to] = balances[to].add(amount); totalTokens = totalTokens.add(amount); emit Minted(to, amount); } /// @dev Burns OWL. /// @param user Address of OWL owner /// @param amount Amount of OWL to be burnt function burnOWL(address user, uint amount) public { allowances[user][msg.sender] = allowances[user][msg.sender].sub(amount); balances[user] = balances[user].sub(amount); totalTokens = totalTokens.sub(amount); emit Burnt(msg.sender, user, amount); } } // File: contracts/DutchExchange.sol /// @title Dutch Exchange - exchange token pairs with the clever mechanism of the dutch auction /// @author Alex Herrmann - <[email protected]> /// @author Dominik Teiml - <[email protected]> contract DutchExchange is Proxied { // The price is a rational number, so we need a concept of a fraction struct fraction { uint num; uint den; } uint constant WAITING_PERIOD_NEW_TOKEN_PAIR = 6 hours; uint constant WAITING_PERIOD_NEW_AUCTION = 10 minutes; uint constant WAITING_PERIOD_CHANGE_MASTERCOPY_OR_ORACLE = 30 days; uint constant AUCTION_START_WAITING_FOR_FUNDING = 1; address public newMasterCopy; // Time when new masterCopy is updatabale uint public masterCopyCountdown; // > Storage // auctioneer has the power to manage some variables address public auctioneer; // Ether ERC-20 token address public ethToken; // Price Oracle interface PriceOracleInterface public ethUSDOracle; // Price Oracle interface proposals during update process PriceOracleInterface public newProposalEthUSDOracle; uint public oracleInterfaceCountdown; // Minimum required sell funding for adding a new token pair, in USD uint public thresholdNewTokenPair; // Minimum required sell funding for starting antoher auction, in USD uint public thresholdNewAuction; // Fee reduction token (magnolia, ERC-20 token) TokenFRT public frtToken; // Token for paying fees TokenOWL public owlToken; // mapping that stores the tokens, which are approved // Token => approved // Only tokens approved by auctioneer generate frtToken tokens mapping (address => bool) public approvedTokens; // For the following two mappings, there is one mapping for each token pair // The order which the tokens should be called is smaller, larger // These variables should never be called directly! They have getters below // Token => Token => index mapping (address => mapping (address => uint)) public latestAuctionIndices; // Token => Token => time mapping (address => mapping (address => uint)) public auctionStarts; // Token => Token => auctionIndex => price mapping (address => mapping (address => mapping (uint => fraction))) public closingPrices; // Token => Token => amount mapping (address => mapping (address => uint)) public sellVolumesCurrent; // Token => Token => amount mapping (address => mapping (address => uint)) public sellVolumesNext; // Token => Token => amount mapping (address => mapping (address => uint)) public buyVolumes; // Token => user => amount // balances stores a user&#39;s balance in the DutchX mapping (address => mapping (address => uint)) public balances; // Token => Token => auctionIndex => amount mapping (address => mapping (address => mapping (uint => uint))) public extraTokens; // Token => Token => auctionIndex => user => amount mapping (address => mapping (address => mapping (uint => mapping (address => uint)))) public sellerBalances; mapping (address => mapping (address => mapping (uint => mapping (address => uint)))) public buyerBalances; mapping (address => mapping (address => mapping (uint => mapping (address => uint)))) public claimedAmounts; // > Modifiers modifier onlyAuctioneer() { // Only allows auctioneer to proceed // R1 require(msg.sender == auctioneer); _; } /// @dev Constructor-Function creates exchange /// @param _frtToken - address of frtToken ERC-20 token /// @param _owlToken - address of owlToken ERC-20 token /// @param _auctioneer - auctioneer for managing interfaces /// @param _ethToken - address of ETH ERC-20 token /// @param _ethUSDOracle - address of the oracle contract for fetching feeds /// @param _thresholdNewTokenPair - Minimum required sell funding for adding a new token pair, in USD function setupDutchExchange( TokenFRT _frtToken, TokenOWL _owlToken, address _auctioneer, address _ethToken, PriceOracleInterface _ethUSDOracle, uint _thresholdNewTokenPair, uint _thresholdNewAuction ) public { // Make sure contract hasn&#39;t been initialised require(ethToken == 0); // Validates inputs require(address(_owlToken) != address(0)); require(address(_frtToken) != address(0)); require(_auctioneer != 0); require(_ethToken != 0); require(address(_ethUSDOracle) != address(0)); frtToken = _frtToken; owlToken = _owlToken; auctioneer = _auctioneer; ethToken = _ethToken; ethUSDOracle = _ethUSDOracle; thresholdNewTokenPair = _thresholdNewTokenPair; thresholdNewAuction = _thresholdNewAuction; } function updateAuctioneer( address _auctioneer ) public onlyAuctioneer { require(_auctioneer != address(0)); auctioneer = _auctioneer; } function initiateEthUsdOracleUpdate( PriceOracleInterface _ethUSDOracle ) public onlyAuctioneer { require(address(_ethUSDOracle) != address(0)); newProposalEthUSDOracle = _ethUSDOracle; oracleInterfaceCountdown = add(now, WAITING_PERIOD_CHANGE_MASTERCOPY_OR_ORACLE); NewOracleProposal(_ethUSDOracle); } function updateEthUSDOracle() public onlyAuctioneer { require(address(newProposalEthUSDOracle) != address(0)); require(oracleInterfaceCountdown < now); ethUSDOracle = newProposalEthUSDOracle; newProposalEthUSDOracle = PriceOracleInterface(0); } function updateThresholdNewTokenPair( uint _thresholdNewTokenPair ) public onlyAuctioneer { thresholdNewTokenPair = _thresholdNewTokenPair; } function updateThresholdNewAuction( uint _thresholdNewAuction ) public onlyAuctioneer { thresholdNewAuction = _thresholdNewAuction; } function updateApprovalOfToken( address[] token, bool approved ) public onlyAuctioneer { for(uint i = 0; i < token.length; i++) { approvedTokens[token[i]] = approved; Approval(token[i], approved); } } function startMasterCopyCountdown ( address _masterCopy ) public onlyAuctioneer { require(_masterCopy != address(0)); // Update masterCopyCountdown newMasterCopy = _masterCopy; masterCopyCountdown = add(now, WAITING_PERIOD_CHANGE_MASTERCOPY_OR_ORACLE); NewMasterCopyProposal(_masterCopy); } function updateMasterCopy() public onlyAuctioneer { require(newMasterCopy != address(0)); require(now >= masterCopyCountdown); // Update masterCopy masterCopy = newMasterCopy; newMasterCopy = address(0); } /// @param initialClosingPriceNum initial price will be 2 * initialClosingPrice. This is its numerator /// @param initialClosingPriceDen initial price will be 2 * initialClosingPrice. This is its denominator function addTokenPair( address token1, address token2, uint token1Funding, uint token2Funding, uint initialClosingPriceNum, uint initialClosingPriceDen ) public { // R1 require(token1 != token2); // R2 require(initialClosingPriceNum != 0); // R3 require(initialClosingPriceDen != 0); // R4 require(getAuctionIndex(token1, token2) == 0); // R5: to prevent overflow require(initialClosingPriceNum < 10 ** 18); // R6 require(initialClosingPriceDen < 10 ** 18); setAuctionIndex(token1, token2); token1Funding = min(token1Funding, balances[token1][msg.sender]); token2Funding = min(token2Funding, balances[token2][msg.sender]); // R7 require(token1Funding < 10 ** 30); // R8 require(token2Funding < 10 ** 30); uint fundedValueUSD; uint ethUSDPrice = ethUSDOracle.getUSDETHPrice(); // Compute fundedValueUSD address ethTokenMem = ethToken; if (token1 == ethTokenMem) { // C1 // MUL: 10^30 * 10^6 = 10^36 fundedValueUSD = mul(token1Funding, ethUSDPrice); } else if (token2 == ethTokenMem) { // C2 // MUL: 10^30 * 10^6 = 10^36 fundedValueUSD = mul(token2Funding, ethUSDPrice); } else { // C3: Neither token is ethToken fundedValueUSD = calculateFundedValueTokenToken(token1, token2, token1Funding, token2Funding, ethTokenMem, ethUSDPrice); } // R5 require(fundedValueUSD >= thresholdNewTokenPair); // Save prices of opposite auctions closingPrices[token1][token2][0] = fraction(initialClosingPriceNum, initialClosingPriceDen); closingPrices[token2][token1][0] = fraction(initialClosingPriceDen, initialClosingPriceNum); // Split into two fns because of 16 local-var cap addTokenPairSecondPart(token1, token2, token1Funding, token2Funding); } function calculateFundedValueTokenToken( address token1, address token2, uint token1Funding, uint token2Funding, address ethTokenMem, uint ethUSDPrice ) internal view returns (uint fundedValueUSD) { // We require there to exist ethToken-Token auctions // R3.1 require(getAuctionIndex(token1, ethTokenMem) > 0); // R3.2 require(getAuctionIndex(token2, ethTokenMem) > 0); // Price of Token 1 uint priceToken1Num; uint priceToken1Den; (priceToken1Num, priceToken1Den) = getPriceOfTokenInLastAuction(token1); // Price of Token 2 uint priceToken2Num; uint priceToken2Den; (priceToken2Num, priceToken2Den) = getPriceOfTokenInLastAuction(token2); // Compute funded value in ethToken and USD // 10^30 * 10^30 = 10^60 uint fundedValueETH = add(mul(token1Funding, priceToken1Num) / priceToken1Den, token2Funding * priceToken2Num / priceToken2Den); fundedValueUSD = mul(fundedValueETH, ethUSDPrice); } function addTokenPairSecondPart( address token1, address token2, uint token1Funding, uint token2Funding ) internal { balances[token1][msg.sender] = sub(balances[token1][msg.sender], token1Funding); balances[token2][msg.sender] = sub(balances[token2][msg.sender], token2Funding); // Fee mechanism, fees are added to extraTokens uint token1FundingAfterFee = settleFee(token1, token2, 1, token1Funding); uint token2FundingAfterFee = settleFee(token2, token1, 1, token2Funding); // Update other variables sellVolumesCurrent[token1][token2] = token1FundingAfterFee; sellVolumesCurrent[token2][token1] = token2FundingAfterFee; sellerBalances[token1][token2][1][msg.sender] = token1FundingAfterFee; sellerBalances[token2][token1][1][msg.sender] = token2FundingAfterFee; setAuctionStart(token1, token2, WAITING_PERIOD_NEW_TOKEN_PAIR); NewTokenPair(token1, token2); } function deposit( address tokenAddress, uint amount ) public returns (uint) { // R1 require(Token(tokenAddress).transferFrom(msg.sender, this, amount)); uint newBal = add(balances[tokenAddress][msg.sender], amount); balances[tokenAddress][msg.sender] = newBal; NewDeposit(tokenAddress, amount); return newBal; } function withdraw( address tokenAddress, uint amount ) public returns (uint) { uint usersBalance = balances[tokenAddress][msg.sender]; amount = min(amount, usersBalance); // R1 require(amount > 0); // R2 require(Token(tokenAddress).transfer(msg.sender, amount)); uint newBal = sub(usersBalance, amount); balances[tokenAddress][msg.sender] = newBal; NewWithdrawal(tokenAddress, amount); return newBal; } function postSellOrder( address sellToken, address buyToken, uint auctionIndex, uint amount ) public returns (uint, uint) { // Note: if a user specifies auctionIndex of 0, it // means he is agnostic which auction his sell order goes into amount = min(amount, balances[sellToken][msg.sender]); // R1 require(amount > 0); // R2 uint latestAuctionIndex = getAuctionIndex(sellToken, buyToken); require(latestAuctionIndex > 0); // R3 uint auctionStart = getAuctionStart(sellToken, buyToken); if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING || auctionStart > now) { // C1: We are in the 10 minute buffer period // OR waiting for an auction to receive sufficient sellVolume // Auction has already cleared, and index has been incremented // sell order must use that auction index // R1.1 if (auctionIndex == 0) { auctionIndex = latestAuctionIndex; } else { require(auctionIndex == latestAuctionIndex); } // R1.2 require(add(sellVolumesCurrent[sellToken][buyToken], amount) < 10 ** 30); } else { // C2 // R2.1: Sell orders must go to next auction if (auctionIndex == 0) { auctionIndex = latestAuctionIndex + 1; } else { require(auctionIndex == latestAuctionIndex + 1); } // R2.2 require(add(sellVolumesNext[sellToken][buyToken], amount) < 10 ** 30); } // Fee mechanism, fees are added to extraTokens uint amountAfterFee = settleFee(sellToken, buyToken, auctionIndex, amount); // Update variables balances[sellToken][msg.sender] = sub(balances[sellToken][msg.sender], amount); uint newSellerBal = add(sellerBalances[sellToken][buyToken][auctionIndex][msg.sender], amountAfterFee); sellerBalances[sellToken][buyToken][auctionIndex][msg.sender] = newSellerBal; if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING || auctionStart > now) { // C1 uint sellVolumeCurrent = sellVolumesCurrent[sellToken][buyToken]; sellVolumesCurrent[sellToken][buyToken] = add(sellVolumeCurrent, amountAfterFee); } else { // C2 uint sellVolumeNext = sellVolumesNext[sellToken][buyToken]; sellVolumesNext[sellToken][buyToken] = add(sellVolumeNext, amountAfterFee); } if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING) { scheduleNextAuction(sellToken, buyToken); } NewSellOrder(sellToken, buyToken, msg.sender, auctionIndex, amountAfterFee); return (auctionIndex, newSellerBal); } function postBuyOrder( address sellToken, address buyToken, uint auctionIndex, uint amount ) public returns (uint) { // R1: auction must not have cleared require(closingPrices[sellToken][buyToken][auctionIndex].den == 0); uint auctionStart = getAuctionStart(sellToken, buyToken); // R2 require(auctionStart <= now); // R4 require(auctionIndex == getAuctionIndex(sellToken, buyToken)); // R5: auction must not be in waiting period require(auctionStart > AUCTION_START_WAITING_FOR_FUNDING); // R6: auction must be funded require(sellVolumesCurrent[sellToken][buyToken] > 0); uint buyVolume = buyVolumes[sellToken][buyToken]; amount = min(amount, balances[buyToken][msg.sender]); // R7 require(add(buyVolume, amount) < 10 ** 30); // Overbuy is when a part of a buy order clears an auction // In that case we only process the part before the overbuy // To calculate overbuy, we first get current price uint sellVolume = sellVolumesCurrent[sellToken][buyToken]; uint num; uint den; (num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex); // 10^30 * 10^37 = 10^67 uint outstandingVolume = atleastZero(int(mul(sellVolume, num) / den - buyVolume)); uint amountAfterFee; if (amount < outstandingVolume) { if (amount > 0) { amountAfterFee = settleFee(buyToken, sellToken, auctionIndex, amount); } } else { amount = outstandingVolume; amountAfterFee = outstandingVolume; } // Here we could also use outstandingVolume or amountAfterFee, it doesn&#39;t matter if (amount > 0) { // Update variables balances[buyToken][msg.sender] = sub(balances[buyToken][msg.sender], amount); uint newBuyerBal = add(buyerBalances[sellToken][buyToken][auctionIndex][msg.sender], amountAfterFee); buyerBalances[sellToken][buyToken][auctionIndex][msg.sender] = newBuyerBal; buyVolumes[sellToken][buyToken] = add(buyVolumes[sellToken][buyToken], amountAfterFee); NewBuyOrder(sellToken, buyToken, msg.sender, auctionIndex, amountAfterFee); } // Checking for equality would suffice here. nevertheless: if (amount >= outstandingVolume) { // Clear auction clearAuction(sellToken, buyToken, auctionIndex, sellVolume); } return (newBuyerBal); } function claimSellerFunds( address sellToken, address buyToken, address user, uint auctionIndex ) public // < (10^60, 10^61) returns (uint returned, uint frtsIssued) { closeTheoreticalClosedAuction(sellToken, buyToken, auctionIndex); uint sellerBalance = sellerBalances[sellToken][buyToken][auctionIndex][user]; // R1 require(sellerBalance > 0); // Get closing price for said auction fraction memory closingPrice = closingPrices[sellToken][buyToken][auctionIndex]; uint num = closingPrice.num; uint den = closingPrice.den; // R2: require auction to have cleared require(den > 0); // Calculate return // < 10^30 * 10^30 = 10^60 returned = mul(sellerBalance, num) / den; frtsIssued = issueFrts(sellToken, buyToken, returned, auctionIndex, sellerBalance, user); // Claim tokens sellerBalances[sellToken][buyToken][auctionIndex][user] = 0; if (returned > 0) { balances[buyToken][user] = add(balances[buyToken][user], returned); } NewSellerFundsClaim(sellToken, buyToken, user, auctionIndex, returned, frtsIssued); } function claimBuyerFunds( address sellToken, address buyToken, address user, uint auctionIndex ) public returns (uint returned, uint frtsIssued) { closeTheoreticalClosedAuction(sellToken, buyToken, auctionIndex); uint num; uint den; (returned, num, den) = getUnclaimedBuyerFunds(sellToken, buyToken, user, auctionIndex); if (closingPrices[sellToken][buyToken][auctionIndex].den == 0) { // Auction is running claimedAmounts[sellToken][buyToken][auctionIndex][user] = add(claimedAmounts[sellToken][buyToken][auctionIndex][user], returned); } else { // Auction has closed // We DON&#39;T want to check for returned > 0, because that would fail if a user claims // intermediate funds & auction clears in same block (he/she would not be able to claim extraTokens) // Assign extra sell tokens (this is possible only after auction has cleared, // because buyVolume could still increase before that) uint extraTokensTotal = extraTokens[sellToken][buyToken][auctionIndex]; uint buyerBalance = buyerBalances[sellToken][buyToken][auctionIndex][user]; // closingPrices.num represents buyVolume // < 10^30 * 10^30 = 10^60 uint tokensExtra = mul(buyerBalance, extraTokensTotal) / closingPrices[sellToken][buyToken][auctionIndex].num; returned = add(returned, tokensExtra); frtsIssued = issueFrts(buyToken, sellToken, mul(buyerBalance, den) / num, auctionIndex, buyerBalance, user); // Auction has closed // Reset buyerBalances and claimedAmounts buyerBalances[sellToken][buyToken][auctionIndex][user] = 0; claimedAmounts[sellToken][buyToken][auctionIndex][user] = 0; } // Claim tokens if (returned > 0) { balances[sellToken][user] = add(balances[sellToken][user], returned); } NewBuyerFundsClaim(sellToken, buyToken, user, auctionIndex, returned, frtsIssued); } function issueFrts( address primaryToken, address secondaryToken, uint x, uint auctionIndex, uint bal, address user ) internal returns (uint frtsIssued) { if (approvedTokens[primaryToken] && approvedTokens[secondaryToken]) { address ethTokenMem = ethToken; // Get frts issued based on ETH price of returned tokens if (primaryToken == ethTokenMem) { frtsIssued = bal; } else if (secondaryToken == ethTokenMem) { // 10^30 * 10^39 = 10^66 frtsIssued = x; } else { // Neither token is ethToken, so we use getHhistoricalPriceOracle() uint pastNum; uint pastDen; (pastNum, pastDen) = getPriceInPastAuction(primaryToken, ethTokenMem, auctionIndex - 1); // 10^30 * 10^35 = 10^65 frtsIssued = mul(bal, pastNum) / pastDen; } if (frtsIssued > 0) { // Issue frtToken frtToken.mintTokens(user, frtsIssued); } } } //@dev allows to close possible theoretical closed markets //@param sellToken sellToken of an auction //@param buyToken buyToken of an auction //@param index is the auctionIndex of the auction function closeTheoreticalClosedAuction( address sellToken, address buyToken, uint auctionIndex ) public { if(auctionIndex == getAuctionIndex(buyToken, sellToken) && closingPrices[sellToken][buyToken][auctionIndex].num == 0) { uint buyVolume = buyVolumes[sellToken][buyToken]; uint sellVolume = sellVolumesCurrent[sellToken][buyToken]; uint num; uint den; (num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex); // 10^30 * 10^37 = 10^67 uint outstandingVolume = atleastZero(int(mul(sellVolume, num) / den - buyVolume)); if(outstandingVolume == 0) { postBuyOrder(sellToken, buyToken, auctionIndex, 0); } } } /// @dev Claim buyer funds for one auction function getUnclaimedBuyerFunds( address sellToken, address buyToken, address user, uint auctionIndex ) public view // < (10^67, 10^37) returns (uint unclaimedBuyerFunds, uint num, uint den) { // R1: checks if particular auction has ever run require(auctionIndex <= getAuctionIndex(sellToken, buyToken)); (num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex); if (num == 0) { // This should rarely happen - as long as there is >= 1 buy order, // auction will clear before price = 0. So this is just fail-safe unclaimedBuyerFunds = 0; } else { uint buyerBalance = buyerBalances[sellToken][buyToken][auctionIndex][user]; // < 10^30 * 10^37 = 10^67 unclaimedBuyerFunds = atleastZero(int( mul(buyerBalance, den) / num - claimedAmounts[sellToken][buyToken][auctionIndex][user] )); } } function settleFee( address primaryToken, address secondaryToken, uint auctionIndex, uint amount ) internal // < 10^30 returns (uint amountAfterFee) { uint feeNum; uint feeDen; (feeNum, feeDen) = getFeeRatio(msg.sender); // 10^30 * 10^3 / 10^4 = 10^29 uint fee = mul(amount, feeNum) / feeDen; if (fee > 0) { fee = settleFeeSecondPart(primaryToken, fee); uint usersExtraTokens = extraTokens[primaryToken][secondaryToken][auctionIndex + 1]; extraTokens[primaryToken][secondaryToken][auctionIndex + 1] = add(usersExtraTokens, fee); Fee(primaryToken, secondaryToken, msg.sender, auctionIndex, fee); } amountAfterFee = sub(amount, fee); } function settleFeeSecondPart( address primaryToken, uint fee ) internal returns (uint newFee) { // Allow user to reduce up to half of the fee with owlToken uint num; uint den; (num, den) = getPriceOfTokenInLastAuction(primaryToken); // Convert fee to ETH, then USD // 10^29 * 10^30 / 10^30 = 10^29 uint feeInETH = mul(fee, num) / den; uint ethUSDPrice = ethUSDOracle.getUSDETHPrice(); // 10^29 * 10^6 = 10^35 // Uses 18 decimal places <> exactly as owlToken tokens: 10**18 owlToken == 1 USD uint feeInUSD = mul(feeInETH, ethUSDPrice); uint amountOfowlTokenBurned = min(owlToken.allowance(msg.sender, this), feeInUSD / 2); amountOfowlTokenBurned = min(owlToken.balanceOf(msg.sender), amountOfowlTokenBurned); if (amountOfowlTokenBurned > 0) { owlToken.burnOWL(msg.sender, amountOfowlTokenBurned); // Adjust fee // 10^35 * 10^29 = 10^64 uint adjustment = mul(amountOfowlTokenBurned, fee) / feeInUSD; newFee = sub(fee, adjustment); } else { newFee = fee; } } function getFeeRatio( address user ) public view // feeRatio < 10^4 returns (uint num, uint den) { uint t = frtToken.totalSupply(); uint b = frtToken.lockedTokenBalances(user); if (b * 100000 < t || t == 0) { // 0.5% num = 1; den = 200; } else if (b * 10000 < t) { // 0.4% num = 1; den = 250; } else if (b * 1000 < t) { // 0.3% num = 3; den = 1000; } else if (b * 100 < t) { // 0.2% num = 1; den = 500; } else if (b * 10 < t) { // 0.1% num = 1; den = 1000; } else { // 0% num = 0; den = 1; } } /// @dev clears an Auction /// @param sellToken sellToken of the auction /// @param buyToken buyToken of the auction /// @param auctionIndex of the auction to be cleared. function clearAuction( address sellToken, address buyToken, uint auctionIndex, uint sellVolume ) internal { // Get variables uint buyVolume = buyVolumes[sellToken][buyToken]; uint sellVolumeOpp = sellVolumesCurrent[buyToken][sellToken]; uint closingPriceOppDen = closingPrices[buyToken][sellToken][auctionIndex].den; uint auctionStart = getAuctionStart(sellToken, buyToken); // Update closing price if (sellVolume > 0) { closingPrices[sellToken][buyToken][auctionIndex] = fraction(buyVolume, sellVolume); } // if (opposite is 0 auction OR price = 0 OR opposite auction cleared) // price = 0 happens if auction pair has been running for >= 24 hrs = 86400 if (sellVolumeOpp == 0 || now >= auctionStart + 86400 || closingPriceOppDen > 0) { // Close auction pair uint buyVolumeOpp = buyVolumes[buyToken][sellToken]; if (closingPriceOppDen == 0 && sellVolumeOpp > 0) { // Save opposite price closingPrices[buyToken][sellToken][auctionIndex] = fraction(buyVolumeOpp, sellVolumeOpp); } uint sellVolumeNext = sellVolumesNext[sellToken][buyToken]; uint sellVolumeNextOpp = sellVolumesNext[buyToken][sellToken]; // Update state variables for both auctions sellVolumesCurrent[sellToken][buyToken] = sellVolumeNext; if (sellVolumeNext > 0) { sellVolumesNext[sellToken][buyToken] = 0; } if (buyVolume > 0) { buyVolumes[sellToken][buyToken] = 0; } sellVolumesCurrent[buyToken][sellToken] = sellVolumeNextOpp; if (sellVolumeNextOpp > 0) { sellVolumesNext[buyToken][sellToken] = 0; } if (buyVolumeOpp > 0) { buyVolumes[buyToken][sellToken] = 0; } // Increment auction index setAuctionIndex(sellToken, buyToken); // Check if next auction can be scheduled scheduleNextAuction(sellToken, buyToken); } AuctionCleared(sellToken, buyToken, sellVolume, buyVolume, auctionIndex); } function scheduleNextAuction( address sellToken, address buyToken ) internal { // Check if auctions received enough sell orders uint ethUSDPrice = ethUSDOracle.getUSDETHPrice(); uint sellNum; uint sellDen; (sellNum, sellDen) = getPriceOfTokenInLastAuction(sellToken); uint buyNum; uint buyDen; (buyNum, buyDen) = getPriceOfTokenInLastAuction(buyToken); // We use current sell volume, because in clearAuction() we set // sellVolumesCurrent = sellVolumesNext before calling this function // (this is so that we don&#39;t need case work, // since it might also be called from postSellOrder()) // < 10^30 * 10^31 * 10^6 = 10^67 uint sellVolume = mul(mul(sellVolumesCurrent[sellToken][buyToken], sellNum), ethUSDPrice) / sellDen; uint sellVolumeOpp = mul(mul(sellVolumesCurrent[buyToken][sellToken], buyNum), ethUSDPrice) / buyDen; if (sellVolume >= thresholdNewAuction || sellVolumeOpp >= thresholdNewAuction) { // Schedule next auction setAuctionStart(sellToken, buyToken, WAITING_PERIOD_NEW_AUCTION); } else { resetAuctionStart(sellToken, buyToken); } } //@ dev returns price in units [token2]/[token1] //@ param token1 first token for price calculation //@ param token2 second token for price calculation //@ param auctionIndex index for the auction to get the averaged price from function getPriceInPastAuction( address token1, address token2, uint auctionIndex ) public view // price < 10^31 returns (uint num, uint den) { if (token1 == token2) { // C1 num = 1; den = 1; } else { // C2 // R2.1 require(auctionIndex >= 0); // C3 // R3.1 require(auctionIndex <= getAuctionIndex(token1, token2)); // auction still running uint i = 0; bool correctPair = false; fraction memory closingPriceToken1; fraction memory closingPriceToken2; while (!correctPair) { closingPriceToken2 = closingPrices[token2][token1][auctionIndex - i]; closingPriceToken1 = closingPrices[token1][token2][auctionIndex - i]; if (closingPriceToken1.num > 0 && closingPriceToken1.den > 0 || closingPriceToken2.num > 0 && closingPriceToken2.den > 0) { correctPair = true; } i++; } // At this point at least one closing price is strictly positive // If only one is positive, we want to output that if (closingPriceToken1.num == 0 || closingPriceToken1.den == 0) { num = closingPriceToken2.den; den = closingPriceToken2.num; } else if (closingPriceToken2.num == 0 || closingPriceToken2.den == 0) { num = closingPriceToken1.num; den = closingPriceToken1.den; } else { // If both prices are positive, output weighted average num = closingPriceToken2.den + closingPriceToken1.num; den = closingPriceToken2.num + closingPriceToken1.den; } } } /// @dev Gives best estimate for market price of a token in ETH of any price oracle on the Ethereum network /// @param token address of ERC-20 token /// @return Weighted average of closing prices of opposite Token-ethToken auctions, based on their sellVolume function getPriceOfTokenInLastAuction( address token ) public view // price < 10^31 returns (uint num, uint den) { uint latestAuctionIndex = getAuctionIndex(token, ethToken); // getPriceInPastAuction < 10^30 (num, den) = getPriceInPastAuction(token, ethToken, latestAuctionIndex - 1); } function getCurrentAuctionPrice( address sellToken, address buyToken, uint auctionIndex ) public view // price < 10^37 returns (uint num, uint den) { fraction memory closingPrice = closingPrices[sellToken][buyToken][auctionIndex]; if (closingPrice.den != 0) { // Auction has closed (num, den) = (closingPrice.num, closingPrice.den); } else if (auctionIndex > getAuctionIndex(sellToken, buyToken)) { (num, den) = (0, 0); } else { // Auction is running uint pastNum; uint pastDen; (pastNum, pastDen) = getPriceInPastAuction(sellToken, buyToken, auctionIndex - 1); // If we&#39;re calling the function into an unstarted auction, // it will return the starting price of that auction uint timeElapsed = atleastZero(int(now - getAuctionStart(sellToken, buyToken))); // The numbers below are chosen such that // P(0 hrs) = 2 * lastClosingPrice, P(6 hrs) = lastClosingPrice, P(>=24 hrs) = 0 // 10^5 * 10^31 = 10^36 num = atleastZero(int((86400 - timeElapsed) * pastNum)); // 10^6 * 10^31 = 10^37 den = mul((timeElapsed + 43200), pastDen); if (mul(num, sellVolumesCurrent[sellToken][buyToken]) <= mul(den, buyVolumes[sellToken][buyToken])) { num = buyVolumes[sellToken][buyToken]; den = sellVolumesCurrent[sellToken][buyToken]; } } } function depositAndSell( address sellToken, address buyToken, uint amount ) external returns (uint newBal, uint auctionIndex, uint newSellerBal) { newBal = deposit(sellToken, amount); (auctionIndex, newSellerBal) = postSellOrder(sellToken, buyToken, 0, amount); } function claimAndWithdraw( address sellToken, address buyToken, address user, uint auctionIndex, uint amount ) external returns (uint returned, uint frtsIssued, uint newBal) { (returned, frtsIssued) = claimSellerFunds(sellToken, buyToken, user, auctionIndex); newBal = withdraw(buyToken, amount); } // > Helper fns function getTokenOrder( address token1, address token2 ) public pure returns (address, address) { if (token2 < token1) { (token1, token2) = (token2, token1); } return (token1, token2); } function setAuctionStart( address token1, address token2, uint value ) internal { (token1, token2) = getTokenOrder(token1, token2); uint auctionStart = now + value; uint auctionIndex = latestAuctionIndices[token1][token2]; auctionStarts[token1][token2] = auctionStart; AuctionStartScheduled(token1, token2, auctionIndex, auctionStart); } function resetAuctionStart( address token1, address token2 ) internal { (token1, token2) = getTokenOrder(token1, token2); if (auctionStarts[token1][token2] != AUCTION_START_WAITING_FOR_FUNDING) { auctionStarts[token1][token2] = AUCTION_START_WAITING_FOR_FUNDING; } } function getAuctionStart( address token1, address token2 ) public view returns (uint auctionStart) { (token1, token2) = getTokenOrder(token1, token2); auctionStart = auctionStarts[token1][token2]; } function setAuctionIndex( address token1, address token2 ) internal { (token1, token2) = getTokenOrder(token1, token2); latestAuctionIndices[token1][token2] += 1; } function getAuctionIndex( address token1, address token2 ) public view returns (uint auctionIndex) { (token1, token2) = getTokenOrder(token1, token2); auctionIndex = latestAuctionIndices[token1][token2]; } // > Math fns function min(uint a, uint b) public pure returns (uint) { if (a < b) { return a; } else { return b; } } function atleastZero(int a) public pure returns (uint) { if (a < 0) { return 0; } else { return uint(a); } } /// @dev Returns whether an add operation causes an overflow /// @param a First addend /// @param b Second addend /// @return Did no overflow occur? function safeToAdd(uint a, uint b) public pure returns (bool) { return a + b >= a; } /// @dev Returns whether a subtraction operation causes an underflow /// @param a Minuend /// @param b Subtrahend /// @return Did no underflow occur? function safeToSub(uint a, uint b) public pure returns (bool) { return a >= b; } /// @dev Returns whether a multiply operation causes an overflow /// @param a First factor /// @param b Second factor /// @return Did no overflow occur? function safeToMul(uint a, uint b) public pure returns (bool) { return b == 0 || a * b / b == a; } /// @dev Returns sum if no overflow occurred /// @param a First addend /// @param b Second addend /// @return Sum function add(uint a, uint b) public pure returns (uint) { require(safeToAdd(a, b)); return a + b; } /// @dev Returns difference if no overflow occurred /// @param a Minuend /// @param b Subtrahend /// @return Difference function sub(uint a, uint b) public pure returns (uint) { require(safeToSub(a, b)); return a - b; } /// @dev Returns product if no overflow occurred /// @param a First factor /// @param b Second factor /// @return Product function mul(uint a, uint b) public pure returns (uint) { require(safeToMul(a, b)); return a * b; } function getRunningTokenPairs( address[] tokens ) external view returns (address[] tokens1, address[] tokens2) { uint arrayLength; for (uint k = 0; k < tokens.length - 1; k++) { for (uint l = k + 1; l < tokens.length; l++) { if (getAuctionIndex(tokens[k], tokens[l]) > 0) { arrayLength++; } } } tokens1 = new address[](arrayLength); tokens2 = new address[](arrayLength); uint h; for (uint i = 0; i < tokens.length - 1; i++) { for (uint j = i + 1; j < tokens.length; j++) { if (getAuctionIndex(tokens[i], tokens[j]) > 0) { tokens1[h] = tokens[i]; tokens2[h] = tokens[j]; h++; } } } } //@dev for quick overview of possible sellerBalances to calculate the possible withdraw tokens //@param auctionSellToken is the sellToken defining an auctionPair //@param auctionBuyToken is the buyToken defining an auctionPair //@param user is the user who wants to his tokens //@param lastNAuctions how many auctions will be checked. 0 means all //@returns returns sellbal for all indices for all tokenpairs function getIndicesWithClaimableTokensForSellers( address auctionSellToken, address auctionBuyToken, address user, uint lastNAuctions ) external view returns(uint[] indices, uint[] usersBalances) { uint runningAuctionIndex = getAuctionIndex(auctionSellToken, auctionBuyToken); uint arrayLength; uint startingIndex = lastNAuctions == 0 ? 1 : runningAuctionIndex - lastNAuctions + 1; for (uint j = startingIndex; j <= runningAuctionIndex; j++) { if (sellerBalances[auctionSellToken][auctionBuyToken][j][user] > 0) { arrayLength++; } } indices = new uint[](arrayLength); usersBalances = new uint[](arrayLength); uint k; for (uint i = startingIndex; i <= runningAuctionIndex; i++) { if (sellerBalances[auctionSellToken][auctionBuyToken][i][user] > 0) { indices[k] = i; usersBalances[k] = sellerBalances[auctionSellToken][auctionBuyToken][i][user]; k++; } } } //@dev for quick overview of current sellerBalances for a user //@param auctionSellTokens are the sellTokens defining an auctionPair //@param auctionBuyTokens are the buyTokens defining an auctionPair //@param user is the user who wants to his tokens function getSellerBalancesOfCurrentAuctions( address[] auctionSellTokens, address[] auctionBuyTokens, address user ) external view returns (uint[]) { uint length = auctionSellTokens.length; uint length2 = auctionBuyTokens.length; require(length == length2); uint[] memory sellersBalances = new uint[](length); for (uint i = 0; i < length; i++) { uint runningAuctionIndex = getAuctionIndex(auctionSellTokens[i], auctionBuyTokens[i]); sellersBalances[i] = sellerBalances[auctionSellTokens[i]][auctionBuyTokens[i]][runningAuctionIndex][user]; } return sellersBalances; } //@dev for quick overview of possible buyerBalances to calculate the possible withdraw tokens //@param auctionSellToken is the sellToken defining an auctionPair //@param auctionBuyToken is the buyToken defining an auctionPair //@param user is the user who wants to his tokens //@param lastNAuctions how many auctions will be checked. 0 means all //@returns returns sellbal for all indices for all tokenpairs function getIndicesWithClaimableTokensForBuyers( address auctionSellToken, address auctionBuyToken, address user, uint lastNAuctions ) external view returns(uint[] indices, uint[] usersBalances) { uint runningAuctionIndex = getAuctionIndex(auctionSellToken, auctionBuyToken); uint arrayLength; uint startingIndex = lastNAuctions == 0 ? 1 : runningAuctionIndex - lastNAuctions + 1; for (uint j = startingIndex; j <= runningAuctionIndex; j++) { if (buyerBalances[auctionSellToken][auctionBuyToken][j][user] > 0) { arrayLength++; } } indices = new uint[](arrayLength); usersBalances = new uint[](arrayLength); uint k; for (uint i = startingIndex; i <= runningAuctionIndex; i++) { if (buyerBalances[auctionSellToken][auctionBuyToken][i][user] > 0) { indices[k] = i; usersBalances[k] = buyerBalances[auctionSellToken][auctionBuyToken][i][user]; k++; } } } //@dev for quick overview of current sellerBalances for a user //@param auctionSellTokens are the sellTokens defining an auctionPair //@param auctionBuyTokens are the buyTokens defining an auctionPair //@param user is the user who wants to his tokens function getBuyerBalancesOfCurrentAuctions( address[] auctionSellTokens, address[] auctionBuyTokens, address user ) external view returns (uint[]) { uint length = auctionSellTokens.length; uint length2 = auctionBuyTokens.length; require(length == length2); uint[] memory buyersBalances = new uint[](length); for (uint i = 0; i < length; i++) { uint runningAuctionIndex = getAuctionIndex(auctionSellTokens[i], auctionBuyTokens[i]); buyersBalances[i] = buyerBalances[auctionSellTokens[i]][auctionBuyTokens[i]][runningAuctionIndex][user]; } return buyersBalances; } //@dev for quick overview of approved Tokens //@param addressesToCheck are the ERC-20 token addresses to be checked whether they are approved function getApprovedAddressesOfList( address[] addressToCheck ) external view returns (bool[]) { uint length = addressToCheck.length; bool[] memory isApproved = new bool[](length); for (uint i = 0; i < length; i++) { isApproved[i] = approvedTokens[addressToCheck[i]]; } return isApproved; } //@dev for multiple withdraws //@param auctionSellTokens are the sellTokens defining an auctionPair //@param auctionBuyTokens are the buyTokens defining an auctionPair //@param auctionIndices are the auction indices on which an token should be claimedAmounts //@param user is the user who wants to his tokens function claimTokensFromSeveralAuctionsAsSeller( address[] auctionSellTokens, address[] auctionBuyTokens, uint[] auctionIndices, address user ) external { uint length = auctionSellTokens.length; uint length2 = auctionBuyTokens.length; require(length == length2); uint length3 = auctionIndices.length; require(length2 == length3); for (uint i = 0; i < length; i++) claimSellerFunds(auctionSellTokens[i], auctionBuyTokens[i], user, auctionIndices[i]); } //@dev for multiple withdraws //@param auctionSellTokens are the sellTokens defining an auctionPair //@param auctionBuyTokens are the buyTokens defining an auctionPair //@param auctionIndices are the auction indices on which an token should be claimedAmounts //@param user is the user who wants to his tokens function claimTokensFromSeveralAuctionsAsBuyer( address[] auctionSellTokens, address[] auctionBuyTokens, uint[] auctionIndices, address user ) external { uint length = auctionSellTokens.length; uint length2 = auctionBuyTokens.length; require(length == length2); uint length3 = auctionIndices.length; require(length2 == length3); for (uint i = 0; i < length; i++) claimBuyerFunds(auctionSellTokens[i], auctionBuyTokens[i], user, auctionIndices[i]); } function getMasterCopy() external view returns (address) { return masterCopy; } // > Events event NewDeposit( address indexed token, uint amount ); event NewOracleProposal( PriceOracleInterface priceOracleInterface ); event NewMasterCopyProposal( address newMasterCopy ); event NewWithdrawal( address indexed token, uint amount ); event NewSellOrder( address indexed sellToken, address indexed buyToken, address indexed user, uint auctionIndex, uint amount ); event NewBuyOrder( address indexed sellToken, address indexed buyToken, address indexed user, uint auctionIndex, uint amount ); event NewSellerFundsClaim( address indexed sellToken, address indexed buyToken, address indexed user, uint auctionIndex, uint amount, uint frtsIssued ); event NewBuyerFundsClaim( address indexed sellToken, address indexed buyToken, address indexed user, uint auctionIndex, uint amount, uint frtsIssued ); event NewTokenPair( address indexed sellToken, address indexed buyToken ); event AuctionCleared( address indexed sellToken, address indexed buyToken, uint sellVolume, uint buyVolume, uint indexed auctionIndex ); event Approval( address indexed token, bool approved ); event AuctionStartScheduled( address indexed sellToken, address indexed buyToken, uint indexed auctionIndex, uint auctionStart ); event Fee( address indexed primaryToken, address indexed secondarToken, address indexed user, uint auctionIndex, uint fee ); }
for quick overview of current sellerBalances for a user auctionSellTokens are the sellTokens defining an auctionPair auctionBuyTokens are the buyTokens defining an auctionPair user is the user who wants to his tokens
function getSellerBalancesOfCurrentAuctions( address[] auctionSellTokens, address[] auctionBuyTokens, address user ) external view returns (uint[]) { uint length = auctionSellTokens.length; uint length2 = auctionBuyTokens.length; require(length == length2); uint[] memory sellersBalances = new uint[](length); for (uint i = 0; i < length; i++) { uint runningAuctionIndex = getAuctionIndex(auctionSellTokens[i], auctionBuyTokens[i]); sellersBalances[i] = sellerBalances[auctionSellTokens[i]][auctionBuyTokens[i]][runningAuctionIndex][user]; } return sellersBalances; }
7,683,290
./partial_match/1/0x0059A21dAc9730DE83A7d624921c66c05f102ca2/sources/PersonalCornerSale.sol
Duplicate Token name for cloneability Duplicate Token symbol for cloneability informational support for external sites that respected Ownable
{ event TokenMetadataChanged(uint256 tokenId); event TokenRedeemed(uint256 tokenId, uint256 timestamp, string memo); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant REDEEM_ROLE = keccak256("REDEEM_ROLE"); string private _name; string private _symbol; address private _legacyOwner; address public tokenDataContract; function initialize( string memory name_, string memory symbol_, address tokenDataContract_, address initialAdmin ) public override initializer { _name = name_; _symbol = symbol_; _legacyOwner = initialAdmin; tokenDataContract = tokenDataContract_; _setupRole(DEFAULT_ADMIN_ROLE, initialAdmin); emit OwnershipTransferred(address(0), initialAdmin); } constructor( string memory name_, string memory symbol_, address tokenDataContract_ ) ERC721(name_, symbol_) { initialize(name_, symbol_, tokenDataContract_, msg.sender); } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function owner() public view returns (address) { return _legacyOwner; } function transferLegacyOwnership(address newOwner) public onlyRole(DEFAULT_ADMIN_ROLE) { require(newOwner != address(0), "new owner is null"); _legacyOwner = newOwner; emit OwnershipTransferred(_legacyOwner, newOwner); } bytes4 private constant _INTERFACE_ID_FEES = 0xb7799584; function getFeeRecipients(uint256 tokenId) public view returns (address payable[] memory) { return INamelessTokenData(tokenDataContract).getFeeRecipients(tokenId); } function getFeeBps(uint256 tokenId) public view returns (uint256[] memory) { return INamelessTokenData(tokenDataContract).getFeeBps(tokenId); } function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "no such token"); return INamelessTokenData(tokenDataContract).getTokenURI( tokenId, ownerOf(tokenId) ); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if ( INamelessTokenData(tokenDataContract).beforeTokenTransfer( from, to, tokenId ) ) { emit TokenMetadataChanged(tokenId); } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if ( INamelessTokenData(tokenDataContract).beforeTokenTransfer( from, to, tokenId ) ) { emit TokenMetadataChanged(tokenId); } } function redeem( uint256 tokenId, uint256 timestamp, string calldata memo ) public onlyRole(REDEEM_ROLE) { INamelessTokenData(tokenDataContract).redeem(tokenId); emit TokenRedeemed(tokenId, timestamp, memo); } function mint(address to, uint256 tokenId) public onlyRole(MINTER_ROLE) { _safeMint(to, tokenId); } function mint( address creator, address recipient, uint256 tokenId ) public onlyRole(MINTER_ROLE) { _safeMint(creator, tokenId); _safeTransfer(creator, recipient, tokenId, ""); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable, AccessControl) returns (bool) { return interfaceId == _INTERFACE_ID_FEES || ERC721Enumerable.supportsInterface(interfaceId) || AccessControl.supportsInterface(interfaceId); } }
3,688,575
// SPDX-License-Identifier: None pragma solidity 0.6.12; import "../BoilerplateStrategy.sol"; import "../../interfaces/curvefi/IYERC20.sol"; import "../../interfaces/curvefi/ICurveFi_DepositY.sol"; import "../../interfaces/curvefi/ICurveFi_SwapY.sol"; import "../../interfaces/uniswap/IUniswapV2Router02.sol"; /** * The goal of this strategy is to take a stable asset (DAI, USDC, USDT), turn it into ycrv using * the curve mechanisms, and supply ycrv into the ycrv vault. The ycrv vault will likely not have * a reward token distribution pool to avoid double dipping. All the calls to functions from this * strategy will be routed to the controller which should then call the respective methods on the * ycrv vault. This strategy will not be liquidating any yield crops (CRV), because the strategy * of the ycrv vault will do that for us. */ contract CRVStrategyStable is IStrategy, BoilerplateStrategy { enum TokenIndex {DAI, USDC, USDT, TUSD} using SafeERC20 for IERC20; using SafeMath for uint256; // the matching enum record used to determine the index TokenIndex tokenIndex; // the y-asset corresponding to our asset address public yToken; // the address of yCRV token address public ycrv; address public yycrv; // the address of the Curve protocol(DepositY, SwapY) address public curve; address public swap; constructor( address _vault, address _underlying, address _strategist, address _curve, address _swap, address _ycrv, address _yycrv, address _yToken, uint256 _tokenIndex ) public BoilerplateStrategy(_vault, _underlying, _strategist) { require(IVault(_vault).token() == _underlying, "vault does not support underlying"); tokenIndex = TokenIndex(_tokenIndex); yycrv = _yycrv; ycrv = _ycrv; curve = _curve; swap = _swap; yToken = _yToken; // set these tokens to be not salvageable unsalvageableTokens[underlying] = true; unsalvageableTokens[yycrv] = true; unsalvageableTokens[ycrv] = true; unsalvageableTokens[yToken] = true; } /***** * VIEW INTERFACE *****/ function getNameStrategy() external view override returns (string memory) { return "CRVStrategyStable"; } function want() external view override returns (address) { return underlying; } /** * Returns the underlying invested balance. This is the amount of yCRV that we are entitled to * from the yCRV vault (based on the number of shares we currently have), converted to the * underlying assets by the Curve protocol, plus the current balance of the underlying assets. */ function balanceOf() public view override returns (uint256) { uint256 stableBal = balanceOfUnderlying(); return stableBal.add(IERC20(underlying).balanceOf(address(this))); } function balanceOfUnderlying() public view returns(uint256) { uint256 yycrvShares = IERC20(yycrv).balanceOf(address(this)); uint256 ycrvBal = yycrvShares.mul(IYERC20(yycrv).getPricePerFullShare()).div(1e18); int128 tokenIdx = int128(tokenIndex); if(ycrvBal > 0) { return ICurveFi_DepositY(curve).calc_withdraw_one_coin(ycrvBal, tokenIdx); } return 0; } /***** * DEPOSIT/WITHDRAW/HARVEST EXTERNAL *****/ /** * Invests all underlying assets into our yCRV vault. */ function deposit() public override { // convert the entire balance not yet invested into yCRV first yCurveFromUnderlying(); // then deposit into the yCRV vault uint256 ycrvBalance = IERC20(ycrv).balanceOf(address(this)); if (ycrvBalance > 0) { IERC20(ycrv).safeApprove(yycrv, 0); IERC20(ycrv).safeApprove(yycrv, ycrvBalance); // deposits the entire balance and also asks the vault to invest it (public function) IYERC20(yycrv).deposit(ycrvBalance); } } /** * Withdraws an underlying asset from the strategy to the vault in the specified amount by asking * the yCRV vault for yCRV (currently all of it), and then removing imbalanced liquidity from * the Curve protocol. The rest is deposited back to the yCRV vault. If the amount requested cannot * be obtained, the method will get as much as we have. */ function withdraw(uint256 amountUnderlying) public override restricted { require(amountUnderlying > 0, "Incorrect amount"); uint256 balanceUnderlying = balanceOfUnderlying(); uint256 looseBalance = IERC20(underlying).balanceOf(address(this)); uint256 total = balanceUnderlying.add(looseBalance); if (amountUnderlying > total) { //cant withdraw more than we own amountUnderlying = total; } if (looseBalance >= amountUnderlying) { IERC20(underlying).safeTransfer(vault, amountUnderlying); return; } uint256 toWithdraw = amountUnderlying.sub(looseBalance); _withdrawSome(toWithdraw); looseBalance = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransfer(vault, looseBalance); } /** * Withdraws all the yCRV tokens to the pool. */ function withdrawAll() external override restricted { _withdrawAll(); uint256 looseBalance = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransfer(vault, looseBalance); } function emergencyExit() external onlyGovernance { _withdrawAll(); uint256 looseBalance = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeTransfer(IVault(vault).governance(), looseBalance); } /** * Claims and liquidates CRV into yCRV, and then invests all underlying. */ function earn() public restricted { deposit(); } /** * Uses the Curve protocol to convert the underlying asset into yAsset and then to yCRV. */ function yCurveFromUnderlying() internal { // convert underlying asset to yAsset uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this)); IERC20(underlying).safeApprove(curve, 0); IERC20(underlying).safeApprove(curve, underlyingBalance); uint256 minimum = 0; uint256[4] memory amounts = wrapCoinAmount(underlyingBalance); ICurveFi_DepositY(curve).add_liquidity(amounts, minimum); // now we have yCRV } function _withdrawSome(uint256 _amount) internal returns (uint256) { // calculate amount of ycrv to withdraw for amount of _want_ uint256 _ycrv = _amount.mul(1e18).div(ICurveFi_SwapY(swap).get_virtual_price()); // calculate amount of yycrv to withdraw for amount of _ycrv_ uint256 _yycrv = _ycrv.mul(1e18).div(IYERC20(yycrv).getPricePerFullShare()); uint256 _before = IERC20(ycrv).balanceOf(address(this)); IYERC20(yycrv).withdraw(_yycrv); uint256 _after = IERC20(ycrv).balanceOf(address(this)); return withdrawUnderlying(_after.sub(_before)); } function _withdrawAll() internal returns(uint256) { uint256 _yycrv = IERC20(yycrv).balanceOf(address(this)); IYERC20(yycrv).withdraw(_yycrv); return withdrawUnderlying(_yycrv); } function withdrawUnderlying(uint256 _amount) internal returns (uint256) { IERC20(ycrv).safeApprove(curve, 0); IERC20(ycrv).safeApprove(curve, _amount); uint256 _before = IERC20(underlying).balanceOf(address(this)); ICurveFi_DepositY(curve).remove_liquidity_one_coin(_amount, int128(tokenIndex), 0); uint256 _after = IERC20(underlying).balanceOf(address(this)); return _after.sub(_before); } /** * Wraps the coin amount in the array for interacting with the Curve protocol */ function wrapCoinAmount(uint256 amount) internal view returns (uint256[4] memory) { uint256[4] memory amounts = [uint256(0), uint256(0), uint256(0), uint256(0)]; amounts[uint56(tokenIndex)] = amount; return amounts; } function convert(address) external override returns (uint256) { revert("Can't convert"); return 0; } function skim() external override { revert("Can't skim"); } } // SPDX-License-Identifier: None pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/yearn/IVault.sol"; import "../interfaces/yearn/IStrategy.sol"; abstract contract BoilerplateStrategy is IStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; enum Setting { CONTROLLER_SET, STRATEGIST_SET, PROFIT_SHARING_SET, LIQ_ALLOWED_SET, HARVEST_ALLOWED_SET, SELL_FLOOR_SET } address public underlying; address public strategist; address public controller; address public vault; uint256 public profitSharingNumerator; uint256 public profitSharingDenominator; bool public harvestOnWithdraw; bool public liquidationAllowed = true; uint256 public sellFloor = 0; // These tokens cannot be claimed by the controller mapping(address => bool) public unsalvageableTokens; event ProfitShared(uint256 amount, uint256 fee, uint256 timestamp); event SettingChanged(Setting setting, address initiator, uint timestamp); modifier restricted() { require( msg.sender == vault || msg.sender == controller || msg.sender == IVault(vault).governance() || msg.sender == strategist, "Sender must be privileged" ); _; } modifier onlyGovernance() { require(msg.sender == IVault(vault).governance(), "!governance"); _; } constructor(address _vault, address _underlying, address _strategist) public { vault = _vault; underlying = _underlying; strategist = _strategist; harvestOnWithdraw = true; profitSharingNumerator = 30; profitSharingDenominator = 100; require(IVault(vault).token() == _underlying, "vault does not support underlying"); controller = IVault(vault).controller(); } function setController(address _controller) external onlyGovernance { controller = _controller; emit SettingChanged(Setting.CONTROLLER_SET, msg.sender, block.timestamp); } function setStrategist(address _strategist) external restricted { strategist = _strategist; emit SettingChanged(Setting.STRATEGIST_SET, msg.sender, block.timestamp); } function setProfitSharing(uint256 _profitSharingNumerator, uint256 _profitSharingDenominator) external restricted { require(_profitSharingDenominator > 0, "Incorrect denominator"); require(_profitSharingNumerator < _profitSharingDenominator, "Numerator < Denominator"); profitSharingNumerator = _profitSharingNumerator; profitSharingDenominator = _profitSharingDenominator; emit SettingChanged(Setting.PROFIT_SHARING_SET, msg.sender, block.timestamp); } function setHarvestOnWithdraw(bool _flag) external restricted { harvestOnWithdraw = _flag; emit SettingChanged(Setting.HARVEST_ALLOWED_SET, msg.sender, block.timestamp); } /** * Allows liquidation */ function setLiquidationAllowed(bool allowed) external restricted { liquidationAllowed = allowed; emit SettingChanged(Setting.LIQ_ALLOWED_SET, msg.sender, block.timestamp); } function setSellFloor(uint256 value) external restricted { sellFloor = value; emit SettingChanged(Setting.SELL_FLOOR_SET, msg.sender, block.timestamp); } /** * Withdraws a token. */ function withdraw(address token) external override restricted { // To make sure that governance cannot come in and take away the coins require(!unsalvageableTokens[token], "!salvageable"); uint256 balance = IERC20(token).balanceOf(address(this)); IERC20(token).safeTransfer(vault, balance); } function _profitSharing(uint256 amount) internal virtual { if (profitSharingNumerator == 0) { return; } uint256 feeAmount = amount.mul(profitSharingNumerator).div(profitSharingDenominator); emit ProfitShared(amount, feeAmount, block.timestamp); if(feeAmount > 0) { IERC20(underlying).safeTransfer(controller, feeAmount); } } } // SPDX-License-Identifier: None pragma solidity 0.6.12; interface IYERC20 { // //ERC20 functions // function totalSupply() external view returns (uint256); // function balanceOf(address account) external view returns (uint256); // function transfer(address recipient, uint256 amount) external returns (bool); // function allowance(address owner, address spender) external view returns (uint256); // function approve(address spender, uint256 amount) external returns (bool); // function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); // function name() external view returns (string memory); // function symbol() external view returns (string memory); // function decimals() external view returns (uint8); //Y-token functions function deposit(uint256 amount) external; function withdraw(uint256 shares) external; function getPricePerFullShare() external view returns (uint256); function token() external returns(address); } // SPDX-License-Identifier: None pragma solidity 0.6.12; /** * @dev Interface for Curve.Fi deposit contract for Y-pool. * @dev See original implementation in official repository: * https://github.com/curvefi/curve-contract/blob/master/contracts/pools/y/DepositY.vy */ interface ICurveFi_DepositY { function add_liquidity(uint256[4] calldata uamounts, uint256 min_mint_amount) external; function remove_liquidity(uint256 _amount, uint256[4] calldata min_uamounts) external; function remove_liquidity_imbalance(uint256[4] calldata uamounts, uint256 max_burn_amount) external; function remove_liquidity_one_coin(uint256 _token_amount, int128 i, uint256 min_uamount) external; function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns(uint256); function coins(int128 i) external view returns (address); function underlying_coins(int128 i) external view returns (address); function underlying_coins() external view returns (address[4] memory); function curve() external view returns (address); function token() external view returns (address); } // SPDX-License-Identifier: None pragma solidity 0.6.12; /** * @dev Interface for Curve.Fi swap contract for Y-pool. * @dev See original implementation in official repository: * https://github.com/curvefi/curve-contract/blob/master/contracts/pools/y/StableSwapY.vy */ interface ICurveFi_SwapY { function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity(uint256 _amount, uint256[4] calldata min_amounts) external; function remove_liquidity_imbalance(uint256[4] calldata amounts, uint256 max_burn_amount) external; function calc_token_amount(uint256[4] calldata amounts, bool deposit) external view returns(uint256); function balances(int128 i) external view returns(uint256); function coins(int128 i) external view returns (address); function get_virtual_price() external view returns(uint256); } // SPDX-License-Identifier: None 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; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IVault { function token() external view returns (address); function controller() external view returns (address); function governance() external view returns (address); function getPricePerFullShare() external view returns (uint256); function deposit(uint256) external; function depositAll() external; function withdraw(uint256) external; function withdrawAll() external; // Part of ERC20 interface //function name() external view returns (string memory); //function symbol() external view returns (string memory); //function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IStrategy { /// @notice Returns the name of the strategy /// @dev The name is set when the strategy is deployed /// @return Returns the name of the strategy function getNameStrategy() external view returns (string memory); /// @notice Returns the want address of the strategy /// @dev The want is set when the strategy is deployed /// @return Returns the name of the strategy function want() external view returns (address); /// @notice Shows the balance of the strategy. function balanceOf() external view returns (uint256); /// @notice Transfers tokens for earnings function deposit() external; // NOTE: must exclude any tokens used in the yield /// @notice Controller role - withdraw should return to Controller function withdraw(address) external; /// @notice Controller | Vault role - withdraw should always return to Vault function withdraw(uint256) external; /// @notice Controller | Vault role - withdraw should always return to Vault function withdrawAll() external; /// @notice Calls to the method to convert the required token to the want token function convert(address _token) external returns(uint256); function skim() external; } // SPDX-License-Identifier: None 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); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
Invests all underlying assets into our yCRV vault./ convert the entire balance not yet invested into yCRV first then deposit into the yCRV vault deposits the entire balance and also asks the vault to invest it (public function)
function deposit() public override { yCurveFromUnderlying(); uint256 ycrvBalance = IERC20(ycrv).balanceOf(address(this)); if (ycrvBalance > 0) { IERC20(ycrv).safeApprove(yycrv, 0); IERC20(ycrv).safeApprove(yycrv, ycrvBalance); IYERC20(yycrv).deposit(ycrvBalance); } }
12,085,148
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /*import "Register.sol"; import "Agora.sol"; import "Loi.sol"; import "API_Register.sol"; import "Delegation.sol"; import "IDelegation.sol"; import "Citizens_Register.sol"; import "IVote.sol"; */ import "contracts/Register.sol"; import "contracts/Agora.sol"; import "contracts/Loi.sol"; import "contracts/API_Register.sol"; import "contracts/Delegation.sol"; import "contracts/Citizens_Register.sol"; import "contracts/IVote.sol"; /** * @notice {Constitution_Register} library is used to reduce the size of Constitution contract in order to avoid to exceed contract limit size. It contains heavy functions and data structures. */ library Constitution_Register{ /** * @dev Deploy a {Loi} contract and returns it's address. * @param Loi_Name Name of the Loi contract * @param agora Addres of the Project's {Agora} contract */ function Create_Loi(string memory Loi_Name, address agora)external returns(address){ Loi loi = new Loi(Loi_Name, agora); //loi.Add_Authority(authority); return address(loi); } /** * @dev Deploy a {API_Register} contract and returns it's address. * @param Name Name of the API_Register contract * @param agora Addres of the Project's {Agora} contract */ function Create_API(string memory Name, address agora) external returns(address){ return address(new API_Register(Name, agora)); } } /** * @notice {Constitution_Delegation} library is used to reduce the size of Constitution contract in order to avoid to exceed contract limit size. It contains heavy functions and data structures. */ library Constitution_Delegation{ /** * @dev Deploy a {Delegation} contract and returns it's address. * @param Delegation_Name Name of the Delegation contract * @param Initial_members List of initial memebers of the delegation * @param Token_Address Address of the Project's {DemoCoin} contract * @param citizen_address Addres of the Project's {Citizens_Register} contract * @param agora_address Addres of the Project's {Agora} contract */ function Create_Delegation(string memory Delegation_Name, address[] calldata Initial_members, address Token_Address, address citizen_address, address agora_address)external returns(address){ Delegation delegation = new Delegation(Delegation_Name, Initial_members, Token_Address, citizen_address, agora_address); return address(delegation); } } /** * @notice Constitution register contract is used to edit parameters of a Web3 Direct Democracy project. * It contains address of all deployed contracts used in a project. Particularly, it contains a list of address of all register contracts that are used in the project, and another list for all Delegations. * Hence, Constitution is the central contract in a project. To launch a Web3 Direct Democracy project, we have to launch the Constitution contract. * From Constitution deployed contract, we can have access to all the project. There is a single Constitution contract in a project. * With Constitution register contract, we can add new register and delegations to the project, we can modify their democratic process parameters, change other register’s _Register_Authorities_ array… * Constitution contract goal is to customize the project to specific use cases and to keep it updatable. * * Once a Web3 Direct Democracy project has just been deployed, it hasn’t any register or delegation. Citizens_Register and DemoCoin contracts haven’t any authority in their _Register_Authorities_ list. * Thus, at the beginning of a Web3 Direct Democracy project, we need an initialisation stage. * In this initialisation stage, there is a _Transitional_Government_ account that has authority on the constitution and can quickly perform necessary operations without passing by any democratic process : */ contract Constitution is Register{ using EnumerableSet for EnumerableSet.AddressSet; // event Register_Parameters_Modified(address); event Register_Created(address register); event Delegation_Created(address delegation); event Transitional_Government_Finised(); Agora public Agora_Instance; Citizens_Register public Citizen_Instance; DemoCoin public Democoin_Instance; //IVote public majority_judgment_ballot; //address public Citizens_Address; address public Transitional_Government; //mapping(address=>Constitution_Register.Register_Parameters) Registers; EnumerableSet.AddressSet Registers_Address_List; //mapping(address=>Constitution_Delegation.Delegation_Parameters) Delegations; EnumerableSet.AddressSet Delegation_Address_List; /** * @param Constitution_Name Name of the Constitution contract * @param DemoCoin_Address Address of the {DemoCoin} contract of the project * @param Citizen_Address Address of the {Citizens_Register} contract of the project * @param Agora_Address Address of the {Agora} contract of the project * @param transition_government Address of the Transitional_Government. */ constructor(string memory Constitution_Name, address DemoCoin_Address, address Citizen_Address, address Agora_Address, address transition_government) Register(Constitution_Name){ require(transition_government !=address(0)); Constitution_Address = address(this); //Type_Institution = Institution_Type.CONSTITUTION; /*Democoin = new DemoCoin(Token_Name, Token_Symbole, initial_citizens, initial_citizens_token_amount); Citizen_Instance = new Citizens_Register(Citizen_Name, initial_citizens, address(Democoin), new_citizen_mint_amount); Agora_Instance = new Agora(Agora_Name, address(Democoin), address(Citizen_Instance));*/ Democoin_Instance = DemoCoin(DemoCoin_Address); Citizen_Instance = Citizens_Register(Citizen_Address); Agora_Instance = Agora(Agora_Address); //majority_judgment_ballot = new majority_judgment_ballot(); //Citizens_Address = Constitution_Register.Create_Citizens(initial_citizens); Transitional_Government = transition_government; Register_Authorities.add(Transitional_Government); Register_Authorities.add(Agora_Address); } /** * @dev Function called by the {Transitional_Government} account to end the Transitional Government stage. This step is mandatory to start using a Web3 Direct Democracy in a safe way. */ function End_Transition_Government()external{ require(msg.sender == Transitional_Government, "Transitional_Government only"); Register_Authorities.remove(Transitional_Government); emit Transitional_Government_Finised(); } /** * @dev Add a new address to a Register contract's (contract that inherit from a {Register} abstract contract) {Register_Authorities} list. * @param register Address of the register contract * @param authority Address to add to the {Register_Authorities} list. */ function Add_Register_Authority(address register, address authority) external Register_Authorities_Only{ require(Registers_Address_List.contains(register), "Unknown Register"); Register res = Register(register); res.Add_Authority(authority); } /** * @dev Removes a, address from a Register contract's {Register_Authorities} list. * @param register Address of the register contract * @param authority Address to remove from the {Register_Authorities} list. */ function Remove_Register_Authority(address register, address authority) external Register_Authorities_Only{ require(Registers_Address_List.contains(register), "Unknown Register"); Register res = Register(register); res.Remove_Authority(authority); } /** * @dev Change the Constitution address of an Institution contract belonging to current project. After this call, this Institution will not recognize this Constitution anymore. * @param institution_address Address of the Institution contract * @param new_address New Constitution address of the {institution_address} Institution */ function Set_Instances_Constitution(address institution_address, address new_address)external Register_Authorities_Only{ require(Registers_Address_List.contains(institution_address) || Delegation_Address_List.contains(institution_address) || institution_address== address(Citizen_Instance), "instance address unknown"); // There is no interest to modify Agora's constitution. require(new_address!=address(0),"address 0"); Institution Insti = Institution(institution_address); Institution_Type type_insti = Insti.Type_Institution(); require(type_insti != Institution_Type.CONSTITUTION); Insti.Set_Constitution(new_address); } /** * @dev Change the Name of an Institution contract. * @param institution_address Address of the Institution contract * @param name New name of the {institution_address} Institution. */ function Set_Institution_Name(address institution_address, string calldata name)external Register_Authorities_Only{ require(Registers_Address_List.contains(institution_address) || Delegation_Address_List.contains(institution_address) || institution_address== address(Citizen_Instance) || institution_address== address(Agora_Instance), "instance address unknown"); Institution Insti = Institution(institution_address); Insti.Set_Name(name); } /*FUNCTIONCALL API functions*/ /*DemoCoin functions*/ /** * @dev Change address that are allowed to mint DemoCoin Token (Minter authorities). They are contained in the {Mint_Authorities} list of {DemoCoin} contract. * @param Add_Minter List of new Minter address * @param Remove_Minter List of Minter address to remove from {Mint_Authorities} */ function Set_Minnter(address[] calldata Add_Minter, address[] calldata Remove_Minter)external Register_Authorities_Only{ uint add_len=Add_Minter.length; uint remove_len = Remove_Minter.length; for(uint i =0; i<add_len;i++){ Democoin_Instance.Add_Minter(Add_Minter[i]); } for(uint j=0; j<remove_len; j++){ Democoin_Instance.Remove_Minter(Remove_Minter[j]); } } /** * @dev Change address that are allowed to burn DemoCoin Token (Burner authorities). They are contained in the {Burn_Authorities} list of {DemoCoin} contract. * @param Add_Burner List of new Burner address * @param Remove_Burner List of Burner address to remove from {Burn_Authorities} */ function Set_Burner(address[] calldata Add_Burner, address[] calldata Remove_Burner)external Register_Authorities_Only{ uint add_len=Add_Burner.length; uint remove_len = Remove_Burner.length; for(uint i =0; i<add_len;i++){ Democoin_Instance.Add_Burner(Add_Burner[i]); } for(uint j=0; j<remove_len; j++){ Democoin_Instance.Remove_Burner(Remove_Burner[j]); } } /*Citizens_Register Handling*/ /** * @dev Change the amount of DemoCoin token to mint for new registered citizens. * @param amount Amount of token to mint. */ function Set_Citizen_Mint_Amount(uint amount) external Register_Authorities_Only{ Citizen_Instance.Set_Citizen_Mint_Amount(amount); } /** * @dev Removes address from {Citizens_Registering_Authorities} (address allowed to register new citizens) and/or from {Citizens_Banning_Authorities} (address allowed to ban citizens) * @param removed_authority Address to removes {Citizens_Register} contract authorities lists. */ function Citizen_Register_Remove_Authority(address removed_authority) external Register_Authorities_Only{ Citizen_Instance.Remove_Authority(removed_authority); } /** * @dev Allows an address to register new citizens. The address is added to {Citizens_Registering_Authorities} list * @param new_authority Address to add to {Citizens_Registering_Authorities} list */ function Add_Registering_Authority(address new_authority)external Register_Authorities_Only{ Citizen_Instance.Add_Registering_Authority(new_authority); } /** * @dev Allows an address to register ban citizens. The address is added to {Citizens_Banning_Authorities} list * @param new_authority Address to add to {Citizens_Banning_Authorities} list */ function Add_Banning_Authority(address new_authority)external Register_Authorities_Only{ Citizen_Instance.Add_Banning_Authority(new_authority); } /*Register/Agora Handling*/ /** * @dev Add/create a new Register Contract to the Web3 Direct Democracy project. It's address is added to {Registers_Address_List} * @param Name Name of the new Register contract * @param register_type Type of the Register Contract (see {Institution_Type} enum of {Institution} abstract contract). * @param Petition_Duration Duration of the proposition/petition stage * @param Vote_Duration Duration of the voting stage * @param Vote_Checking_Duration Duration of the validation stage * @param Law_Initialisation_Price Amount of DemoCoin token to pay to submit a new Referendum proposition. * @param FunctionCall_Price Amount of DemoCoin token to pay for each new function call of a function call corpus proposal submission. * @param Required_Petition_Rate The minimum ratio of citizens signatures required to submit the referendum proposition as a referendum to all citizens. * @param Ivote_address Address of the IVote contract used in the voting and validation stage */ function Create_Register(string memory Name, uint8 register_type, uint Petition_Duration, uint Vote_Duration, uint Vote_Checking_Duration, uint Law_Initialisation_Price, uint FunctionCall_Price, uint16 Required_Petition_Rate, address Ivote_address) external Register_Authorities_Only{ //returns(bool, bytes memory){ address new_register_address; if(register_type == 0){ new_register_address = address(this); }else if(register_type == 3){ new_register_address = Constitution_Register.Create_Loi(Name, address(Agora_Instance)); }else if(register_type == 4){ new_register_address = Constitution_Register.Create_API(Name, address(Agora_Instance)); }else{ revert("Not Register Type"); } require(!Registers_Address_List.contains(new_register_address), "Register Already Existing"); Registers_Address_List.add(new_register_address); Agora_Instance.Create_Register_Referendum(new_register_address, register_type); _Set_Register_Param(new_register_address, Petition_Duration, Vote_Duration, Vote_Checking_Duration, Law_Initialisation_Price, FunctionCall_Price, Required_Petition_Rate, Ivote_address); emit Register_Created(new_register_address); } /** * @dev Change parameters of a Register Contract of the project. * @param register_address Address of the Register contract * @param Petition_Duration Duration of the proposition/petition stage * @param Vote_Duration Duration of the voting stage * @param Vote_Checking_Duration Duration of the validation stage * @param Law_Initialisation_Price Amount of DemoCoin token to pay to submit a new Referendum proposition. * @param FunctionCall_Price Amount of DemoCoin token to pay for each new function call of a function call corpus proposal submission. * @param Required_Petition_Rate The minimum ratio of citizens signatures required to submit the referendum proposition as a referendum to all citizens. * @param Ivote_address Address of the IVote contract used in the voting and validation stage */ function Set_Register_Param(address register_address, uint Petition_Duration, uint Vote_Duration, uint Vote_Checking_Duration, uint Law_Initialisation_Price, uint FunctionCall_Price, uint16 Required_Petition_Rate, address Ivote_address) external Register_Authorities_Only{ //returns(bool, bytes memory){ require(Registers_Address_List.contains(register_address), "Register doesn't exist"); _Set_Register_Param(register_address, Petition_Duration, Vote_Duration, Vote_Checking_Duration, Law_Initialisation_Price, FunctionCall_Price, Required_Petition_Rate, Ivote_address); } function _Set_Register_Param(address register_address, uint Petition_Duration, uint Vote_Duration, uint Vote_Checking_Duration, uint Law_Initialisation_Price, uint FunctionCall_Price, uint16 Required_Petition_Rate, address Ivote_address) internal { if(Petition_Duration ==0 || Vote_Duration ==0 || Required_Petition_Rate == 0 || Required_Petition_Rate >10000 || Ivote_address==address(0)){ revert("Bad arguments value"); } Agora_Instance.Update_Register_Referendum_Parameters(register_address, Petition_Duration, Vote_Duration, Vote_Checking_Duration, Law_Initialisation_Price, FunctionCall_Price, Required_Petition_Rate, Ivote_address); } /*Delegations Handling*/ /** * @dev Add/Deploy a new Delegation contract to the project. It's address is added to {Delegation_Address_List} * @param Name Name of the Delegation contract * @param delegation_address Address of an already deployed Delegation contract to add to the Project. If the delegation_address argument is address(0) then the function deploy a new Delegation contract. * @param Uint256_Legislatifs_Arg Array of uitn256 parameters related to Delegation's legislatif process. We use an array in order to reduce stack size (to avoid the "stack too deep" error). Array elements represent following parameters: * - Member_Max_Token_Usage: The maximum amount of token a member is allowed to use for a law project elaboration * - Law_Initialisation_Price: The price in token for creating a law project * - FunctionCall_Price: The price in token for one FunctionCall. * - Proposition_Duration: The duration of the stage in which members are allowed to submit propositions * - Vote_Duration: The duration of the stage in which members are allowed to vote for the proposition they want * - Law_Censor_Period_Duration: The duration of the stage in which all citizens are allowed to sign a etition against the law project proposed by the Delegation * * @param Uint256_Governance_Arg Array of uitn256 parameters related to Delegation's Internal governance. We use an array in order to reduce stack size (to avoid the "stack too deep" error). Array elements represent following parameters: * - Election_Duration: Duration of the stage in which citizens are allowed to vote for Candidats they prefer * - Validation_Duration: Duration of the stage in which citizens can validate their hased vote by revealing their choice and the salt that has been used for hasing * - Mandate_Duration: Duration of a delegation mandate * - Immunity_Duration: Amount of time after the beginning of a new mandate during which delegation's members can't be revoked * - Mint_Token: Amount of token to mint for the Delegation * @param Num_Max_Members Maximum number of members in the delegation. * @param Revert_Proposition_Petition_Rate The minimum ratio of citizens required to cancel a law project * @param Revert_Penalty_Rate Ratio of total amount of token belonged by the delegation that will be lost if a law project is rejected by citizens * @param New_Election_Petition_Rate The minimum ratio of citizens required to revoke the current delegation's members and start a new election * @param Initial_members: Initials members of the delegation * @param Ivote_address_legislatif Address of the IVote contract that will be used during Legislatif process * @param Ivote_address_governance Address of the IVote contract that will be used during election stage */ function Create_Delegation(string memory Name, address delegation_address, uint[6] calldata Uint256_Legislatifs_Arg, uint[5] calldata Uint256_Governance_Arg, uint16 Num_Max_Members, uint16 Revert_Proposition_Petition_Rate, uint16 Revert_Penalty_Rate, uint16 New_Election_Petition_Rate, address[] memory Initial_members, address Ivote_address_legislatif, address Ivote_address_governance) external Register_Authorities_Only { if(Uint256_Legislatifs_Arg[3]==0 || Uint256_Legislatifs_Arg[4]==0 || Revert_Proposition_Petition_Rate>10000 || Revert_Penalty_Rate>10000 || Ivote_address_legislatif==address(0)){ revert("Legislatif: Bad Argument Value"); } if(Uint256_Governance_Arg[0]==0 || Uint256_Governance_Arg[2]==0 || Num_Max_Members==0 || New_Election_Petition_Rate ==0 || New_Election_Petition_Rate>10000 || Initial_members.length > Num_Max_Members || Ivote_address_governance==address(0)){ revert("Governance: Bad Argument Value"); } if(delegation_address == address(0)){ //Create a new delegation for(uint i =0; i<Initial_members.length; i++){ require(Citizen_Instance.Contains(Initial_members[i]), "Member is not citizen"); } delegation_address = Constitution_Delegation.Create_Delegation(Name, Initial_members, address(Democoin_Instance), address(Citizen_Instance), address(Agora_Instance)); }else{ require(!Delegation_Address_List.contains(delegation_address), "Delegation already registered"); } Delegation_Address_List.add(delegation_address); emit Delegation_Created(delegation_address); if(Uint256_Governance_Arg[4]>0){ Democoin_Instance.Mint(delegation_address, Uint256_Governance_Arg[4]); } IDelegation(delegation_address).Update_Legislatif_Process(Uint256_Legislatifs_Arg, Revert_Proposition_Petition_Rate, Revert_Penalty_Rate, Ivote_address_legislatif); IDelegation(delegation_address).Update_Internal_Governance(Uint256_Governance_Arg[0], Uint256_Governance_Arg[1], Uint256_Governance_Arg[2], Uint256_Governance_Arg[3], Num_Max_Members, New_Election_Petition_Rate, Ivote_address_governance); } /** * @dev Put a Register contract under the control of a Delegation. The Register contract address is added to {Controled_Registers} list of the Delegation. * It means that the Delegation recognize the Register contract as a controled one. But to allow the Delegation to call Register functions of the Register contract, you also have to to add the Delegation' address to the {Register_Authorities} list of the register contract via the {Add_Register_Authority} function. * @param delegation_address Address of the Delegation * @param new_controled_register Address of the Register contract. */ function Add_Delegation_Controled_Register(address delegation_address, address new_controled_register) external Register_Authorities_Only{ require(Delegation_Address_List.contains(delegation_address), "Non Existing Delegation"); require(Registers_Address_List.contains(new_controled_register), "Non Existing Register"); IDelegation(delegation_address).Add_Controled_Register( new_controled_register); } /** * @dev Removes a Register contract from the control of a Delegation. The Register contract address is removed from the {Controled_Registers} list of the Delegation. * It means that the Delegation doesn't recognize anymore the Register contract as a controled one. But to fully cut bonds between the Delegation and the Register contract, you also have to to remove the Delegation' address from the {Register_Authorities} list of the register contract via the {Remove_Register_Authority} function. * @param delegation_address Address of the Delegation * @param removed_controled_register Address of the Register contract. */ function Remove_Delegation_Controled_Register(address delegation_address, address removed_controled_register) external Register_Authorities_Only{ require(Delegation_Address_List.contains(delegation_address), "Non Existing Delegation"); require(Registers_Address_List.contains(removed_controled_register), "Non Existing Register"); IDelegation(delegation_address).Remove_Controled_Register( removed_controled_register); } /** * @dev Modify parameters related to the Legislatif process of a Delegation. * @param delegation_address Address of the Delegation contract * @param delegation_address Address of an already deployed Delegation contract to add to the Project. If the delegation_address argument is address(0) then the function deploy a new Delegation contract. * @param Uint256_Legislatifs_Arg Array of uitn256 parameters related to Delegation's legislatif process. We use an array in order to reduce stack size (to avoid the "stack too deep" error). Array elements represent following parameters: * - Member_Max_Token_Usage: The maximum amount of token a member is allowed to use for a law project elaboration * - Law_Initialisation_Price: The price in token for creating a law project * - FunctionCall_Price: The price in token for one FunctionCall. * - Proposition_Duration: The duration of the stage in which members are allowed to submit propositions * - Vote_Duration: The duration of the stage in which members are allowed to vote for the proposition they want * - Law_Censor_Period_Duration: The duration of the stage in which all citizens are allowed to sign a etition against the law project proposed by the Delegation * * @param Revert_Proposition_Petition_Rate The minimum ratio of citizens required to cancel a law project * @param Revert_Penalty_Rate Ratio of total amount of token belonged by the delegation that will be lost if a law project is rejected by citizens * @param Ivote_address Address of the IVote contract that will be used during Legislatif process */ function Set_Delegation_Legislatif_Process(address delegation_address, uint[6] calldata Uint256_Legislatifs_Arg, uint16 Revert_Proposition_Petition_Rate, uint16 Revert_Penalty_Rate, address Ivote_address) external Register_Authorities_Only{ //returns(bool, bytes memory){ require(Delegation_Address_List.contains(delegation_address), "Non Existing Delegation"); if(Uint256_Legislatifs_Arg[3]==0 || Uint256_Legislatifs_Arg[4]==0 || Revert_Proposition_Petition_Rate>10000 || Revert_Penalty_Rate>10000 || Ivote_address==address(0) ){ revert("Legislatif: Bad Argument Value"); } IDelegation(delegation_address).Update_Legislatif_Process(Uint256_Legislatifs_Arg, Revert_Proposition_Petition_Rate, Revert_Penalty_Rate, Ivote_address); } /** * @dev Modify parameters related to the Legislatif process of a Delegation. * @param delegation_address Address of the Delegation contract * @param Election_Duration: Duration of the stage in which citizens are allowed to vote for Candidats they prefer * @param Validation_Duration: Duration of the stage in which citizens can validate their hased vote by revealing their choice and the salt that has been used for hasing * @param Mandate_Duration: Duration of a delegation mandate * @param Immunity_Duration: Amount of time after the beginning of a new mandate during which delegation's members can't be revoked * @param Num_Max_Members: Maximum number of members in the delegation. * @param New_Election_Petition_Rate: The minimum ratio of citizens required to revoke the current delegation's members and start a new election * @param Mint_Token Amount of token to mint for the Delegation: Initials members of the delegation * @param Ivote_address Address of the IVote contract that will be used during election stage */ function Set_Delegation_Internal_Governance(address delegation_address, uint Election_Duration, uint Validation_Duration, uint Mandate_Duration, uint Immunity_Duration, uint16 Num_Max_Members, uint16 New_Election_Petition_Rate, uint Mint_Token, address Ivote_address) external Register_Authorities_Only{ require(Delegation_Address_List.contains(delegation_address), "Non Existing Delegation"); if(Election_Duration==0 || Mandate_Duration==0 || Num_Max_Members==0 || New_Election_Petition_Rate ==0 || New_Election_Petition_Rate>10000 || Ivote_address==address(0)){ revert("Governance: Bad Argument Value"); } if(Mint_Token>0){ Democoin_Instance.Mint(delegation_address, Mint_Token); } IDelegation(delegation_address).Update_Internal_Governance(Election_Duration, Validation_Duration, Mandate_Duration, Immunity_Duration, Num_Max_Members, New_Election_Petition_Rate, Ivote_address); } /*GETTERS*/ /** * @dev Get the list of all address of Register contracts registered in the Constitution * @return register_list Array of Register contract address */ function Get_Register_List() external view returns(bytes32[] memory register_list){ return Registers_Address_List._inner._values; } /** * @dev Get the list of all address of Delegation contracts registered in the Constitution * @return delegation_list Array of Delegation contract address */ function Get_Delegation_List() external view returns(bytes32[] memory delegation_list){ return Delegation_Address_List._inner._values; } }
Removes a, address from a Register contract's {Register_Authorities} list. register Address of the register contract authority Address to remove from the {Register_Authorities} list./
function Remove_Register_Authority(address register, address authority) external Register_Authorities_Only{ require(Registers_Address_List.contains(register), "Unknown Register"); Register res = Register(register); res.Remove_Authority(authority); }
12,741,920
//File: contracts\EthereumSign.sol pragma solidity ^0.4.18; contract EthereumSign { //archive of digital certificates, every certificate combine signer //address and arts guid mapping(bytes32 => Version[]) digitalCertificateArchive; struct Version { uint8 version; bytes32 sign; uint256 timestamp; } function Sign(string guid, string hash) public { address _signer = msg.sender; string memory addressString = toString(_signer); //combine signer with guid of arts to create an archive managed by the signer string memory concatenatedData = strConcat(addressString,guid); bytes32 hashed = keccak256(concatenatedData); uint8 version = 1; Version[] memory versions = digitalCertificateArchive[hashed]; uint length = versions.length; for(uint8 i = 0; i < length; i++) { version = i+2; } bytes32 hashedSign = keccak256(hash); Version memory v = Version(version,hashedSign,now); digitalCertificateArchive[hashed].push(v); } function GetSign(string guid, address signer) public view returns(bytes32 sign, uint8 signedVersion,uint256 timestamp){ address _signer = signer; string memory addressString = toString(_signer); //combine signer with guid of arts to create an archive managed by the signer string memory concatenatedData = strConcat(addressString,guid); bytes32 hashed = keccak256(concatenatedData); uint length = digitalCertificateArchive[hashed].length; Version memory v = digitalCertificateArchive[hashed][length-1]; return (v.sign, v.version, v.timestamp); } function GetSignVersion(string guid, address signer, uint version) public view returns(bytes32 sign, uint8 signedVersion,uint256 timestamp){ address _signer = signer; string memory addressString = toString(_signer); //combine signer with guid of arts to create an archive managed by the signer string memory concatenatedData = strConcat(addressString,guid); bytes32 hashed = keccak256(concatenatedData); Version memory v = digitalCertificateArchive[hashed][version-1]; return (v.sign, v.version, v.timestamp); } function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string){ bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } function toString(address x) returns (string) { bytes memory b = new bytes(20); for (uint i = 0; i < 20; i++) b[i] = byte(uint8(uint(x) / (2**(8*(19 - i))))); return string(b); } function bytes32ToString(bytes32 x) constant returns (string) { bytes memory bytesString = new bytes(32); uint charCount = 0; for (uint j = 0; j < 32; j++) { byte char = byte(bytes32(uint(x) * 2 ** (8 * j))); if (char != 0) { bytesString[charCount] = char; charCount++; } } bytes memory bytesStringTrimmed = new bytes(charCount); for (j = 0; j < charCount; j++) { bytesStringTrimmed[j] = bytesString[j]; } return string(bytesStringTrimmed); } }
combine signer with guid of arts to create an archive managed by the signer
function GetSignVersion(string guid, address signer, uint version) public view returns(bytes32 sign, uint8 signedVersion,uint256 timestamp){ address _signer = signer; string memory addressString = toString(_signer); string memory concatenatedData = strConcat(addressString,guid); bytes32 hashed = keccak256(concatenatedData); Version memory v = digitalCertificateArchive[hashed][version-1]; return (v.sign, v.version, v.timestamp); }
2,379,854
./full_match/1/0xeb1BD76F9f018A05D1FB1C28d8Af4e3E54b5773a/sources/contract.sol
Withdraw Balance to Address
function withdrawMoneyTo(address payable _to) public onlyOwner { _to.transfer(getBalance()); }
4,959,165
// solium-disable linebreak-style pragma solidity ^0.5.0; import "./oraclizeAPI.sol"; /** * * @dev Interface with Oraclize in 5.0 fashion * @dev Main purpose to set bool storage IsMarioPrez as to whether the current president's name starts with mario :) * * Example execution result * * [2019-02-22T01:21:16.781Z] INFO sending __callback tx... * { * "contract_myid": "0xaf9c9029a46cf93613729ddb9fa22c04ef0856e051ea96f6e127baebfd06c645", * "contract_address": "0xddcf4eb16a999b436161ad137f7031d11675aa9d" * } * [2019-02-22T01:21:22.060Z] INFO contract 0xddcf4eb16a999b436161ad137f7031d11675aa9d __callback tx sent, transaction hash: 0x022ad5a25aa815403acb6c4a43d29901dd07627f77370567043128c5468aeed2 * { * "myid": "0xaf9c9029a46cf93613729ddb9fa22c04ef0856e051ea96f6e127baebfd06c645", * "result": "Nicos Anastasiades", * "proof": null, * "proof_type": "0x00", * "contract_address": "0xddcf4eb16a999b436161ad137f7031d11675aa9d", * "gas_limit": 1000000, * "gas_price": 1000000000 * } * ------------------------------------------------------------------------------ * Note the next pending query 60 days from now that's sitting for fullfilment... * * [2019-02-23T02:00:54.902Z] INFO new HTTP query created, id: 3d4e1a72cd9d19ffb7fe6266d93623db8e817f52f1f7a3e927c094faf17b7b4f * [2019-02-23T02:00:54.904Z] INFO checking HTTP query 3d4e1a72cd9d19ffb7fe6266d93623db8e817f52f1f7a3e927c094faf17b7b4f status on Wed Apr 24 2019 05:00:53 GMT+0300 (Eastern European Summer Time) */ contract Wa is usingOraclize { //-------------------------------------------------------- //------------------- Storage Declarations // // When true it ends voting. // bool public IsMarioPrez = false; // // President is declared in storage for testing purposes // Not needed for application flow // string public President = ""; // // Check whether response matches request id // mapping(bytes32=>bool) ValidQryIds; // // Terse WolframAlpha request with my app id // string constant wolframCyprusPres = "https://api.wolframalpha.com/v1/result?i=Cyprus+president%3F&appid=7YX4VR-HYV3XJ9QTR"; // // daysDelayForNextOraclizeQuery // uint public DaysInSecondsDelayForNextOraclizeQuery = 60 * 24 * 3600; //-------------------------------------------------------------------------------- //------------------------ Events Declarations event LogNewOraclizeQuery(string description, uint secondsToDelay); event LogNewPrezResult(string prezRes); //-------------------------------------------------------------------------------- //------------------------ Modifier Declarations // // Oraclize response id in __callback matching the request id. // modifier onlyValidResponseOraIds(bytes32 respId) { require (ValidQryIds[respId], "ORA1: Not valid response Id to query."); _; } // // __callback check for matching response address to request // modifier onlyValidOraAddress() { require(msg.sender == oraclize_cbAddress(), "ORA2: cbAddress not matching msg.sender."); _; } //------------------------------------------------------------------------------ //--------------------------- Public Functions /** * @dev Setup oraclize and ask the current president. * @param oraclizeResAddr OAR address related to Ethereum bridge. * @param daysDelayForNextOraclizeQuery delay in Days before next query. */ function setupOraclize( address oraclizeResAddr, uint daysDelayForNextOraclizeQuery) internal { // // Replace the following with the value from the ethereum-bridge launch // ethereum-bridge.cmd -a 9 -H 127.0.0.1:7545 --dev // OAR = OraclizeAddrResolverI(oraclizeResAddr); // // Days before next query. // DaysInSecondsDelayForNextOraclizeQuery = daysDelayForNextOraclizeQuery * 24 * 3600; // // Instead of the default 20 GWei opt in for a friendlier gas price: 2 Gwei // oraclize_setCustomGasPrice(2000000000); // // Update on contract creation... // queryWolframAlpha(0); } /** * Call query again if first name != mario * @param queryAgain T/F whether to query for a response in 59 days. */ function CallUpdateAgainIfNecessary(bool queryAgain) internal { if (queryAgain) { queryWolframAlpha(DaysInSecondsDelayForNextOraclizeQuery); } } /** * Called by oraclize itself to answer the pending query. * Hard to troubleshoot if it appears that it never enters here your * after you see the query response in ethereum bridge. * Two reasons I found for this: * 1. Wrong function signature if using proof authentication * * 2. These queries are gas guzzles especially with the contained recursive query call * and if it spends all available contract balance * -- or -- * reaches a custom API gas limit during the execution of this, it rolls back and appears * like it never entered this... * */ function __callback(bytes32 respId, string memory result) public onlyValidResponseOraIds(respId) onlyValidOraAddress { bool isMarioPrez = getIsMarioPrez(result); // Not needed other than for testing President = result; IsMarioPrez = isMarioPrez; emit LogNewPrezResult(result); delete ValidQryIds[respId]; // // Not elegant but enter in a 2-month loop of constant queries // Till there's a positive response // Check next update max time from now: two months. // CallUpdateAgainIfNecessary(!IsMarioPrez); } /** * @dev Query wolfram alpha with an estimated gas for lower costs. * @dev Side effect: __callback is called. * @dev authenticity proof is not used because it comes back empty. * @dev other authenticity mechanisms are used i.e. queryId, cbAddress (see __callback) */ function queryWolframAlpha(uint secondsToDelay) public payable { emit LogNewOraclizeQuery("New Cypriot Prez Request:", secondsToDelay); // // Had touble to squeze the gas limit here to 50k instead of using the default 200k // as it is suggested by afficionados. // Note each query is prepaid and the difference due to the callback nature // is refunded to Oraclize. // Before launching to a live network, a plethora of testing would // determine the optimal price for each query and subsequent recursive one. // bytes32 queryId = oraclize_query(secondsToDelay, "URL", wolframCyprusPres); ValidQryIds[queryId] = true; } /** * @dev Detects whether "maRio" in any small/caps combination is the first substring within the input parameter. * @dev Tolerates initial spaces e.g. " Mario" or " mario" or "mArio" * @param fullName The returned oraclize name string to search for the given first name. * Note as of this writing it looks like this: "Nicos Anastasiades" * @return True/False Whether mario is contained as a substring at index 0 or few spaces later. */ function getIsMarioPrez(string memory fullName) public pure returns (bool) { bytes memory fullNameBytes = bytes(fullName); bytes memory soughtAfterCaps = bytes("MARIO"); bytes memory soughtAfterSmall = bytes("mario"); uint8 fni = 0; uint8 spaces = 0; bytes1 space = bytes1(" "); for(uint8 i = 0; i < fullNameBytes.length && i < 256; ) { if (fullNameBytes[i] == space && i == spaces) { // Eat up preceeding white spaces. i++; spaces++; } else if (fni < 4 && (fullNameBytes[i] == soughtAfterCaps[fni] || fullNameBytes[i] == soughtAfterSmall[fni])) { // Matching any of [Mari] i++; fni++; } else if (fni == 4 && (fullNameBytes[i] == soughtAfterCaps[fni] || fullNameBytes[i] == soughtAfterSmall[fni])) { // final o in mario return true; } else if (fni > 0 && (fullNameBytes[i] != soughtAfterCaps[fni] && fullNameBytes[i] != soughtAfterSmall[fni])) { // Detected unrelated character within mario e.g. Mar io return false; } else { // Any non-space irrelevant byte... return false; } } return false; } }
Detects whether "maRio" in any small/caps combination is the first substring within the input parameter. Tolerates initial spaces e.g. " Mario" or " mario" or "mArio" fullName The returned oraclize name string to search for the given first name. Note as of this writing it looks like this: "Nicos Anastasiades" return True/False Whether mario is contained as a substring at index 0 or few spaces later./ Eat up preceeding white spaces. Matching any of [Mari] final o in mario Detected unrelated character within mario e.g. Mar io Any non-space irrelevant byte...
function getIsMarioPrez(string memory fullName) public pure returns (bool) { bytes memory fullNameBytes = bytes(fullName); bytes memory soughtAfterCaps = bytes("MARIO"); bytes memory soughtAfterSmall = bytes("mario"); uint8 fni = 0; uint8 spaces = 0; bytes1 space = bytes1(" "); for(uint8 i = 0; i < fullNameBytes.length && i < 256; ) { if (fullNameBytes[i] == space && i == spaces) { i++; spaces++; i++; fni++; return true; return false; return false; } } return false; }
883,406
./full_match/1/0x0303C9298CEaf4D467ba80A37aE2b5Abc94D2566/sources/contracts/ThePaintedSatoshis.sol
Transfers `tokenId` from `from` to `to`. As opposed to {transferFrom}, this imposes no restrictions on msg.sender. Requirements: - `to` cannot be the zero address. - `tokenId` token must be owned by `from`. Emits a {Transfer} event./ Clear approvals from the previous owner
function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721S.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); _approve(address(0), tokenId); _owners[tokenId] = to; emit Transfer(from, to, tokenId); }
3,058,764
./partial_match/3/0xE2B9ab1C0E4426F753e20E85eBF5A14E79600DF2/sources/RetjehSwapPair.sol
update reserves and, on the first call per block, price accumulators never overflows, and + overflow is desired
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private { require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'RetjehSwap: OVERFLOW'); uint32 blockTimestamp = uint32(block.timestamp % 2**32); if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); }
5,297,572
// SPDX-License-Identifier: MIT pragma solidity =0.8.6; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @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); } } } } /** * @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"); } } } /** * @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 Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } function owner() public view virtual returns (address) { return _owner; } modifier onlyOwner() { require(owner() == msg.sender, "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract ERC20WithVoting is ERC20 { constructor(string memory name_, string memory symbol_) ERC20(name_, symbol_) { } /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "PEVRT::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "PEVRT::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "PEVRT::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "PEVRT::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying PEVRT (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = (srcRepOld - amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = (dstRepOld + amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "PEVRT::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal view returns (uint256) { return block.chainid; } function _mint(address account, uint256 amount) internal override { super._mint(account, amount); _moveDelegates(address(0), _delegates[account], amount); } function _burn(address account, uint256 amount) internal override { super._burn(account, amount); _moveDelegates(address(0), _delegates[account], amount); } function _transfer(address sender, address recipient, uint256 amount) internal virtual override { super._transfer(sender, recipient, amount); _moveDelegates(_delegates[sender], _delegates[recipient], amount); } } // This contract handles powering and uncharging of your pEVRT, Everest DAO's staking token. contract EVRTCharger is ERC20WithVoting("Charged EVRT", "pEVRT"), Ownable { using SafeERC20 for IERC20; IERC20 public immutable evrt; uint256 public constant MAX_PAPER_HANDS_PENALTY = 2500; uint256 public constant MAX_BIPS = 10000; uint256 public constant SECONDS_PER_DAY = 86400; // This is a variable that can be changed by the admin uint256 public paperHandsPenalty; // Tracks total EVRT that has been collected via the PHP. uint256 public fundsCollectedByPHP; // tracks total deposits over all time uint256 public totalDeposits; // tracks total withdrawals over all time uint256 public totalWithdrawals; //stored historic exchange rates and their timestamps, separated by ~24 hour intervals uint256 public numStoredExchangeRates; uint256[] public historicExchangeRates; uint256[] public historicTimestamps; //for tracking rewards sent to nest in trailing 24 hour period uint256 public rollingStartTimestamp; uint256 public rollingStartEvrtBalance; uint256 public rollingStartTotalDeposits; uint256 public rollingStartTotalWithdrawals; //stores deposits to help tracking of profits mapping(address => uint256) public deposits; //stores withdrawals to help tracking of profits mapping(address => uint256) public withdrawals; event Enter(address indexed penguin, uint256 amount); event Leave(address indexed penguin, uint256 amount, uint256 shares); event PaperHandsPenaltySet(uint256 newPaperHandsPenalty); event DailyRewardsReceived(uint256 indexed timestamp, uint256 amountEvrt); // Make sure that the PenguinToken contract we are passing in here // has the function `burnOwnTokens` which will burn tokens of your own // address. constructor(IERC20 _evrt, uint256 _paperHandsPenalty) { evrt = _evrt; setPaperHandsPenalty(_paperHandsPenalty); numStoredExchangeRates = 1; historicExchangeRates.push(1e18); historicTimestamps.push(block.timestamp); rollingStartTimestamp = block.timestamp; } //returns current exchange rate of pEVRT to EVRT, scaled up by 1e18 function currentExchangeRate() public view returns(uint256) { uint256 totalShares = totalSupply(); if(totalShares == 0) { return 1e18; } return (evrtBalance() * 1e18) / totalShares; } //returns user profits in EVRT (returns zero in the case that user has losses due to previous PHP) function userProfits(address stakingAddress) public view returns(uint256) { uint256 userDeposits = deposits[stakingAddress]; uint256 userWithdrawals = withdrawals[stakingAddress]; uint256 totalShares = totalSupply(); uint256 shareValue = (balanceOf(stakingAddress) * evrtBalance()) / totalShares; uint256 totalAssets = userWithdrawals + shareValue; if(totalAssets >= userDeposits) { return (totalAssets - userDeposits); } else { return 0; } } //returns most recent stored exchange rate and the time at which it was stored function getLatestStoredExchangeRate() public view returns(uint256, uint256) { return (historicExchangeRates[numStoredExchangeRates - 1], historicTimestamps[numStoredExchangeRates - 1]); } //returns last amount of stored exchange rate datas function getExchangeRateHistory(uint256 amount) public view returns(uint256[] memory, uint256[] memory) { uint256 endIndex = numStoredExchangeRates - 1; uint256 startIndex = (amount > endIndex) ? 0 : (endIndex - amount + 1); uint256 length = endIndex - startIndex + 1; uint256[] memory exchangeRates = new uint256[](length); uint256[] memory timestamps = new uint256[](length); for(uint256 i = startIndex; i <= endIndex; i++) { exchangeRates[i - startIndex] = historicExchangeRates[i]; timestamps[i - startIndex] = historicTimestamps[i]; } return (exchangeRates, timestamps); } function evrtBalance() public view returns(uint256) { return evrt.balanceOf(address(this)); } //tracks the amount of EVRT the nest has received over the last 24 hours function rewardsReceived() public view returns(uint256) { // Gets the current EVRT balance of the nest uint256 totalEvrt = evrtBalance(); // gets deposits during the period uint256 depositsDuringPeriod = totalDeposits - rollingStartTotalDeposits; // gets withdrawals during the period uint256 withdrawalsDuringPeriod = totalWithdrawals - rollingStartTotalWithdrawals; // net rewards received is (new evrt balance - old evrt balance) + (withdrawals - deposits) return ((totalEvrt + withdrawalsDuringPeriod) - (depositsDuringPeriod + rollingStartEvrtBalance)); } function timeSinceLastDailyUpdate() public view returns(uint256) { return (block.timestamp - rollingStartTimestamp); } // Enter the nest. Pay some EVRT. Earn some shares. // Locks EVRT and mints pEVRT function enter(uint256 _amount) external { // Gets the amount of EVRT locked in the contract uint256 totalEvrt = evrtBalance(); // Gets the amount of pEVRT in existence uint256 totalShares = totalSupply(); // If no pEVRT exists, mint it 1:1 to the amount put in if (totalShares == 0 || totalEvrt == 0) { _mint(msg.sender, _amount); } // Calculate and mint the amount of pEVRT the EVRT is worth. // The ratio will change overtime, as pEVRT is burned/minted and EVRT // deposited + gained from fees / withdrawn. else { uint256 what = (_amount * totalShares) / totalEvrt; _mint(msg.sender, what); } //track deposited EVRT deposits[msg.sender] = deposits[msg.sender] + _amount; totalDeposits += _amount; // Lock the EVRT in the contract evrt.safeTransferFrom(msg.sender, address(this), _amount); _dailyUpdate(); emit Enter(msg.sender, _amount); } // Leave the vault. Claim back your EVRT. // Unlocks the staked + gained EVRT and redistributes pEVRT. function leave(uint256 _share) external { // Gets the amount of pEVRT in existence uint256 totalShares = totalSupply(); // Gets the EVRT balance of the nest uint256 totalEvrt = evrtBalance(); // Calculates the amount of EVRT the pEVRT is worth uint256 what = (_share * totalEvrt) / totalShares; //burn pEVRT _burn(msg.sender, _share); //send withdrawn EVRT uint256 tax = (what * paperHandsPenalty) / MAX_BIPS; uint256 toSend = what - tax; // Send the person's EVRT to their address evrt.safeTransfer(msg.sender, toSend); //track withdrawn EVRT withdrawals[msg.sender] += toSend; totalWithdrawals += toSend; fundsCollectedByPHP += tax; _dailyUpdate(); emit Leave(msg.sender, what, _share); } // Change the early withdrawal amount function setPaperHandsPenalty(uint256 _paperHandsPenalty) public onlyOwner { require(_paperHandsPenalty <= MAX_PAPER_HANDS_PENALTY, "Can't have paper hands penalty greater than maximum"); paperHandsPenalty = _paperHandsPenalty; emit PaperHandsPenaltySet(_paperHandsPenalty); } //tracking for profits on transfers function _transfer( address sender, address recipient, uint256 amount ) internal override { // Gets the amount of pEVRT in existence uint256 totalShares = totalSupply(); // Gets the EVRT balance of the nest uint256 totalEvrt = evrtBalance(); uint256 evrtValueOfShares = (amount * totalEvrt) / totalShares; // take part of profit tracking deposits[recipient] += evrtValueOfShares; withdrawals[sender] += evrtValueOfShares; //perform the internal transfer super._transfer(sender, recipient, amount); } function _dailyUpdate() internal { if (timeSinceLastDailyUpdate() >= SECONDS_PER_DAY) { emit DailyRewardsReceived(block.timestamp, rewardsReceived()); //update rolling data rollingStartTimestamp = block.timestamp; rollingStartEvrtBalance = evrtBalance(); rollingStartTotalDeposits = totalDeposits; rollingStartTotalWithdrawals = totalWithdrawals; //store exchange rate and timestamp historicExchangeRates.push(currentExchangeRate()); historicTimestamps.push(block.timestamp); numStoredExchangeRates += 1; } } }
update rolling datastore exchange rate and timestamp
function _dailyUpdate() internal { if (timeSinceLastDailyUpdate() >= SECONDS_PER_DAY) { emit DailyRewardsReceived(block.timestamp, rewardsReceived()); rollingStartTimestamp = block.timestamp; rollingStartEvrtBalance = evrtBalance(); rollingStartTotalDeposits = totalDeposits; rollingStartTotalWithdrawals = totalWithdrawals; historicExchangeRates.push(currentExchangeRate()); historicTimestamps.push(block.timestamp); numStoredExchangeRates += 1; } }
5,536,942
./partial_match/1/0x0fFce62A09a14344e2FA1306Ca34674f205dE259/sources/Shibrabbit.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Shiba Rabbit", "SHIBRABBIT") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 4; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 4; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 1 * 1e12 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
15,998,746
// File: contracts/zeppelin/SafeMath.sol pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } // File: contracts/ZTUSDImplementation.sol pragma solidity ^0.4.24; pragma experimental "v0.5.0"; /** * @title ZTUSDImplementation * @dev this contract is a Pausable ERC20 token with Burn and Mint * controleld by a central SupplyController. By implementing Zap Theory Implementation * this contract also includes external methods for setting * a new implementation contract for the Proxy. * NOTE: The storage defined here will actually be held in the Proxy * contract and all calls to this contract should be made through * the proxy, including admin actions done as owner or supplyController. * Any call to transfer against this contract should fail * with insufficient funds since no tokens will be issued there. */ contract ZTUSDImplementation { /** * MATH */ using SafeMath for uint256; /** * DATA */ // INITIALIZATION DATA bool private initialized = false; // ERC20 BASIC DATA mapping(address => uint256) internal balances; uint256 internal totalSupply_; string public constant name = "ZTUSD"; // solium-disable-line uppercase string public constant symbol = "ZTUSD"; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase // ERC20 DATA mapping (address => mapping (address => uint256)) internal allowed; // OWNER DATA address public owner; // PAUSABILITY DATA bool public paused = false; // EMERGENCY CONTROLLER DATA address public emergencyControllerRole; mapping(address => bool) internal frozen; // SUPPLY CONTROL DATA address public supplyController; /** * EVENTS */ // ERC20 BASIC EVENTS event Transfer(address indexed from, address indexed to, uint256 value); // ERC20 EVENTS event Approval( address indexed owner, address indexed spender, uint256 value ); // OWNABLE EVENTS event OwnershipTransferred( address indexed oldOwner, address indexed newOwner ); // PAUSABLE EVENTS event Pause(); event Unpause(); // EMERGENCY CONTROLLER EVENTS event AddressFrozen(address indexed addr); event AddressUnfrozen(address indexed addr); event FrozenAddressWiped(address indexed addr); event EmergencyControllerRoleSet ( address indexed oldEmergencyControllerRole, address indexed newEmergencyControllerRole ); // SUPPLY CONTROL EVENTS event SupplyIncreased(address indexed to, uint256 value); event SupplyDecreased(address indexed from, uint256 value); event SupplyControllerSet( address indexed oldSupplyController, address indexed newSupplyController ); /** * FUNCTIONALITY */ // INITIALIZATION FUNCTIONALITY /** * @dev sets 0 initials tokens, the owner, and the supplyController. * this serves as the constructor for the proxy but compiles to the * memory model of the Implementation contract. */ function initialize() public { require(!initialized, "already initialized"); owner = msg.sender; emergencyControllerRole = address(0); totalSupply_ = 0; supplyController = msg.sender; initialized = true; } /** * The constructor is used here to ensure that the implementation * contract is initialized. An uncontrolled implementation * contract might lead to misleading state * for users who accidentally interact with it. */ constructor() public { initialize(); pause(); } // ERC20 BASIC FUNCTIONALITY /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { require(_to != address(0), "cannot transfer to address zero"); require(!frozen[_to] && !frozen[msg.sender], "address frozen"); require(_value <= balances[msg.sender], "insufficient funds"); 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 _addr The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _addr) public view returns (uint256) { return balances[_addr]; } // ERC20 FUNCTIONALITY /** * @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 whenNotPaused returns (bool) { require(_to != address(0), "cannot transfer to address zero"); require(!frozen[_to] && !frozen[_from] && !frozen[msg.sender], "address frozen"); require(_value <= balances[_from], "insufficient funds"); require(_value <= allowed[_from][msg.sender], "insufficient allowance"); 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'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 whenNotPaused returns (bool) { require(!frozen[_spender] && !frozen[msg.sender], "address frozen"); 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 view returns (uint256) { return allowed[_owner][_spender]; } // OWNER FUNCTIONALITY /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "onlyOwner"); _; } /** * @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), "cannot transfer ownership to address zero"); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } // PAUSABILITY FUNCTIONALITY /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused, "whenNotPaused"); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner { require(!paused, "already paused"); paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner { require(paused, "already unpaused"); paused = false; emit Unpause(); } // EMERGENCY CONTROLLER FUNCTIONALITY /** * @dev Sets a new emergency controller role address. * @param _newEmergencyControllerRole The new address allowed to freeze/unfreeze addresses and seize their tokens. */ function setEmergencyControllerRole(address _newEmergencyControllerRole) public { require(msg.sender == emergencyControllerRole || msg.sender == owner, "only emergencyControllerRole or Owner"); emit EmergencyControllerRoleSet(emergencyControllerRole, _newEmergencyControllerRole); emergencyControllerRole = _newEmergencyControllerRole; } modifier onlyEmergencyControllerRole() { require(msg.sender == emergencyControllerRole, "onlyEmergencyControllerRole"); _; } /** * @dev Freezes an address balance from being transferred. * @param _addr The new address to freeze. */ function freeze(address _addr) public onlyEmergencyControllerRole { require(!frozen[_addr], "address already frozen"); frozen[_addr] = true; emit AddressFrozen(_addr); } /** * @dev Unfreezes an address balance allowing transfer. * @param _addr The new address to unfreeze. */ function unfreeze(address _addr) public onlyEmergencyControllerRole { require(frozen[_addr], "address already unfrozen"); frozen[_addr] = false; emit AddressUnfrozen(_addr); } /** * @dev Wipes the balance of a frozen address, burning the tokens * and setting the approval to zero. * @param _addr The new frozen address to wipe. */ function wipeFrozenAddress(address _addr) public onlyEmergencyControllerRole { require(frozen[_addr], "address is not frozen"); uint256 _balance = balances[_addr]; balances[_addr] = 0; totalSupply_ = totalSupply_.sub(_balance); emit FrozenAddressWiped(_addr); emit SupplyDecreased(_addr, _balance); emit Transfer(_addr, address(0), _balance); } /** * @dev Gets the balance of the specified address. * @param _addr The address to check if frozen. * @return A bool representing whether the given address is frozen. */ function isFrozen(address _addr) public view returns (bool) { return frozen[_addr]; } // SUPPLY CONTROL FUNCTIONALITY /** * @dev Sets a new supply controller address. * @param _newSupplyController The address allowed to burn/mint tokens to control supply. */ function setSupplyController(address _newSupplyController) public { require(msg.sender == supplyController || msg.sender == owner, "only SupplyController or Owner"); require(_newSupplyController != address(0), "cannot set supply controller to address zero"); emit SupplyControllerSet(supplyController, _newSupplyController); supplyController = _newSupplyController; } modifier onlySupplyController() { require(msg.sender == supplyController, "onlySupplyController"); _; } /** * @dev Increases the total supply by minting the specified number of tokens to the supply controller account. * @param _value The number of tokens to add. * @return A boolean that indicates if the operation was successful. */ function increaseSupply(uint256 _value) public onlySupplyController returns (bool success) { totalSupply_ = totalSupply_.add(_value); balances[supplyController] = balances[supplyController].add(_value); emit SupplyIncreased(supplyController, _value); emit Transfer(address(0), supplyController, _value); return true; } /** * @dev Decreases the total supply by burning the specified number of tokens from the supply controller account. * @param _value The number of tokens to remove. * @return A boolean that indicates if the operation was successful. */ function decreaseSupply(uint256 _value) public onlySupplyController returns (bool success) { require(_value <= balances[supplyController], "not enough supply"); balances[supplyController] = balances[supplyController].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit SupplyDecreased(supplyController, _value); emit Transfer(supplyController, address(0), _value); return true; } }
Decreases the total supply by burning the specified number of tokens from the supply controller account. _value The number of tokens to remove. return A boolean that indicates if the operation was successful./
function decreaseSupply(uint256 _value) public onlySupplyController returns (bool success) { require(_value <= balances[supplyController], "not enough supply"); balances[supplyController] = balances[supplyController].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit SupplyDecreased(supplyController, _value); emit Transfer(supplyController, address(0), _value); return true; }
173,105
pragma solidity ^0.4.24; interface PlayerBookReceiverInterface { function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external; function receivePlayerNameList(uint256 _pID, bytes32 _name) external; } contract PlayerBook { using NameFilter for string; using SafeMath for uint256; address private admin = msg.sender; //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . //=============================|================================================ uint256 public registrationFee_ = 10 finney; // price to register a name mapping(uint256 => PlayerBookReceiverInterface) public games_; // mapping of our game interfaces for sending your account info to games mapping(address => bytes32) public gameNames_; // lookup a games name mapping(address => uint256) public gameIDs_; // lokup a games ID uint256 public gID_; // total number of games uint256 public pID_; // total number of players mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amoungst any name you own) mapping (uint256 => mapping (uint256 => bytes32)) public plyrNameList_; // (pID => nameNum => name) list of names a player owns struct Player { address addr; bytes32 name; uint256 laff; uint256 names; } //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public {} //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } modifier onlyAdmin() { require(msg.sender == admin); _; } modifier isRegisteredGame() { require(gameIDs_[msg.sender] != 0); _; } //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= function checkIfNameValid(string _nameStr) public view returns(bool) { bytes32 _name = _nameStr.nameFilter(); if (pIDxName_[_name] == 0) return (true); else return (false); } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev registers a name. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who refered you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { // update last affiliate plyr_[_pID].laff = _affCode; } else if (_affCode == _pID) { _affCode = 0; } // register name registerNameCore(_pID, _addr, _affCode, _name, _isNewPlayer, _all); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // filter name + condition checks bytes32 _name = NameFilter.nameFilter(_nameString); // set up address address _addr = msg.sender; // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); } /** * @dev players, if you registered a profile, before a game was released, or * set the all bool to false when you registered, use this function to push * your profile to a single game. also, if you&#39;ve updated your name, you * can use this to push your name to games of your choosing. * -functionhash- 0x81c5b206 * @param _gameID game id */ function addMeToGame(uint256 _gameID) isHuman() public { require(_gameID <= gID_, "silly player, that game doesn&#39;t exist yet"); address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _totalNames = plyr_[_pID].names; // add players profile and most recent name games_[_gameID].receivePlayerInfo(_pID, _addr, plyr_[_pID].name, plyr_[_pID].laff); // add list of all names if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[_gameID].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } /** * @dev players, use this to push your player profile to all registered games. * -functionhash- 0x0c6940ea */ function addMeToAllGames() isHuman() public { address _addr = msg.sender; uint256 _pID = pIDxAddr_[_addr]; require(_pID != 0, "hey there buddy, you dont even have an account"); uint256 _laff = plyr_[_pID].laff; uint256 _totalNames = plyr_[_pID].names; bytes32 _name = plyr_[_pID].name; for (uint256 i = 1; i <= gID_; i++) { games_[i].receivePlayerInfo(_pID, _addr, _name, _laff); if (_totalNames > 1) for (uint256 ii = 1; ii <= _totalNames; ii++) games_[i].receivePlayerNameList(_pID, plyrNameList_[_pID][ii]); } } /** * @dev players use this to change back to one of your old names. tip, you&#39;ll * still need to push that info to existing games. * -functionhash- 0xb9291296 * @param _nameString the name you want to use */ function useMyOldName(string _nameString) isHuman() public { // filter name, and get pID bytes32 _name = _nameString.nameFilter(); uint256 _pID = pIDxAddr_[msg.sender]; // make sure they own the name require(plyrNames_[_pID][_name] == true, "umm... thats not a name you own"); // update their current name plyr_[_pID].name = _name; } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . //=====================_|======================================================= function registerNameCore(uint256 _pID, address _addr, uint256 _affID, bytes32 _name, bool _isNewPlayer, bool _all) private { // if names already has been used, require that current msg sender owns the name if (pIDxName_[_name] != 0) require(plyrNames_[_pID][_name] == true, "sorry that names already taken"); // add name to player profile, registry, and name book plyr_[_pID].name = _name; pIDxName_[_name] = _pID; if (plyrNames_[_pID][_name] == false) { plyrNames_[_pID][_name] = true; plyr_[_pID].names++; plyrNameList_[_pID][plyr_[_pID].names] = _name; } // registration fee goes directly to community rewards admin.transfer(address(this).balance); // push player info to games if (_all == true) for (uint256 i = 1; i <= gID_; i++) games_[i].receivePlayerInfo(_pID, _addr, _name, _affID); // fire event emit onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, msg.value, now); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== function determinePID(address _addr) private returns (bool) { if (pIDxAddr_[_addr] == 0) { pID_++; pIDxAddr_[_addr] = pID_; plyr_[pID_].addr = _addr; // set the new player bool to true return (true); } else { return (false); } } //============================================================================== // _ _|_ _ _ _ _ | _ _ || _ . // (/_>< | (/_| | |(_|| (_(_|||_\ . //============================================================================== function getPlayerID(address _addr) isRegisteredGame() external returns (uint256) { determinePID(_addr); return (pIDxAddr_[_addr]); } function getPlayerName(uint256 _pID) external view returns (bytes32) { return (plyr_[_pID].name); } function getPlayerLAff(uint256 _pID) external view returns (uint256) { return (plyr_[_pID].laff); } function getPlayerAddr(uint256 _pID) external view returns (address) { return (plyr_[_pID].addr); } function getNameFee() external view returns (uint256) { return(registrationFee_); } function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given, no new affiliate code was given, or the // player tried to use their own pID as an affiliate code, lolz uint256 _affID = _affCode; if (_affID != 0 && _affID != plyr_[_pID].laff && _affID != _pID) { // update last affiliate plyr_[_pID].laff = _affID; } else if (_affID == _pID) { _affID = 0; } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != address(0) && _affCode != _addr) { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) isRegisteredGame() external payable returns(bool, uint256) { // make sure name fees paid require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); // set up our tx event data and determine if player is new or not bool _isNewPlayer = determinePID(_addr); // fetch player id uint256 _pID = pIDxAddr_[_addr]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz uint256 _affID; if (_affCode != "" && _affCode != _name) { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // register name registerNameCore(_pID, _addr, _affID, _name, _isNewPlayer, _all); return(_isNewPlayer, _affID); } //============================================================================== // _ _ _|_ _ . // _\(/_ | |_||_) . //=============|================================================================ function addGame(address _gameAddress, string _gameNameStr) onlyAdmin() public { require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered"); gID_++; bytes32 _name = _gameNameStr.nameFilter(); gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = PlayerBookReceiverInterface(_gameAddress); } function setRegistrationFee(uint256 _fee) onlyAdmin() public { registrationFee_ = _fee; } } /** * @title -Name Filter- v0.1.9 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ &#169; Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ * _ __ _ ____ ____ _ _ _____ ____ ___ *=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============* *=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============* * * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ */ library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
============================================================================== _ _ _|_ _ . _\(/_ | |_||_) .=============|================================================================
function addGame(address _gameAddress, string _gameNameStr) onlyAdmin() public { require(gameIDs_[_gameAddress] == 0, "derp, that games already been registered"); gID_++; bytes32 _name = _gameNameStr.nameFilter(); gameIDs_[_gameAddress] = gID_; gameNames_[_gameAddress] = _name; games_[gID_] = PlayerBookReceiverInterface(_gameAddress); }
2,041,585
./partial_match/1/0xEC221AE5c62029cB03D91EFf85611A378A1F8883/sources/Strategy.sol
Transfers an ERC20 stuck in the contract to designated address _token - token address (can not be staking token) _to - address to send token to _amount - amount to transfer
function rescueToken( address _token, address _to, uint256 _amount ) external onlyOwner { _rescueToken(_token, _to, _amount); }
2,775,046
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; pragma abicoder v2; import '@uniswap/v3-core/contracts/libraries/SafeCast.sol'; import '@uniswap/v3-core/contracts/libraries/TickMath.sol'; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol'; import '../interfaces/IQuoter.sol'; import '../base/PeripheryImmutableState.sol'; import '../libraries/Path.sol'; import '../libraries/PoolAddress.sol'; import '../libraries/CallbackValidation.sol'; /// @title Provides quotes for swaps /// @notice Allows getting the expected amount out or amount in for a given swap without executing the swap /// @dev These functions are not gas efficient and should _not_ be called on chain. Instead, optimistically execute /// the swap and check the amounts in the callback. contract Quoter is IQuoter, IUniswapV3SwapCallback, PeripheryImmutableState { using Path for bytes; using SafeCast for uint256; /// @dev Transient storage variable used to check a safety condition in exact output swaps. uint256 private amountOutCached; constructor(address _factory, address _WETH9) PeripheryImmutableState(_factory, _WETH9) {} function getPool( address tokenA, address tokenB, uint24 fee ) private view returns (IUniswapV3Pool) { return IUniswapV3Pool(PoolAddress.computeAddress(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee))); } /// @inheritdoc IUniswapV3SwapCallback function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes memory path ) external view override { require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool(); CallbackValidation.verifyCallback(factory, tokenIn, tokenOut, fee); (bool isExactInput, uint256 amountToPay, uint256 amountReceived) = amount0Delta > 0 ? (tokenIn < tokenOut, uint256(amount0Delta), uint256(-amount1Delta)) : (tokenOut < tokenIn, uint256(amount1Delta), uint256(-amount0Delta)); if (isExactInput) { assembly { let ptr := mload(0x40) mstore(ptr, amountReceived) revert(ptr, 32) } } else { // if the cache has been populated, ensure that the full output amount has been received if (amountOutCached != 0) require(amountReceived == amountOutCached); assembly { let ptr := mload(0x40) mstore(ptr, amountToPay) revert(ptr, 32) } } } /// @dev Parses a revert reason that should contain the numeric quote function parseRevertReason(bytes memory reason) private pure returns (uint256) { if (reason.length != 32) { if (reason.length < 68) revert('Unexpected error'); assembly { reason := add(reason, 0x04) } revert(abi.decode(reason, (string))); } return abi.decode(reason, (uint256)); } /// @inheritdoc IQuoter function quoteExactInputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint160 sqrtPriceLimitX96 ) public override returns (uint256 amountOut) { bool zeroForOne = tokenIn < tokenOut; try getPool(tokenIn, tokenOut, fee).swap( address(this), // address(0) might cause issues with some tokens zeroForOne, amountIn.toInt256(), sqrtPriceLimitX96 == 0 ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1) : sqrtPriceLimitX96, abi.encodePacked(tokenIn, fee, tokenOut) ) {} catch (bytes memory reason) { return parseRevertReason(reason); } } /// @inheritdoc IQuoter function quoteExactInput(bytes memory path, uint256 amountIn) external override returns (uint256 amountOut) { while (true) { bool hasMultiplePools = path.hasMultiplePools(); (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool(); // the outputs of prior swaps become the inputs to subsequent ones amountIn = quoteExactInputSingle(tokenIn, tokenOut, fee, amountIn, 0); // decide whether to continue or terminate if (hasMultiplePools) { path = path.skipToken(); } else { return amountIn; } } } /// @inheritdoc IQuoter function quoteExactOutputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountOut, uint160 sqrtPriceLimitX96 ) public override returns (uint256 amountIn) { bool zeroForOne = tokenIn < tokenOut; // if no price limit has been specified, cache the output amount for comparison in the swap callback if (sqrtPriceLimitX96 == 0) amountOutCached = amountOut; try getPool(tokenIn, tokenOut, fee).swap( address(this), // address(0) might cause issues with some tokens zeroForOne, -amountOut.toInt256(), sqrtPriceLimitX96 == 0 ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1) : sqrtPriceLimitX96, abi.encodePacked(tokenOut, fee, tokenIn) ) {} catch (bytes memory reason) { if (sqrtPriceLimitX96 == 0) delete amountOutCached; // clear cache return parseRevertReason(reason); } } /// @inheritdoc IQuoter function quoteExactOutput(bytes memory path, uint256 amountOut) external override returns (uint256 amountIn) { while (true) { bool hasMultiplePools = path.hasMultiplePools(); (address tokenOut, address tokenIn, uint24 fee) = path.decodeFirstPool(); // the inputs of prior swaps become the outputs of subsequent ones amountOut = quoteExactOutputSingle(tokenIn, tokenOut, fee, amountOut, 0); // decide whether to continue or terminate if (hasMultiplePools) { path = path.skipToken(); } else { return amountOut; } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Safe casting methods /// @notice Contains methods for safely casting between types library SafeCast { /// @notice Cast a uint256 to a uint160, revert on overflow /// @param y The uint256 to be downcasted /// @return z The downcasted integer, now type uint160 function toUint160(uint256 y) internal pure returns (uint160 z) { require((z = uint160(y)) == y); } /// @notice Cast a int256 to a int128, revert on overflow or underflow /// @param y The int256 to be downcasted /// @return z The downcasted integer, now type int128 function toInt128(int256 y) internal pure returns (int128 z) { require((z = int128(y)) == y); } /// @notice Cast a uint256 to a int256, revert on overflow /// @param y The uint256 to be casted /// @return z The casted integer, now type int256 function toInt256(uint256 y) internal pure returns (int256 z) { require(y < 2**255); z = int256(y); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './pool/IUniswapV3PoolImmutables.sol'; import './pool/IUniswapV3PoolState.sol'; import './pool/IUniswapV3PoolDerivedState.sol'; import './pool/IUniswapV3PoolActions.sol'; import './pool/IUniswapV3PoolOwnerActions.sol'; import './pool/IUniswapV3PoolEvents.sol'; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; /// @title Quoter Interface /// @notice Supports quoting the calculated amounts from exact input or exact output swaps /// @dev These functions are not marked view because they rely on calling non-view functions and reverting /// to compute the result. They are also not gas efficient and should not be called on-chain. interface IQuoter { /// @notice Returns the amount out received for a given exact input swap without executing the swap /// @param path The path of the swap, i.e. each token pair and the pool fee /// @param amountIn The amount of the first token to swap /// @return amountOut The amount of the last token that would be received function quoteExactInput(bytes memory path, uint256 amountIn) external returns (uint256 amountOut); /// @notice Returns the amount out received for a given exact input but for a swap of a single pool /// @param tokenIn The token being swapped in /// @param tokenOut The token being swapped out /// @param fee The fee of the token pool to consider for the pair /// @param amountIn The desired input amount /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap /// @return amountOut The amount of `tokenOut` that would be received function quoteExactInputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountOut); /// @notice Returns the amount in required for a given exact output swap without executing the swap /// @param path The path of the swap, i.e. each token pair and the pool fee /// @param amountOut The amount of the last token to receive /// @return amountIn The amount of first token required to be paid function quoteExactOutput(bytes memory path, uint256 amountOut) external returns (uint256 amountIn); /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool /// @param tokenIn The token being swapped in /// @param tokenOut The token being swapped out /// @param fee The fee of the token pool to consider for the pair /// @param amountOut The desired output amount /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap /// @return amountIn The amount required as the input for the swap in order to receive `amountOut` function quoteExactOutputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountOut, uint160 sqrtPriceLimitX96 ) external returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import '../interfaces/IPeripheryImmutableState.sol'; /// @title Immutable state /// @notice Immutable state used by periphery contracts abstract contract PeripheryImmutableState is IPeripheryImmutableState { /// @inheritdoc IPeripheryImmutableState address public immutable override factory; /// @inheritdoc IPeripheryImmutableState address public immutable override WETH9; constructor(address _factory, address _WETH9) { factory = _factory; WETH9 = _WETH9; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import './BytesLib.sol'; /// @title Functions for manipulating path data for multihop swaps library Path { using BytesLib for bytes; /// @dev The length of the bytes encoded address uint256 private constant ADDR_SIZE = 20; /// @dev The length of the bytes encoded fee uint256 private constant FEE_SIZE = 3; /// @dev The offset of a single token address and pool fee uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE; /// @dev The offset of an encoded pool key uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE; /// @dev The minimum length of an encoding that contains 2 or more pools uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET; /// @notice Returns true iff the path contains two or more pools /// @param path The encoded swap path /// @return True if path contains two or more pools, otherwise false function hasMultiplePools(bytes memory path) internal pure returns (bool) { return path.length >= MULTIPLE_POOLS_MIN_LENGTH; } /// @notice Decodes the first pool in path /// @param path The bytes encoded swap path /// @return tokenA The first token of the given pool /// @return tokenB The second token of the given pool /// @return fee The fee level of the pool function decodeFirstPool(bytes memory path) internal pure returns ( address tokenA, address tokenB, uint24 fee ) { tokenA = path.toAddress(0); fee = path.toUint24(ADDR_SIZE); tokenB = path.toAddress(NEXT_OFFSET); } /// @notice Gets the segment corresponding to the first pool in the path /// @param path The bytes encoded swap path /// @return The segment containing all data necessary to target the first pool in the path function getFirstPool(bytes memory path) internal pure returns (bytes memory) { return path.slice(0, POP_OFFSET); } /// @notice Skips a token + fee element from the buffer and returns the remainder /// @param path The swap path /// @return The remaining token + fee elements in the path function skipToken(bytes memory path) internal pure returns (bytes memory) { return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param factory The Uniswap V3 factory contract address /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity =0.7.6; import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol'; import './PoolAddress.sol'; /// @notice Provides validation for callbacks from Uniswap V3 Pools library CallbackValidation { /// @notice Returns the address of a valid Uniswap V3 Pool /// @param factory The contract address of the Uniswap V3 factory /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The V3 pool contract address function verifyCallback( address factory, address tokenA, address tokenB, uint24 fee ) internal view returns (IUniswapV3Pool pool) { return verifyCallback(factory, PoolAddress.getPoolKey(tokenA, tokenB, fee)); } /// @notice Returns the address of a valid Uniswap V3 Pool /// @param factory The contract address of the Uniswap V3 factory /// @param poolKey The identifying key of the V3 pool /// @return pool The V3 pool contract address function verifyCallback(address factory, PoolAddress.PoolKey memory poolKey) internal view returns (IUniswapV3Pool pool) { pool = IUniswapV3Pool(PoolAddress.computeAddress(factory, poolKey)); require(msg.sender == address(pool)); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Immutable state /// @notice Functions that return immutable state of the router interface IPeripheryImmutableState { /// @return Returns the address of the Uniswap V3 factory function factory() external view returns (address); /// @return Returns the address of WETH9 function WETH9() external view returns (address); } // SPDX-License-Identifier: GPL-2.0-or-later /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity >=0.5.0 <0.8.0; library BytesLib { function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, 'slice_overflow'); require(_start + _length >= _start, 'slice_overflow'); require(_bytes.length >= _start + _length, 'slice_outOfBounds'); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, 'toAddress_overflow'); require(_bytes.length >= _start + 20, 'toAddress_outOfBounds'); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_start + 3 >= _start, 'toUint24_overflow'); require(_bytes.length >= _start + 3, 'toUint24_outOfBounds'); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } }
@inheritdoc IQuoter
function quoteExactInput(bytes memory path, uint256 amountIn) external override returns (uint256 amountOut) { while (true) { bool hasMultiplePools = path.hasMultiplePools(); (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool(); amountIn = quoteExactInputSingle(tokenIn, tokenOut, fee, amountIn, 0); if (hasMultiplePools) { path = path.skipToken(); return amountIn; } } while (true) { bool hasMultiplePools = path.hasMultiplePools(); (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool(); amountIn = quoteExactInputSingle(tokenIn, tokenOut, fee, amountIn, 0); if (hasMultiplePools) { path = path.skipToken(); return amountIn; } } } else { }
350,082
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /* *\ * ,.-"""-., * * / === \ * * / ======= \ * * __| (o) (0) |__ * * / _| .---. |_ \ * * | /.----/ O O \----.\ | * * \/ | | \/ * * | | * * | | * * | | * * _\ -.,_____,.- /_ * * ,.-" "-.,_________,.-" "-., * * / | | ╭-╮ \ * * | l. .l ┃ ┃ | * * | | | ┃ ╰━━╮ | * * l. | | ┃ ╭╮ ┃ .l * * | l. .l ┃ ┃┃ ┃ | \, * * l. | | ╰-╯╰-╯ .l \, * * | | | | \, * * l. | | .l | * * | | | | | * * | |---| | | * * | | | | | * * /"-.,__,.-"\ /"-.,__,.-"\"-.,_,.-"\ * * | \ / | | * * | | | | * * \__|__|__|__/ \__|__|__|__/ \_|__|__/ * \* */ contract ForexVesting is Ownable { using SafeERC20 for IERC20; /** @dev Canonical FOREX token address */ address public immutable FOREX; /** @dev The vesting period in seconds at which the FOREX supply for each participant is accrued as claimable each second according to their vested value */ uint256 public immutable vestingPeriod; /** @dev Minimum delay (in seconds) between user claims. */ uint256 public immutable minimumClaimDelay; /** @dev Date from which participants can claim their immediate value, and from which the vested value starts accruing as claimable */ uint256 public claimStartDate; /** @dev Mapping of (participant address => participant vesting data) */ mapping(address => Participant) public participants; /** @dev Total funds required by contract. Used for asserting the contract has been correctly funded after deployment */ uint256 public immutable forexSupply; /** @dev Vesting data for participant */ struct Participant { /* Amount initially claimable at any time from the claimStartDate */ uint256 claimable; /* Total vested amount released in equal amounts throughout the vesting period. */ uint256 vestedValue; /* Date at which the participant last claimed FOREX */ uint256 lastClaimDate; } event ParticipantAddressChanged( address indexed previous, address indexed current ); constructor( address _FOREX, uint256 _vestingPeriod, uint256 _minimumClaimDelay, address[] memory participantAddresses, uint256[] memory initiallyClaimable, uint256[] memory vestedValues ) { // Assert that the minimum claim delay is greater than zero seconds. assert(_minimumClaimDelay > 0); // Assert that the vesting period is a multiple of the minimum delay. assert(_vestingPeriod % _minimumClaimDelay == 0); // Assert all array lengths match. uint256 length = participantAddresses.length; assert(length == initiallyClaimable.length); assert(length == vestedValues.length); // Initialise immutable variables. FOREX = _FOREX; vestingPeriod = _vestingPeriod; minimumClaimDelay = _minimumClaimDelay; uint256 _forexSupply = 0; // Initialise participants mapping. for (uint256 i = 0; i < length; i++) { participants[participantAddresses[i]] = Participant({ claimable: initiallyClaimable[i], vestedValue: vestedValues[i], lastClaimDate: 0 }); _forexSupply += initiallyClaimable[i] + vestedValues[i]; } forexSupply = _forexSupply; } /** * @dev Transfers claimable FOREX to participant. */ function claim() external { require(isClaimable(), "Funds not yet claimable"); Participant storage participant = participants[msg.sender]; require( block.timestamp >= participant.lastClaimDate + minimumClaimDelay, "Must wait before next claim" ); uint256 cutoffTime = getLastCutoffTime(msg.sender); uint256 claimable = _balanceOf(msg.sender, cutoffTime); if (claimable == 0) return; // Reset vesting period for accruing new FOREX. // This starts at the claim date and then is incremented in // a value multiple of minimumClaimDelay. participant.lastClaimDate = cutoffTime; // Clear initial claimable amount if claiming for the first time. if (participant.claimable > 0) participant.claimable = 0; // Transfer tokens. IERC20(FOREX).safeTransfer(msg.sender, claimable); } /** * @dev Returns the last valid claim date for a participant. * The difference between this value and the participant's * last claim date is the actual claimable amount that * can be transferred so that the minimum delay also enforces * a minimum FOREX claim granularity. * @param account The participant account to fetch the cutoff time for. */ function getLastCutoffTime(address account) public view returns (uint256) { Participant storage participant = participants[account]; uint256 lastClaimDate = getParticipantLastClaimDate(participant); uint256 elapsed = block.timestamp - lastClaimDate; uint256 remainder = elapsed % minimumClaimDelay; if (elapsed > remainder) { // At least one cutoff time has passed. return lastClaimDate + elapsed - remainder; } else { // Next cutoff time not yet reached. return lastClaimDate; } } /** * @dev Returns the parsed last claim date for a participant. * Instead of returning the default date of zero, it returns * the claim start date. * @param participant The storage pointer to a participant. */ function getParticipantLastClaimDate(Participant storage participant) private view returns (uint256) { return participant.lastClaimDate > claimStartDate ? participant.lastClaimDate : claimStartDate; } /** * @dev Returns the accrued FOREX balance for an participant. * This amount may not be fully claimable yet. * @param account The participant to fetch the balance for. */ function balanceOf(address account) public view returns (uint256) { return _balanceOf(account, block.timestamp); } /** * @dev Returns the claimable FOREX balance for an participant. * @param account The participant to fetch the balance for. * @param cutoffTime The time to fetch the balance from. */ function _balanceOf(address account, uint256 cutoffTime) public view returns (uint256) { if (!isClaimable()) return 0; Participant storage participant = participants[account]; uint256 lastClaimed = getParticipantLastClaimDate(participant); uint256 vestingCompleteDate = claimStartDate + vestingPeriod; // Prevent elapsed from passing the vestingPeriod value. uint256 elapsed = cutoffTime > vestingCompleteDate ? vestingCompleteDate - lastClaimed : cutoffTime - lastClaimed; uint256 accrued = (participant.vestedValue * elapsed) / vestingPeriod; return participant.claimable + accrued; } /** * @dev Withdraws FOREX for the contract owner. * @param amount The amount of FOREX to withdraw. */ function withdrawForex(uint256 amount) external onlyOwner { IERC20(FOREX).safeTransfer(msg.sender, amount); } /** * @dev Changes the address for a participant. The new address * will be eligible to claim the currently claimable funds * from the previous address, plus all the accrued funds * until the end of the vesting period. * @param previous The previous participant address to be changed. * @param current The current participant address to be eligible for claims. */ function changeParticipantAddress(address previous, address current) external onlyOwner { require(current != address(0), "Current address cannot be zero"); require(previous != current, "Addresses are the same"); Participant storage previousParticipant = participants[previous]; require( doesParticipantExist(previousParticipant), "Previous participant does not exist" ); Participant storage currentParticipant = participants[current]; require( !doesParticipantExist(currentParticipant), "Next participant already exists" ); currentParticipant.claimable = previousParticipant.claimable; currentParticipant.vestedValue = previousParticipant.vestedValue; currentParticipant.lastClaimDate = previousParticipant.lastClaimDate; delete participants[previous]; emit ParticipantAddressChanged(previous, current); } /** * @dev Returns whether the participant exists. * @param participant Pointer to the participant object. */ function doesParticipantExist(Participant storage participant) private view returns (bool) { return participant.claimable > 0 || participant.vestedValue > 0; } /** * @dev Enables FOREX claiming from the next block. * Can only be called once. */ function enableForexClaims() public onlyOwner { assert(claimStartDate == 0); claimStartDate = block.timestamp + 1; } /** * Returns whether the contract is currently claimable. */ function isClaimable() private view returns (bool) { return claimStartDate != 0 && block.timestamp >= claimStartDate; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
Returns whether the contract is currently claimable./
function isClaimable() private view returns (bool) { return claimStartDate != 0 && block.timestamp >= claimStartDate; }
9,945,750
pragma solidity 0.5.11; pragma experimental "ABIEncoderV2"; import "../interfaces/CounterfactualApp.sol"; /// @title LibAppCaller /// @author Liam Horne - <[email protected]> /// @notice A library for the ChallengeRegistry to make staticcalls to Apps contract LibAppCaller { /// @notice A helper method to check if the state of an application is terminal or not /// @param appDefinition An address of an app definition to call /// @param appState The ABI encoded version of some application state /// @return A boolean indicating if the application state is terminal or not function isStateTerminal( address appDefinition, bytes memory appState ) internal pure returns (bool) { return CounterfactualApp(appDefinition).isStateTerminal(appState); } /// @notice A helper method to get the turn taker for an app /// @param appDefinition An address of an app definition to call /// @param appState The ABI encoded version of some application state /// @return An address representing the turn taker in the `participants` function getTurnTaker( address appDefinition, address[] memory participants, bytes memory appState ) internal pure returns (address) { return CounterfactualApp(appDefinition) .getTurnTaker(appState, participants); } /// @notice Execute the application's applyAction function to compute new state /// @param appDefinition An address of an app definition to call /// @param appState The ABI encoded version of some application state /// @param action The ABI encoded version of some application action /// @return A bytes array of the ABI encoded newly computed application state function applyAction( address appDefinition, bytes memory appState, bytes memory action ) internal pure returns (bytes memory) { return CounterfactualApp(appDefinition).applyAction(appState, action); } /// @notice Execute the application's computeOutcome function to compute an outcome /// @param appDefinition An address of an app definition to call /// @param appState The ABI encoded version of some application state function computeOutcome( address appDefinition, bytes memory appState ) internal pure returns (bytes memory) { return CounterfactualApp(appDefinition).computeOutcome(appState); } }
Execute the application's applyAction function to compute new state appDefinition An address of an app definition to call appState The ABI encoded version of some application state action The ABI encoded version of some application action return A bytes array of the ABI encoded newly computed application state
function applyAction( address appDefinition, bytes memory appState, bytes memory action ) internal pure returns (bytes memory) { return CounterfactualApp(appDefinition).applyAction(appState, action); }
12,596,136
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; // Part: IERC20Wrapper interface IERC20Wrapper { /// @dev Return the underlying ERC-20 for the given ERC-1155 token id. function getUnderlyingToken(uint id) external view returns (address); /// @dev Return the conversion rate from ERC-1155 to ERC-20, multiplied by 2**112. function getUnderlyingRate(uint id) external view returns (uint); } // Part: IMasterChef interface IMasterChef { function sushi() external view returns (address); function poolInfo(uint pid) external view returns ( address lpToken, uint allocPoint, uint lastRewardBlock, uint accSushiPerShare ); function deposit(uint pid, uint amount) external; function withdraw(uint pid, uint amount) external; } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // 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); } } } } // Part: OpenZeppelin/[email protected]/Context /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Part: OpenZeppelin/[email protected]/IERC165 /** * @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); } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/ReentrancyGuard /** * @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; } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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; } } // Part: HomoraMath library HomoraMath { using SafeMath for uint; function divCeil(uint lhs, uint rhs) internal pure returns (uint) { return lhs.add(rhs).sub(1) / rhs; } function fmul(uint lhs, uint rhs) internal pure returns (uint) { return lhs.mul(rhs) / (2**112); } function fdiv(uint lhs, uint rhs) internal pure returns (uint) { return lhs.mul(2**112) / rhs; } // implementation from https://github.com/Uniswap/uniswap-lib/commit/99f3f28770640ba1bb1ff460ac7c5292fb8291a0 // original implementation: https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687 function sqrt(uint x) internal pure returns (uint) { if (x == 0) return 0; uint xx = x; uint r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint r1 = x / r; return (r < r1 ? r : r1); } } // Part: OpenZeppelin/[email protected]/ERC165 /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // Part: OpenZeppelin/[email protected]/IERC1155 /** * @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; } // Part: OpenZeppelin/[email protected]/IERC1155Receiver /** * _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); } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: OpenZeppelin/[email protected]/IERC1155MetadataURI /** * @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); } // Part: OpenZeppelin/[email protected]/ERC1155 /** * * @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)) private _balances; // Mapping from account to operator approvals mapping (address => mapping(address => bool)) private _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_) public { _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 (uint 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 (uint 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 ) private { 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 ) private { 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) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // File: WMasterChef.sol contract WMasterChef is ERC1155('WMasterChef'), ReentrancyGuard, IERC20Wrapper { using SafeMath for uint; using HomoraMath for uint; using SafeERC20 for IERC20; IMasterChef public immutable chef; // Sushiswap masterChef IERC20 public immutable sushi; // Sushi token constructor(IMasterChef _chef) public { chef = _chef; sushi = IERC20(_chef.sushi()); } /// @dev Encode pid, sushiPerShare to ERC1155 token id /// @param pid Pool id (16-bit) /// @param sushiPerShare Sushi amount per share, multiplied by 1e18 (240-bit) function encodeId(uint pid, uint sushiPerShare) public pure returns (uint id) { require(pid < (1 << 16), 'bad pid'); require(sushiPerShare < (1 << 240), 'bad sushi per share'); return (pid << 240) | sushiPerShare; } /// @dev Decode ERC1155 token id to pid, sushiPerShare /// @param id Token id function decodeId(uint id) public pure returns (uint pid, uint sushiPerShare) { pid = id >> 240; // First 16 bits sushiPerShare = id & ((1 << 240) - 1); // Last 240 bits } /// @dev Return the underlying ERC-20 for the given ERC-1155 token id. /// @param id Token id function getUnderlyingToken(uint id) external view override returns (address) { (uint pid, ) = decodeId(id); (address lpToken, , , ) = chef.poolInfo(pid); return lpToken; } /// @dev Return the conversion rate from ERC-1155 to ERC-20, multiplied by 2**112. function getUnderlyingRate(uint) external view override returns (uint) { return 2**112; } /// @dev Mint ERC1155 token for the given pool id. /// @param pid Pool id /// @param amount Token amount to wrap /// @return The token id that got minted. function mint(uint pid, uint amount) external nonReentrant returns (uint) { (address lpToken, , , ) = chef.poolInfo(pid); IERC20(lpToken).safeTransferFrom(msg.sender, address(this), amount); if (IERC20(lpToken).allowance(address(this), address(chef)) != uint(-1)) { // We only need to do this once per pool, as LP token's allowance won't decrease if it's -1. IERC20(lpToken).safeApprove(address(chef), uint(-1)); } chef.deposit(pid, amount); (, , , uint sushiPerShare) = chef.poolInfo(pid); uint id = encodeId(pid, sushiPerShare); _mint(msg.sender, id, amount, ''); return id; } /// @dev Burn ERC1155 token to redeem LP ERC20 token back plus SUSHI rewards. /// @param id Token id /// @param amount Token amount to burn /// @return The pool id that that you will receive LP token back. function burn(uint id, uint amount) external nonReentrant returns (uint) { if (amount == uint(-1)) { amount = balanceOf(msg.sender, id); } (uint pid, uint stSushiPerShare) = decodeId(id); _burn(msg.sender, id, amount); chef.withdraw(pid, amount); (address lpToken, , , uint enSushiPerShare) = chef.poolInfo(pid); IERC20(lpToken).safeTransfer(msg.sender, amount); uint stSushi = stSushiPerShare.mul(amount).divCeil(1e12); uint enSushi = enSushiPerShare.mul(amount).div(1e12); if (enSushi > stSushi) { sushi.safeTransfer(msg.sender, enSushi.sub(stSushi)); } return pid; } }
Burn ERC1155 token to redeem LP ERC20 token back plus SUSHI rewards. id Token id amount Token amount to burn return The pool id that that you will receive LP token back.
function burn(uint id, uint amount) external nonReentrant returns (uint) { if (amount == uint(-1)) { amount = balanceOf(msg.sender, id); } (uint pid, uint stSushiPerShare) = decodeId(id); _burn(msg.sender, id, amount); chef.withdraw(pid, amount); (address lpToken, , , uint enSushiPerShare) = chef.poolInfo(pid); IERC20(lpToken).safeTransfer(msg.sender, amount); uint stSushi = stSushiPerShare.mul(amount).divCeil(1e12); uint enSushi = enSushiPerShare.mul(amount).div(1e12); if (enSushi > stSushi) { sushi.safeTransfer(msg.sender, enSushi.sub(stSushi)); } return pid; }
12,035,131
./full_match/137/0x2b7f5C0ae63365eb033bbC2e67821d3a6650986f/sources/contracts/helpers/EnsoShortcutsHelpers.sol
Returns `input` bytes32 as uint256./
function bytes32ToUint256(bytes32 input) external pure returns (uint256) { return uint256(input); }
3,756,129
./full_match/1/0xd9dF2211b576D430FAb3BD93f915a1345974D797/sources/contracts/v1/governance/PRTCLCoreERC721Votes.sol
Override regular delegation to disable it/
function delegate(address /* delegatee */, uint256 /* collectionId */) public virtual override { revert("PRTCLCoreERC721Votes: regular delegation disabled. Please use delegation with signature."); }
8,408,837
./full_match/5/0x5c0CEcB41148E1528e7ec8d8a6a04CC2b3E0592c/sources/project_/contracts/examples/IncentivisedSlidingWindowOracle.sol
returns the observation from the oldest epoch (at the beginning of the window) relative to the current time no overflow issue. if observationIndex + 1 overflows, result is still zero.
function getFirstObservationInWindow(address pair) private view returns (Observation storage firstObservation) { uint8 observationIndex = observationIndexOf(block.timestamp); uint8 firstObservationIndex = (observationIndex + 1) % granularity; firstObservation = pairObservations[pair][firstObservationIndex]; }
1,949,549
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Errors.sol"; import "./PaymentSplitter.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract WithinWithout is Context, PaymentSplitter, ERC721, ReentrancyGuard, AccessControl, Ownable { using Address for address; struct Collection { uint256 priceInWei; uint256 maxPresaleMints; uint256 maxReservedMints; uint256 maxSupply; uint256 maxMintsPerPurchase; } struct TokenData { uint256 printsCount; bytes32 tokenHash; } Collection public collection; string public script; event Mint(uint256 indexed tokenId, address indexed minter, bytes32 tokenHash, uint256 fingerprintsBalance); mapping(uint256 => TokenData) public tokenIdToTokenData; uint256 private presaleMintCount = 0; uint256 private reservedMintCount = 0; uint256 public totalSupply = 0; bool public presaleStarted; uint256 public publicSaleStartingBlock; mapping(address => bool) public presaleMints; bytes32 public merkleRootSingleMint; bytes32 public merkleRootDoubleMint; address public prints; string private baseURI_ = "https://www.withinwithout.xyz/api/token/metadata/"; constructor( address[] memory payees_, uint256[] memory shares_, address[] memory admins_, Collection memory collection_, address prints_ ) ERC721("Within/Without", "WW") PaymentSplitter(payees_, shares_) { _grantRole(DEFAULT_ADMIN_ROLE, _msgSender()); for (uint256 i = 0; i < admins_.length; i++) { _grantRole(DEFAULT_ADMIN_ROLE, admins_[i]); } collection = collection_; prints = prints_; } function publicSupplyRemaining() public view returns (uint256) { return collection.maxSupply - totalSupply - (collection.maxReservedMints - reservedMintCount); } function publicSaleStarted() public view returns (bool) { return presaleStarted && block.number >= publicSaleStartingBlock; } function startPresale() external onlyRole(DEFAULT_ADMIN_ROLE) { publicSaleStartingBlock = block.number + 720; // ~ Three hours after presale starts presaleStarted = true; } function updatePublicSaleStartBlock(uint256 startingBlock) external onlyRole(DEFAULT_ADMIN_ROLE) { publicSaleStartingBlock = startingBlock; } function setMerkleRoots(bytes32 merkleRootSingleMint_, bytes32 merkleRootDoubleMint_) external onlyRole(DEFAULT_ADMIN_ROLE) { merkleRootSingleMint = merkleRootSingleMint_; merkleRootDoubleMint = merkleRootDoubleMint_; } function mintReserved(uint256 count) public nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { if (count == 0) revert CountCannotBeZero(); if (reservedMintCount >= collection.maxReservedMints) revert ReserveMintCountExceeded(); // Edge case: minter wants to buy multiple but we have less supply than their count, // but don't want them to get nothing uint256 remaining = collection.maxReservedMints - reservedMintCount; count = uint256(Math.min(count, remaining)); reservedMintCount += count; handleMint(_msgSender(), count); } function purchasePresale(uint256 count, bytes32[] calldata _merkleProof) external payable nonReentrant { if (!presaleStarted) revert PresaleNotOpen(); if (publicSaleStarted()) revert PublicSaleAlreadyOpen(); if (presaleMintCount >= collection.maxPresaleMints) revert PresaleSoldOut(); if (publicSupplyRemaining() == 0) revert CollectionSoldOut(); if (presaleMints[_msgSender()] == true) revert AlreadyMintedInPresale(); if (count == 0) revert CountCannotBeZero(); if (count > 2) revert CountExceedsMaxMints(); address minter = _msgSender(); bytes32 leaf = keccak256(abi.encodePacked(minter)); if (count == 1) { // @dev: note, everyone in the double mint merkle tree is also in the single mint tree, so people // eligible for 2 mints can mint only 1 if they want if (!MerkleProof.verify(_merkleProof, merkleRootSingleMint, leaf)) revert NotEligible(); } if (count == 2) { if (!MerkleProof.verify(_merkleProof, merkleRootDoubleMint, leaf)) revert NotEligible(); } // Edge case: minter wants to buy multiple but we have less supply than their count, // but don't want them to get nothing uint256 remaining = collection.maxPresaleMints - presaleMintCount; count = uint256(Math.min(count, remaining)); presaleMints[minter] = true; presaleMintCount += count; mint(minter, collection.priceInWei, count); } function purchase(uint256 count) external payable nonReentrant { if (!publicSaleStarted()) revert PublicSaleNotOpen(); if (count == 0) revert CountCannotBeZero(); if (publicSupplyRemaining() == 0) revert CollectionSoldOut(); address minter = _msgSender(); if (count > collection.maxMintsPerPurchase) revert CountExceedsMaxMints(); // Edge case: minter wants to buy multiple but we have less supply than their count, // but don't want them to get nothing count = uint256(Math.min(count, publicSupplyRemaining())); mint(minter, collection.priceInWei, count); } function mint( address minter, uint256 priceInWei, uint256 count ) private { if (minter.isContract()) revert CannotPurchaseFromContract(); uint256 cost = priceInWei * count; if (msg.value < cost) revert InsufficientFundsForPurchase(); if (msg.value > cost) { // Refund any excess payable(minter).transfer(msg.value - cost); } handleMint(minter, count); } function handleMint(address minter, uint256 count) private { for (uint256 i = 0; i < count; i++) { uint256 tokenId = totalSupply; bytes32 tokenHash = keccak256( abi.encodePacked(blockhash(block.number - 1), block.number, block.timestamp, minter, tokenId) ); uint256 fingerprintsBalance = IERC20(prints).balanceOf(minter); tokenIdToTokenData[tokenId] = TokenData(fingerprintsBalance, tokenHash); totalSupply++; _safeMint(minter, tokenId); emit Mint(tokenId, minter, tokenHash, fingerprintsBalance); } } function getTokensOfOwner(address _owner) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](tokenCount); uint256 seen = 0; for (uint256 i; i < totalSupply; i++) { if (ownerOf(i) == _owner) { tokenIds[seen] = i; seen++; } } return tokenIds; } function setBaseURI(string memory uri) external onlyRole(DEFAULT_ADMIN_ROLE) { baseURI_ = uri; } function _baseURI() internal view override returns (string memory) { return baseURI_; } function setScript(string memory script_) external onlyRole(DEFAULT_ADMIN_ROLE) { script = script_; } function updateCollection(Collection memory collection_) external onlyRole(DEFAULT_ADMIN_ROLE) { require(!presaleStarted, "The sale has already started"); collection = collection_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; error InsufficientFundsForPurchase(); error CollectionPaused(); error CollectionSoldOut(); error PresaleNotOpen(); error PresaleSoldOut(); error AlreadyMintedInPresale(); error PublicSaleAlreadyOpen(); error PublicSaleNotOpen(); error NotEligible(); error CountCannotBeZero(); error ReserveMintCountExceeded(); error AccountExceedsMaxMints(); error CountExceedsMaxMints(); error CannotPurchaseFromContract(); // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Context.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(payable(account), payment); emit PaymentReleased(account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // 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 (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/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/Math.sol) pragma solidity ^0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 (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 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 (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); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; }
Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the total shares and their previous withdrawals./
function release(address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(payable(account), payment); emit PaymentReleased(account, payment); }
5,839,753
/** *Submitted for verification at Etherscan.io on 2020-12-18 */ // SPDX-License-Identifier: MIT // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: contracts/upgrade_proxy/Proxy.sol pragma solidity ^0.6.0; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _delegate(address implementation) internal { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function * and {_fallback} should delegate. */ function _implementation() internal virtual view returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal { _beforeFallback(); _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback () payable external { _fallback(); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data * is empty. */ receive () payable external { _fallback(); } /** * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback` * call, or as part of the Solidity `fallback` or `receive` functions. * * If overriden should call `super._beforeFallback()`. */ function _beforeFallback() internal virtual { } } // File: contracts/upgrade_proxy/UpgradeableProxy.sol pragma solidity ^0.6.0; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. * * Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see * {TransparentUpgradeableProxy}. */ contract UpgradeableProxy is Proxy { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`. * * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded * function call, and allows initializating the storage of the proxy like a Solidity constructor. */ constructor(address _logic, bytes memory _data) public payable { assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if(_data.length > 0) { // solhint-disable-next-line avoid-low-level-calls (bool success,) = _logic.delegatecall(_data); require(success); } } /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation address. */ function _implementation() internal override view returns (address impl) { bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(Address.isContract(newImplementation), "UpgradeableProxy: new implementation is not a contract"); bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newImplementation) } } } // File: contracts/upgrade_proxy/TransparentUpgradeableProxy.sol pragma solidity ^0.6.0; /** * @dev This contract implements a proxy that is upgradeable by an admin. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches one of the admin functions exposed by the proxy itself. * 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the * implementation. If the admin tries to call a function on the implementation it will fail with an error that says * "admin cannot fallback to proxy target". * * These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing * the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due * to sudden errors when trying to call a function from the proxy implementation. * * Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way, * you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy. */ contract TransparentUpgradeableProxy is UpgradeableProxy { /** * @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and * optionally initialized with `_data` as explained in {UpgradeableProxy-constructor}. */ constructor(address _logic, address _admin, bytes memory _data) public payable UpgradeableProxy(_logic, _data) { assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(_admin); } /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @dev Returns the current admin. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @dev Returns the current implementation. * * NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the * https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. * * NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the implementation of the proxy. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified * by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the * proxied contract. * * NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}. */ function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin { _upgradeTo(newImplementation); // solhint-disable-next-line avoid-low-level-calls (bool success,) = newImplementation.delegatecall(data); require(success); } /** * @dev Returns the current admin. */ function _admin() internal view returns (address adm) { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { adm := sload(slot) } } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { bytes32 slot = _ADMIN_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, newAdmin) } } /** * @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}. */ function _beforeFallback() internal override virtual { require(msg.sender != _admin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target"); super._beforeFallback(); } }
Changes the admin of the proxy. Emits an {AdminChanged} event. NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}./
function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "TransparentUpgradeableProxy: new admin is the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); }
2,453,199
./partial_match/4/0x3c3d4e051D347f1dfDebe1F235754b6e12E01ecf/sources/InstantSwap.sol
Shows interest to be paid/ calculate time difference Get number of weeks Get the left out days Get Interest amount based on user loan amount
function viewInterest(address token, uint256 loanId, uint256 period) public view returns (uint256 value, uint256 leftoutDays) { uint256 time = (loans[loanId].interestpaidOn > 0 ? loans[loanId].interestpaidOn : loans[loanId].depositTime); time = now.sub(time); time = time.div(604800); leftoutDays = time.mod(604800); uint256 interest; if(loans[loanId].amount > 0 && loans[loanId].amount >= 10000) { interest = (token == USDC ? USDCInterest[1] : OROInterest[1]); } if(loans[loanId].amount > 10000 && loans[loanId].amount >= 50000) { interest = (token == USDC ? USDCInterest[2] : OROInterest[2]); } if(loans[loanId].amount > 50000 && loans[loanId].amount >= 100000) { interest = (token == USDC ? USDCInterest[3] : OROInterest[3]); } if(loans[loanId].amount > 100000) { interest = (token == USDC ? USDCInterest[4] : OROInterest[4]); } }
8,620,924
pragma solidity ^0.4.15; contract testAddress { function f() { address x = 0x123; address myAddress = this; if (x.balance < 10 && myAddress.balance >= 10) x.transfer(10); } function g() { address nameReg = 0x72ba7d8e73fe8eb666ea66babc8116a41bfb10e2; nameReg.call("register", "MyName"); nameReg.call(bytes4(keccak256("fun(uint256)")), 1); } } contract test { enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } ActionChoices choice; ActionChoices constant defaultChoice = ActionChoices.GoStraight; function setGoStraight() { choice = ActionChoices.GoStraight; } // Since enum types are not part of the ABI, the signature of "getChoice" // will automatically be changed to "getChoice() returns (uint8)" // for all matters external to Solidity. The integer type used is just // large enough to hold all enum values, i.e. if you have more values, // `uint16` will be used and so on. function getChoice() returns (ActionChoices) { return choice; } function getDefaultChoice() returns (uint) { return uint(defaultChoice); } } library ArrayUtils { // internal functions can be used in internal library functions because // they will be part of the same code context function map(uint[] memory self, function (uint) returns (uint) f) internal returns (uint[] memory r) { r = new uint[](self.length); for (uint i = 0; i < self.length; i++) { r[i] = f(self[i]); } } function reduce( uint[] memory self, function (uint, uint) returns (uint) f ) internal returns (uint r) { r = self[0]; for (uint i = 1; i < self.length; i++) { r = f(r, self[i]); } } function range(uint length) internal returns (uint[] memory r) { r = new uint[](length); for (uint i = 0; i < r.length; i++) { r[i] = i; } } } contract Pyramid { using ArrayUtils for *; function pyramid(uint l) returns (uint) { ArrayUtils.range(l); } function square(uint x) internal returns (uint) { return x * x; } function sum(uint x, uint y) internal returns (uint) { return x + y; } } contract Oracle { struct Request { bytes data; function(bytes memory) external callback; } Request[] requests; event NewRequest(uint); function query(bytes data, function(bytes memory) external callback) { requests.push(Request(data, callback)); NewRequest(requests.length - 1); } function reply(uint requestID, bytes response) { // Here goes the check that the reply comes from a trusted source requests[requestID].callback(response); } } contract OracleUser { Oracle constant oracle = Oracle(0x1234567); // known contract function buySomething() { oracle.query("USD", this.oracleResponse); } function oracleResponse(bytes response) { require(msg.sender == address(oracle)); // Use the data } } contract C { uint[] x; // the data location of x is storage // the data location of memoryArray is memory function f(uint[] memoryArray) { x = memoryArray; // works, copies the whole array to storage var y = x; // works, assigns a pointer, data location of y is storage y[7]; // fine, returns the 8th element y.length = 2; // fine, modifies x through y delete x; // fine, clears the array, also modifies y // The following does not work; it would need to create a new temporary / // unnamed array in storage, but storage is "statically" allocated: // y = memoryArray; // This does not work either, since it would "reset" the pointer, but there // is no sensible location it could point to. // delete y; g(x); // calls g, handing over a reference to x h(x); // calls h and creates an independent, temporary copy in memory } function g(uint[] storage storageArray) internal {} function h(uint[] memoryArray) {} } contract C2 { function f(uint len) { uint[] memory a = new uint[](7); bytes memory b = new bytes(len); // Here we have a.length == 7 and b.length == len a[6] = 8; } } contract C3 { function f() { g([uint(1), 2, 3]); } function g(uint[3] _data) { // ... } } contract ArrayContract { uint[2**20] m_aLotOfIntegers; // Note that the following is not a pair of dynamic arrays but a // dynamic array of pairs (i.e. of fixed size arrays of length two). bool[2][] m_pairsOfFlags; // newPairs is stored in memory - the default for function arguments function setAllFlagPairs(bool[2][] newPairs) { // assignment to a storage array replaces the complete array m_pairsOfFlags = newPairs; } function setFlagPair(uint index, bool flagA, bool flagB) { // access to a non-existing index will throw an exception m_pairsOfFlags[index][0] = flagA; m_pairsOfFlags[index][1] = flagB; } function changeFlagArraySize(uint newSize) { // if the new size is smaller, removed array elements will be cleared m_pairsOfFlags.length = newSize; } function clear() { // these clear the arrays completely delete m_pairsOfFlags; delete m_aLotOfIntegers; // identical effect here m_pairsOfFlags.length = 0; } bytes m_byteData; function byteArrays(bytes data) { // byte arrays ("bytes") are different as they are stored without padding, // but can be treated identical to "uint8[]" m_byteData = data; m_byteData.length += 7; m_byteData[3] = 8; delete m_byteData[2]; } function addFlag(bool[2] flag) returns (uint) { return m_pairsOfFlags.push(flag); } function createMemoryArray(uint size) returns (bytes) { // Dynamic memory arrays are created using `new`: uint[2][] memory arrayOfPairs = new uint[2][](size); // Create a dynamic byte array: bytes memory b = new bytes(200); for (uint i = 0; i < b.length; i++) b[i] = byte(i); return b; } } contract CrowdFunding { // Defines a new type with two fields. struct Funder { address addr; uint amount; } struct Campaign { address beneficiary; uint fundingGoal; uint numFunders; uint amount; mapping (uint => Funder) funders; } uint numCampaigns; mapping (uint => Campaign) campaigns; function newCampaign(address beneficiary, uint goal) returns (uint campaignID) { campaignID = numCampaigns++; // campaignID is return variable // Creates new struct and saves in storage. We leave out the mapping type. campaigns[campaignID] = Campaign(beneficiary, goal, 0, 0); } function contribute(uint campaignID) payable { Campaign storage c = campaigns[campaignID]; // Creates a new temporary memory struct, initialised with the given values // and copies it over to storage. // Note that you can also use Funder(msg.sender, msg.value) to initialise. c.funders[c.numFunders++] = Funder({addr: msg.sender, amount: msg.value}); c.amount += msg.value; } function checkGoalReached(uint campaignID) returns (bool reached) { Campaign storage c = campaigns[campaignID]; if (c.amount < c.fundingGoal) return false; uint amount = c.amount; c.amount = 0; c.beneficiary.transfer(amount); return true; } } contract MappingExample { mapping(address => uint) public balances; function update(uint newBalance) { balances[msg.sender] = newBalance; } } contract MappingUser { function f() returns (uint) { MappingExample m = new MappingExample(); m.update(100); return m.balances(this); } } contract DeleteExample { uint data; uint[] dataArray; function f() { uint x = data; delete x; // sets x to 0, does not affect data delete data; // sets data to 0, does not affect x which still holds a copy uint[] y = dataArray; delete dataArray; // this sets dataArray.length to zero, but as uint[] is a complex object, also // y is affected which is an alias to the storage object // On the other hand: "delete y" is not valid, as assignments to local variables // referencing storage objects can only be made from existing storage objects. } }
Since enum types are not part of the ABI, the signature of "getChoice" will automatically be changed to "getChoice() returns (uint8)" for all matters external to Solidity. The integer type used is just large enough to hold all enum values, i.e. if you have more values, `uint16` will be used and so on.
function getChoice() returns (ActionChoices) { return choice; }
6,347,261
pragma solidity ^0.4.11; library SafeMath { // function assert(bool assertion) internal { // if (!assertion) { // throw; // } // } // assert no longer needed once solidity is on 0.4.10 */ 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&#39;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; } function max64(uint64 a, uint64 b) internal constant returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal constant returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal constant returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal constant returns (uint256) { return a < b ? a : b; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract SmileToken is StandardToken { string public name = "SMILECOIN"; string public symbol = "SMILECOIN"; uint256 public decimals = 3; uint256 public INITIAL_SUPPLY = 10001; /** * @dev Contructor that gives msg.sender all of existing tokens. */ function SmileToken() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } }
Contructor that gives msg.sender all of existing tokens./
function SmileToken() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; }
15,354,664
./partial_match/1/0xBa31AEF54734A89D7b89aBa2e0C7bf2564F6657F/sources/BPool.sol
Absorb any tokens that have been sent to this contract into the pool
function gulp(address token) external _logs_ _lock_ { require(_records[token].bound); _records[token].balance = IERC20(token).balanceOf(address(this)); }
3,711,864
./full_match/4/0x663065Ff4b7A99c06e264F743e99Fd1cB520e7dA/sources/contracts/NFTCollection.sol
buy token/1. verify price and not address(0)2. calculate fee3. transfer fee and transfer money to seller4. transfer token from seller to buyerfire event to FE
function buy(uint256 _tokenId, uint256 amount) public payable { address payable seller = payable(address(ERC721.ownerOf(_tokenId))); address buyer = msg.sender; uint256 payAmount = msg.value; require(payAmount >= amount, "Price issue"); uint256 fee = marketFee(payAmount); uint256 withFee = SafeMath.sub(payAmount, fee); seller.transfer(withFee); _marketAddress.transfer(fee); _beforeTokenTransfer(seller, buyer, _tokenId); safeTransferFrom(seller, buyer, _tokenId); emit Bought(_tokenId, tokenURI(_tokenId), payAmount); }
646,369
pragma solidity ^0.4.11; /** * @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; } } pragma solidity ^0.4.11; /** * @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() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } pragma solidity ^0.4.11; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } pragma solidity ^0.4.11; /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } pragma solidity ^0.4.11; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.4.11; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public 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) returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) 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); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } pragma solidity ^0.4.11; /***** * @title The ICO Contract */ contract DadiToken is StandardToken, Ownable { using SafeMath for uint256; /* Public variables of the token */ string public name = "DADI"; string public symbol = "DADI"; uint8 public decimals = 18; string public version = "H1.0"; address public owner; uint256 public hundredPercent = 1000; uint256 public foundersPercentOfTotal = 200; uint256 public referralPercentOfTotal = 50; uint256 public ecosystemPercentOfTotal = 25; uint256 public operationsPercentOfTotal = 25; uint256 public investorCount = 0; uint256 public totalRaised; // total ether raised (in wei) uint256 public preSaleRaised = 0; // ether raised (in wei) uint256 public publicSaleRaised = 0; // ether raised (in wei) // PartnerSale variables uint256 public partnerSaleTokensAvailable; uint256 public partnerSaleTokensPurchased = 0; mapping(address => uint256) public purchasedTokens; mapping(address => uint256) public partnerSaleWei; // PreSale variables uint256 public preSaleTokensAvailable; uint256 public preSaleTokensPurchased = 0; // PublicSale variables uint256 public publicSaleTokensAvailable; uint256 public publicSaleTokensPurchased = 0; // Price data uint256 public partnerSaleTokenPrice = 125; // USD$0.125 uint256 public partnerSaleTokenValue; uint256 public preSaleTokenPrice = 250; // USD$0.25 uint256 public publicSaleTokenPrice = 500; // USD$0.50 // ETH to USD Rate, set by owner: 1 ETH = ethRate USD uint256 public ethRate; // Address which will receive raised funds and owns the total supply of tokens address public fundsWallet; address public ecosystemWallet; address public operationsWallet; address public referralProgrammeWallet; address[] public foundingTeamWallets; address[] public partnerSaleWallets; address[] public preSaleWallets; address[] public publicSaleWallets; /***** * State machine * 0 - Preparing: All contract initialization calls * 1 - PartnerSale: Contract is in the invite-only PartnerSale Period * 6 - PartnerSaleFinalized: PartnerSale has completed * 2 - PreSale: Contract is in the PreSale Period * 7 - PreSaleFinalized: PreSale has completed * 3 - PublicSale: The public sale of tokens, follows PreSale * 8 - PublicSaleFinalized: The PublicSale has completed * 4 - Success: ICO Successful * 5 - Failure: Minimum funding goal not reached * 9 - Refunding: Owner can transfer refunds * 10 - Closed: ICO has finished, all tokens must have been claimed */ enum SaleState { Preparing, PartnerSale, PreSale, PublicSale, Success, Failure, PartnerSaleFinalized, PreSaleFinalized, PublicSaleFinalized, Refunding, Closed } SaleState public state = SaleState.Preparing; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param tokens amount of tokens purchased */ event LogTokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 tokens); event LogRedistributeTokens(address recipient, SaleState state, uint256 tokens); event LogRefundProcessed(address recipient, uint256 value); event LogRefundFailed(address recipient, uint256 value); event LogClaimTokens(address recipient, uint256 tokens); event LogFundTransfer(address wallet, uint256 value); /***** * @dev Modifier to check that amount transferred is not 0 */ modifier nonZero() { require(msg.value != 0); _; } /***** * @dev The constructor function to initialize the token related properties * @param _wallet address Specifies the address of the funding wallet * @param _operationalWallets address[] Specifies an array of addresses for [0] ecosystem, [1] operations, [2] referral programme * @param _foundingTeamWallets address[] Specifies an array of addresses of the founding team wallets * @param _initialSupply uint256 Specifies the total number of tokens available * @param _tokensAvailable uint256[] Specifies an array of tokens available for each phase, [0] PartnerSale, [1] PreSale, [2] PublicSale */ function DadiToken ( address _wallet, address[] _operationalWallets, address[] _foundingTeamWallets, uint256 _initialSupply, uint256[] _tokensAvailable ) public { require(_wallet != address(0)); owner = msg.sender; // Token distribution per sale phase partnerSaleTokensAvailable = _tokensAvailable[0]; preSaleTokensAvailable = _tokensAvailable[1]; publicSaleTokensAvailable = _tokensAvailable[2]; // Determine the actual supply using token amount * decimals totalSupply = _initialSupply * (uint256(10) ** decimals); // Give all the initial tokens to the contract owner balances[owner] = totalSupply; Transfer(0x0, owner, totalSupply); // Distribute tokens to the supporting operational wallets ecosystemWallet = _operationalWallets[0]; operationsWallet = _operationalWallets[1]; referralProgrammeWallet = _operationalWallets[2]; foundingTeamWallets = _foundingTeamWallets; fundsWallet = _wallet; // Set a base ETHUSD rate updateEthRate(300000); } /***** * @dev Fallback Function to buy the tokens */ function () payable { require( state == SaleState.PartnerSale || state == SaleState.PreSale || state == SaleState.PublicSale ); buyTokens(msg.sender, msg.value); } /***** * @dev Allows transfer of tokens to a recipient who has purchased offline, during the PartnerSale * @param _recipient address The address of the recipient of the tokens * @param _tokens uint256 The number of tokens purchased by the recipient * @return success bool Returns true if executed successfully */ function offlineTransaction (address _recipient, uint256 _tokens) public onlyOwner returns (bool) { require(state == SaleState.PartnerSale); require(_tokens > 0); // Convert to a token with decimals uint256 tokens = _tokens * (uint256(10) ** decimals); purchasedTokens[_recipient] = purchasedTokens[_recipient].add(tokens); // Use original _token argument to increase the count of tokens purchased in the PartnerSale partnerSaleTokensPurchased = partnerSaleTokensPurchased.add(_tokens); // Finalize the PartnerSale if necessary if (partnerSaleTokensPurchased >= partnerSaleTokensAvailable) { state = SaleState.PartnerSaleFinalized; } LogTokenPurchase(msg.sender, _recipient, 0, tokens); return true; } /***** * @dev Allow updating the ETH USD exchange rate * @param rate uint256 the current ETH USD rate, multiplied by 1000 * @return bool Return true if the contract is in PartnerSale Period */ function updateEthRate (uint256 rate) public onlyOwner returns (bool) { require(rate >= 100000); ethRate = rate; return true; } /***** * @dev Allows the contract owner to add a new PartnerSale wallet, used to hold funds safely * Can only be performed in the Preparing state * @param _wallet address The address of the wallet * @return success bool Returns true if executed successfully */ function addPartnerSaleWallet (address _wallet) public onlyOwner returns (bool) { require(state < SaleState.PartnerSaleFinalized); require(_wallet != address(0)); partnerSaleWallets.push(_wallet); return true; } /***** * @dev Allows the contract owner to add a new PreSale wallet, used to hold funds safely * Can not be performed in the PreSale state * @param _wallet address The address of the wallet * @return success bool Returns true if executed successfully */ function addPreSaleWallet (address _wallet) public onlyOwner returns (bool) { require(state != SaleState.PreSale); require(_wallet != address(0)); preSaleWallets.push(_wallet); return true; } /***** * @dev Allows the contract owner to add a new PublicSale wallet, used to hold funds safely * Can not be performed in the PublicSale state * @param _wallet address The address of the wallet * @return success bool Returns true if executed successfully */ function addPublicSaleWallet (address _wallet) public onlyOwner returns (bool) { require(state != SaleState.PublicSale); require(_wallet != address(0)); publicSaleWallets.push(_wallet); return true; } /***** * @dev Calculates the number of tokens that can be bought for the amount of Wei transferred * @param _amount uint256 The amount of money invested by the investor * @return tokens uint256 The number of tokens purchased for the amount invested */ function calculateTokens (uint256 _amount) public returns (uint256 tokens) { if (isStatePartnerSale()) { tokens = _amount * ethRate / partnerSaleTokenPrice; } else if (isStatePreSale()) { tokens = _amount * ethRate / preSaleTokenPrice; } else if (isStatePublicSale()) { tokens = _amount * ethRate / publicSaleTokenPrice; } else { tokens = 0; } return tokens; } /***** * @dev Called by the owner of the contract to open the Partner/Pre/Crowd Sale periods */ function setPhase (uint256 phase) public onlyOwner { state = SaleState(uint(phase)); } /***** * @dev Called by the owner of the contract to start the Partner Sale * @param rate uint256 the current ETH USD rate, multiplied by 1000 */ function startPartnerSale (uint256 rate) public onlyOwner { state = SaleState.PartnerSale; updateEthRate(rate); } /***** * @dev Called by the owner of the contract to start the Pre Sale * @param rate uint256 the current ETH USD rate, multiplied by 1000 */ function startPreSale (uint256 rate) public onlyOwner { state = SaleState.PreSale; updateEthRate(rate); } /***** * @dev Called by the owner of the contract to start the Public Sale * @param rate uint256 the current ETH USD rate, multiplied by 1000 */ function startPublicSale (uint256 rate) public onlyOwner { state = SaleState.PublicSale; updateEthRate(rate); } /***** * @dev Called by the owner of the contract to close the Partner Sale */ function finalizePartnerSale () public onlyOwner { require(state == SaleState.PartnerSale); state = SaleState.PartnerSaleFinalized; } /***** * @dev Called by the owner of the contract to close the Pre Sale */ function finalizePreSale () public onlyOwner { require(state == SaleState.PreSale); state = SaleState.PreSaleFinalized; } /***** * @dev Called by the owner of the contract to close the Public Sale */ function finalizePublicSale () public onlyOwner { require(state == SaleState.PublicSale); state = SaleState.PublicSaleFinalized; } /***** * @dev Called by the owner of the contract to finalize the ICO * and redistribute funds and unsold tokens */ function finalizeIco () public onlyOwner { require(state == SaleState.PublicSaleFinalized); state = SaleState.Success; // 2.5% of total goes to DADI ecosystem distribute(ecosystemWallet, ecosystemPercentOfTotal); // 2.5% of total goes to DADI+ operations distribute(operationsWallet, operationsPercentOfTotal); // 5% of total goes to referral programme distribute(referralProgrammeWallet, referralPercentOfTotal); // 20% of total goes to the founding team wallets distributeFoundingTeamTokens(foundingTeamWallets); // redistribute unsold tokens to DADI ecosystem uint256 remainingPreSaleTokens = getPreSaleTokensAvailable(); preSaleTokensAvailable = 0; uint256 remainingPublicSaleTokens = getPublicSaleTokensAvailable(); publicSaleTokensAvailable = 0; // we need to represent the tokens with included decimals // `2640 ** (10 ^ 18)` not `2640` if (remainingPreSaleTokens > 0) { remainingPreSaleTokens = remainingPreSaleTokens * (uint256(10) ** decimals); balances[owner] = balances[owner].sub(remainingPreSaleTokens); balances[ecosystemWallet] = balances[ecosystemWallet].add(remainingPreSaleTokens); Transfer(0, ecosystemWallet, remainingPreSaleTokens); } if (remainingPublicSaleTokens > 0) { remainingPublicSaleTokens = remainingPublicSaleTokens * (uint256(10) ** decimals); balances[owner] = balances[owner].sub(remainingPublicSaleTokens); balances[ecosystemWallet] = balances[ecosystemWallet].add(remainingPublicSaleTokens); Transfer(0, ecosystemWallet, remainingPublicSaleTokens); } // Transfer ETH to the funding wallet. if (!fundsWallet.send(this.balance)) { revert(); } } /***** * @dev Called by the owner of the contract to close the ICO * and unsold tokens to the ecosystem wallet. No more tokens * may be claimed */ function closeIco () public onlyOwner { state = SaleState.Closed; } /***** * @dev Allow investors to claim their tokens after the ICO is finalized & successful * @return bool Return true, if executed successfully */ function claimTokens () public returns (bool) { require(state == SaleState.Success); // get the tokens available for the sender uint256 tokens = purchasedTokens[msg.sender]; require(tokens > 0); purchasedTokens[msg.sender] = 0; balances[owner] = balances[owner].sub(tokens); balances[msg.sender] = balances[msg.sender].add(tokens); LogClaimTokens(msg.sender, tokens); Transfer(owner, msg.sender, tokens); return true; } /***** * @dev Allow investors to take their money back after a failure in the ICO * @param _recipient address The caller of the function who is looking for refund * @return bool Return true, if executed successfully */ function refund (address _recipient) public onlyOwner returns (bool) { require(state == SaleState.Refunding); uint256 value = partnerSaleWei[_recipient]; require(value > 0); partnerSaleWei[_recipient] = 0; if(!_recipient.send(value)) { partnerSaleWei[_recipient] = value; LogRefundFailed(_recipient, value); } LogRefundProcessed(_recipient, value); return true; } /***** * @dev Allows owner to withdraw funds from the contract balance for marketing purposes * @param _address address The recipient address for the ether * @return bool Return true, if executed successfully */ function withdrawFunds (address _address, uint256 _amount) public onlyOwner { _address.transfer(_amount); } /***** * @dev Generates a random number from 1 to max based on the last block hash * @param max uint the maximum value * @return a random number */ function getRandom(uint max) public constant returns (uint randomNumber) { return (uint(sha3(block.blockhash(block.number - 1))) % max) + 1; } /***** * @dev Called by the owner of the contract to set the state to Refunding */ function setRefunding () public onlyOwner { require(state == SaleState.PartnerSaleFinalized); state = SaleState.Refunding; } /***** * @dev Get the overall success state of the ICO * @return bool whether the state is successful, or not */ function isSuccessful () public constant returns (bool) { return state == SaleState.Success; } /***** * @dev Get the amount of PreSale tokens left for purchase * @return uint256 the count of tokens available */ function getPreSaleTokensAvailable () public constant returns (uint256) { if (preSaleTokensAvailable == 0) { return 0; } return preSaleTokensAvailable - preSaleTokensPurchased; } /***** * @dev Get the amount of PublicSale tokens left for purchase * @return uint256 the count of tokens available */ function getPublicSaleTokensAvailable () public constant returns (uint256) { if (publicSaleTokensAvailable == 0) { return 0; } return publicSaleTokensAvailable - publicSaleTokensPurchased; } /***** * @dev Get the total count of tokens purchased in all the Sale periods * @return uint256 the count of tokens purchased */ function getTokensPurchased () public constant returns (uint256) { return partnerSaleTokensPurchased + preSaleTokensPurchased + publicSaleTokensPurchased; } /***** * @dev Get the total amount raised in the PreSale and PublicSale periods * @return uint256 the amount raised, in Wei */ function getTotalRaised () public constant returns (uint256) { return preSaleRaised + publicSaleRaised; } /***** * @dev Get the balance sent to the contract * @return uint256 the amount sent to this contract, in Wei */ function getBalance () public constant returns (uint256) { return this.balance; } /***** * @dev Get the balance of the funds wallet used to transfer the final balance * @return uint256 the amount sent to the funds wallet at the end of the ICO, in Wei */ function getFundsWalletBalance () public constant onlyOwner returns (uint256) { return fundsWallet.balance; } /***** * @dev Get the count of unique investors * @return uint256 the total number of unique investors */ function getInvestorCount () public constant returns (uint256) { return investorCount; } /***** * @dev Send ether to the fund collection wallets */ function forwardFunds (uint256 _value) internal { // if (isStatePartnerSale()) { // // move funds to a partnerSaleWallet // if (partnerSaleWallets.length > 0) { // // Transfer ETH to a random wallet // uint accountNumber = getRandom(partnerSaleWallets.length) - 1; // address account = partnerSaleWallets[accountNumber]; // account.transfer(_value); // LogFundTransfer(account, _value); // } // } uint accountNumber; address account; if (isStatePreSale()) { // move funds to a preSaleWallet if (preSaleWallets.length > 0) { // Transfer ETH to a random wallet accountNumber = getRandom(preSaleWallets.length) - 1; account = preSaleWallets[accountNumber]; account.transfer(_value); LogFundTransfer(account, _value); } } else if (isStatePublicSale()) { // move funds to a publicSaleWallet if (publicSaleWallets.length > 0) { // Transfer ETH to a random wallet accountNumber = getRandom(publicSaleWallets.length) - 1; account = publicSaleWallets[accountNumber]; account.transfer(_value); LogFundTransfer(account, _value); } } } /***** * @dev Internal function to execute the token transfer to the recipient * In the PartnerSale period, token balances are stored in a separate mapping, to * await the PartnerSaleFinalized state, when investors may call claimTokens * @param _recipient address The address of the recipient of the tokens * @param _value uint256 The amount invested by the recipient * @return success bool Returns true if executed successfully */ function buyTokens (address _recipient, uint256 _value) internal returns (bool) { uint256 boughtTokens = calculateTokens(_value); require(boughtTokens != 0); if (isStatePartnerSale()) { // assign tokens to separate mapping purchasedTokens[_recipient] = purchasedTokens[_recipient].add(boughtTokens); partnerSaleWei[_recipient] = partnerSaleWei[_recipient].add(_value); } else { // increment the unique investor count if (purchasedTokens[_recipient] == 0) { investorCount++; } // assign tokens to separate mapping, that is not "balances" purchasedTokens[_recipient] = purchasedTokens[_recipient].add(boughtTokens); } LogTokenPurchase(msg.sender, _recipient, _value, boughtTokens); forwardFunds(_value); updateSaleParameters(_value, boughtTokens); return true; } /***** * @dev Internal function to modify parameters based on tokens bought * @param _value uint256 The amount invested in exchange for the tokens * @param _tokens uint256 The number of tokens purchased * @return success bool Returns true if executed successfully */ function updateSaleParameters (uint256 _value, uint256 _tokens) internal returns (bool) { // we need to represent the integer value of tokens here // tokensPurchased = `2640`, not `2640 ** (10 ^ 18)` uint256 tokens = _tokens / (uint256(10) ** decimals); if (isStatePartnerSale()) { partnerSaleTokensPurchased = partnerSaleTokensPurchased.add(tokens); // No PartnerSale tokens remaining if (partnerSaleTokensPurchased >= partnerSaleTokensAvailable) { state = SaleState.PartnerSaleFinalized; } } else if (isStatePreSale()) { preSaleTokensPurchased = preSaleTokensPurchased.add(tokens); preSaleRaised = preSaleRaised.add(_value); // No PreSale tokens remaining if (preSaleTokensPurchased >= preSaleTokensAvailable) { state = SaleState.PreSaleFinalized; } } else if (isStatePublicSale()) { publicSaleTokensPurchased = publicSaleTokensPurchased.add(tokens); publicSaleRaised = publicSaleRaised.add(_value); // No PublicSale tokens remaining if (publicSaleTokensPurchased >= publicSaleTokensAvailable) { state = SaleState.PublicSaleFinalized; } } } /***** * @dev Internal calculation for the amount of Wei the specified tokens are worth * @param _tokens uint256 The number of tokens purchased by the investor * @return amount uint256 The amount the tokens are worth */ function calculateValueFromTokens (uint256 _tokens) internal returns (uint256) { uint256 amount = _tokens.div(ethRate.div(partnerSaleTokenPrice)); return amount; } /***** * @dev Private function to distribute tokens evenly amongst the founding team wallet addresses * @param _recipients address[] An array of founding team wallet addresses * @return success bool Returns true if executed successfully */ function distributeFoundingTeamTokens (address[] _recipients) private returns (bool) { // determine the split between wallets // to arrive at a valid percentage we start the percentage the founding team has // available, which is 20% of the total supply. The percentage to distribute then is the // total percentage divided by the number of founding team wallets (likely 4). uint percentage = foundersPercentOfTotal / _recipients.length; for (uint i = 0; i < _recipients.length; i++) { distribute(_recipients[i], percentage); } } /***** * @dev Private function to move tokens to the specified wallet address * @param _recipient address The address of the wallet to move tokens to * @param percentage uint The percentage of the total supply of tokens to move * @return success bool Returns true if executed successfully */ function distribute (address _recipient, uint percentage) private returns (bool) { uint256 tokens = totalSupply / (hundredPercent / percentage); balances[owner] = balances[owner].sub(tokens); balances[_recipient] = balances[_recipient].add(tokens); Transfer(0, _recipient, tokens); } /***** * @dev Check the PartnerSale state of the contract * @return bool Return true if the contract is in the PartnerSale state */ function isStatePartnerSale () private constant returns (bool) { return state == SaleState.PartnerSale; } /***** * @dev Check the PreSale state of the contract * @return bool Return true if the contract is in the PreSale state */ function isStatePreSale () private constant returns (bool) { return state == SaleState.PreSale; } /***** * @dev Check the PublicSale state of the contract * @return bool Return true if the contract is in the PublicSale state */ function isStatePublicSale () private constant returns (bool) { return state == SaleState.PublicSale; } }
Get the overall success state of the ICO return bool whether the state is successful, or not/
function isSuccessful () public constant returns (bool) { return state == SaleState.Success; }
6,380,356
./partial_match/1/0xC88DF5326FcCeD20Cb1a3a441DF4F955f4AA23AE/sources/ICOCycle.sol
INTERNALcounter +=1;
function executeVerdict(uint _disputeId, bool _verdictForInvestor) internal { disputes[_disputeId].pending = false; uint milestoneDispute = disputes[_disputeId].milestone; ICOCycle icoRound = ICOCycle(disputes[_disputeId].icoRoundAddress); icoRound.verdictExecuted(disputes[_disputeId].investorAddress,_verdictForInvestor,milestoneDispute); }
15,636,259
./full_match/1/0x51c537d5a4305281F6354369Af074f2301236b35/sources/presale_dep.sol
Instantly burns your Token and sends you proportional backing.
function liquifyForMain(uint256 amt) external{
8,419,013
// SPDX-License-Identifier: MIT pragma solidity >=0.5.0; import '@openzeppelin/contracts/math/SafeMath.sol'; import '../interfaces/IGoSwapPair.sol'; import '../interfaces/IGoSwapFactory.sol'; import '../interfaces/IGoSwapCompany.sol'; /** * @title GoSwap库合约 */ library GoSwapLibrary { using SafeMath for uint256; /** * @dev 排序token地址 * @notice 返回排序的令牌地址,用于处理按此顺序排序的对中的返回值 * @param tokenA TokenA * @param tokenB TokenB * @return token0 Token0 * @return token1 Token1 */ function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { //确认tokenA不等于tokenB require(tokenA != tokenB, 'GoSwapLibrary: IDENTICAL_ADDRESSES'); //排序token地址 (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); //确认token地址不等于0地址 require(token0 != address(0), 'GoSwapLibrary: ZERO_ADDRESS'); } /** * @dev 获取pair合约地址 * @notice 计算一对的CREATE2地址,而无需进行任何外部调用 * @param company 配对寻找工厂地址 * @param tokenA TokenA * @param tokenB TokenB * @return pair pair合约地址 */ function pairFor( address company, address tokenA, address tokenB ) internal pure returns (address pair) { // 通过配对寻找工厂合约 address factory = IGoSwapCompany(company).pairForFactory(tokenA, tokenB); //排序token地址 (address token0, address token1) = sortTokens(tokenA, tokenB); // 获取pairCodeHash bytes32 pairCodeHash = IGoSwapFactory(factory).pairCodeHash(); //根据排序的token地址计算create2的pair地址 pair = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash // init code hash ) ) ) ); } /** * @dev 获取不含虚流动性的储备量 * @notice 提取并排序一对的储备金 * @param company 配对寻找工厂地址 * @param tokenA TokenA * @param tokenB TokenB * @return reserveA 储备量A * @return reserveB 储备量B * @return fee 手续费 */ // fetches and sorts the reserves and fee for a pair function getReservesWithoutDummy( address company, address tokenA, address tokenB ) internal view returns ( uint256 reserveA, uint256 reserveB, uint8 fee ) { //排序token地址 (address token0, ) = sortTokens(tokenA, tokenB); // 实例化配对合约 IGoSwapPair pair = IGoSwapPair(pairFor(company, tokenA, tokenB)); // 获取储备量 (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); // 获取虚流动性 (uint256 dummy0, uint256 dummy1) = pair.getDummy(); // 储备量0 - 虚流动性0 reserve0 -= dummy0; // 储备量1 - 虚流动性1 reserve1 -= dummy1; // 排序token (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); // 返回手续费 fee = pair.fee(); } /** * @dev 获取储备量 * @notice 提取并排序一对的储备金 * @param company 配对寻找工厂地址 * @param tokenA TokenA * @param tokenB TokenB * @return reserveA 储备量A * @return reserveB 储备量B * @return fee 手续费 */ function getReserves( address company, address tokenA, address tokenB ) internal view returns ( uint256 reserveA, uint256 reserveB, uint8 fee ) { //排序token地址 (address token0, ) = sortTokens(tokenA, tokenB); //通过排序后的token地址和工厂合约地址获取到pair合约地址,并从pair合约中获取储备量0,1 (uint256 reserve0, uint256 reserve1, ) = IGoSwapPair(pairFor(company, tokenA, tokenB)).getReserves(); //根据输入的token顺序返回储备量 (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); //获取配对合约中设置的手续费比例 fee = IGoSwapPair(pairFor(company, tokenA, tokenB)).fee(); } /** * @dev 对价计算 * @notice 给定一定数量的资产和货币对储备金,则返回等值的其他资产 * @param amountA 数额A * @param reserveA 储备量A * @param reserveB 储备量B * @return amountB 数额B */ function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { //确认数额A>0 require(amountA > 0, 'GoSwapLibrary: INSUFFICIENT_AMOUNT'); //确认储备量A,B大于0 require(reserveA > 0 && reserveB > 0, 'GoSwapLibrary: INSUFFICIENT_LIQUIDITY'); //数额B = 数额A * 储备量B / 储备量A amountB = amountA.mul(reserveB) / reserveA; } /** * @dev 获取单个输出数额 * @notice 给定一项资产的输入量和配对的储备,返回另一项资产的最大输出量 * @param amountIn 输入数额 * @param reserveIn 储备量In * @param reserveOut 储备量Out * @param fee 手续费比例 * @return amountOut 输出数额 */ function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut, uint8 fee ) internal pure returns (uint256 amountOut) { //确认输入数额大于0 require(amountIn > 0, 'GoSwapLibrary: INSUFFICIENT_INPUT_AMOUNT'); //确认储备量In和储备量Out大于0 require(reserveIn > 0 && reserveOut > 0, 'GoSwapLibrary: INSUFFICIENT_LIQUIDITY'); //税后输入数额 = 输入数额 * (1000-fee) uint256 amountInWithFee = amountIn.mul(1000 - fee); //分子 = 税后输入数额 * 储备量Out uint256 numerator = amountInWithFee.mul(reserveOut); //分母 = 储备量In * 1000 + 税后输入数额 uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); //输出数额 = 分子 / 分母 amountOut = numerator / denominator; } /** * @dev 获取单个输出数额 * @notice 给定一项资产的输出量和对储备,返回其他资产的所需输入量 * @param amountOut 输出数额 * @param reserveIn 储备量In * @param reserveOut 储备量Out * @param fee 手续费比例 * @return amountIn 输入数额 */ function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut, uint8 fee ) internal pure returns (uint256 amountIn) { //确认输出数额大于0 require(amountOut > 0, 'GoSwapLibrary: INSUFFICIENT_OUTPUT_AMOUNT'); //确认储备量In和储备量Out大于0 require(reserveIn > 0 && reserveOut > 0, 'GoSwapLibrary: INSUFFICIENT_LIQUIDITY'); //分子 = 储备量In * 储备量Out * 1000 uint256 numerator = reserveIn.mul(amountOut).mul(1000); //分母 = 储备量Out - 输出数额 * (1000-fee) uint256 denominator = reserveOut.sub(amountOut).mul(1000 - fee); //输入数额 = (分子 / 分母) + 1 amountIn = (numerator / denominator).add(1); } /** * @dev 获取输出数额 * @notice 对任意数量的对执行链接的getAmountOut计算 * @param company 配对寻找工厂合约地址 * @param amountIn 输入数额 * @param path 路径数组 * @return amounts 数额数组 */ function getAmountsOut( address company, uint256 amountIn, address[] memory path ) internal view returns (uint256[] memory amounts) { //确认路径数组长度大于2 require(path.length >= 2, 'GoSwapLibrary: INVALID_PATH'); //初始化数额数组 amounts = new uint256[](path.length); //数额数组[0] = 输入数额 amounts[0] = amountIn; //遍历路径数组,path长度-1 for (uint256 i; i < path.length - 1; i++) { //(储备量In,储备量Out,手续费比例) = 获取储备(当前路径地址,下一个路径地址) (uint256 reserveIn, uint256 reserveOut, uint8 fee) = getReserves(company, path[i], path[i + 1]); //下一个数额 = 获取输出数额(当前数额,储备量In,储备量Out) amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut, fee); } } /** * @dev 获取输出数额 * @notice 对任意数量的对执行链接的getAmountIn计算 * @param company 公司合约地址 * @param amountOut 输出数额 * @param path 路径数组 * @return amounts 数额数组 */ function getAmountsIn( address company, uint256 amountOut, address[] memory path ) internal view returns (uint256[] memory amounts) { //确认路径数组长度大于2 require(path.length >= 2, 'GoSwapLibrary: INVALID_PATH'); //初始化数额数组 amounts = new uint256[](path.length); //数额数组最后一个元素 = 输出数额 amounts[amounts.length - 1] = amountOut; //从倒数第二个元素倒叙遍历路径数组 for (uint256 i = path.length - 1; i > 0; i--) { //(储备量In,储备量Out,手续费比例) = 获取储备(上一个路径地址,当前路径地址) (uint256 reserveIn, uint256 reserveOut, uint8 fee) = getReserves(company, path[i - 1], path[i]); //上一个数额 = 获取输入数额(当前数额,储备量In,储备量Out) amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut, fee); } } }
获取单个输出数额 给定一项资产的输出量和对储备,返回其他资产的所需输入量 amountOut 输出数额 reserveIn 储备量In reserveOut 储备量Out fee 手续费比例 return amountIn 输入数额/确认输出数额大于0确认储备量In和储备量Out大于0分子 = 储备量In 储备量Out 1000分母 = 储备量Out - 输出数额 (1000-fee)输入数额 = (分子 / 分母) + 1
function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut, uint8 fee ) internal pure returns (uint256 amountIn) { require(amountOut > 0, 'GoSwapLibrary: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'GoSwapLibrary: INSUFFICIENT_LIQUIDITY'); uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(1000 - fee); amountIn = (numerator / denominator).add(1); }
6,411,643
pragma solidity 0.4.23; import "Ownable.sol"; import "ICOEngineInterface.sol"; import "KYCBase.sol"; import "./ORSToken.sol"; /// @title ORSTokenSale /// @author Autogenerated from a Dia UML diagram contract ORSTokenSale is Ownable, ICOEngineInterface, KYCBase { uint public PRESALE_CAP = 222247844e18; uint public MAILSALE_CAP = 281945791e18; uint public BONUS_CAP = 60266365e18; uint public COMPANY_SHARE = 127206667e18; uint public TEAM_SHARE = 83333333e18; uint public ADVISORS_SHARE = 58333333e18; uint public mainsaleRemaining = MAINSALE_CAP; uint public presaleRemaining = PRESALE_CAP; uint public bonusRemaining = BONUS_CAP; address public companyWallet; address public advisorsWallet; address public bountyWallet; ORSToken public token; uint public rate; uint public openingTime; uint public closingTime; address public wallet; address public eidooSigner; bool public isFinalized = false; /// @dev Log entry on rate changed /// @param newRate A positive number event RateChanged(uint newRate); /// @dev Log entry on token purchased /// @param buyer An Ethereum address /// @param value A positive number /// @param tokens A positive number event TokenPurchased(address buyer, uint value, uint tokens); /// @dev Log entry on buyer refunded /// @param buyer An Ethereum address /// @param value A positive number event BuyerRefunded(address buyer, uint value); /// @dev Log entry on finalized event Finalized(); /// @dev Constructor /// @param _token An ORSToken /// @param _rate A positive number /// @param _openingTime A positive number /// @param _closingTime A positive number /// @param _wallet A positive number /// @param _companyWallet An Ethereum address /// @param _advisorsWallet An Ethereum address /// @param _bountyWallet An Ethereum address /// @param _kycSigners A list where each entry is an Ethereum address constructor(ORSToken _token, uint _rate, uint _openingTime, uint _closingTime, uint _wallet, address _companyWallet, address _advisorsWallet, address _bountyWallet, address[] _kycSigners) public KYCBase(_kycSigners) { require(IMPLEMENTATION); } /// @dev Set rate /// @param _price A positive number function setRate(uint _price) public onlyOwner { require(IMPLEMENTATION); } /// @dev Distribute presale /// @param _investors A list where each entry is an Ethereum address /// @param _tokens A list where each entry is a positive number function distributePresale(address[] _investors, uint[] _tokens) public onlyOwner { require(IMPLEMENTATION); } /// @dev Finalize function finalize() public onlyOwner { require(IMPLEMENTATION); } /// @dev Started /// @return True or false function started() public view returns (bool) { require(IMPLEMENTATION); } /// @dev Ended /// @return True or false function ended() public view returns (bool) { require(IMPLEMENTATION); } /// @dev Start time /// @return A positive number function startTime() public view returns (uint) { require(IMPLEMENTATION); } /// @dev End time /// @return A positive number function endTime() public view returns (uint) { require(IMPLEMENTATION); } /// @dev Total tokens /// @return A positive number function totalTokens() public view returns (uint) { require(IMPLEMENTATION); } /// @dev Remaining tokens /// @return A positive number function remainingTokens() public view returns (uint) { require(IMPLEMENTATION); } /// @dev Price /// @return A positive number function price() public view returns (uint) { require(IMPLEMENTATION); } /// @dev Release tokens to /// @param buyer An Ethereum address /// @param signer An Ethereum address /// @return True or false function releaseTokensTo(address buyer, address signer) internal returns (bool) { require(IMPLEMENTATION); } }
Started return True or false
function started() public view returns (bool) { require(IMPLEMENTATION); }
994,659
// Dependency file: @openzeppelin/contracts-ethereum-package/contracts/math/Math.sol // pragma solidity ^0.6.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Dependency file: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol // pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Dependency file: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol // pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * // importANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Dependency file: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol // pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [// importANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * // importANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // Dependency file: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts-ethereum-package/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 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"); } } } // Dependency file: @openzeppelin/contracts-ethereum-package/contracts/Initializable.sol // pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // Dependency file: @openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuardUpgradeSafe is Initializable { bool private _notEntered; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } uint256[49] private __gap; } // Dependency file: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // Dependency file: @openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol"; // import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Triggers stopped state. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // Dependency file: @openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol"; // import "@openzeppelin/contracts-ethereum-package/contracts/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. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // Dependency file: contracts/BannedContractList.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.6.0; // import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; /* Approve and Ban Contracts to interact with pools. (All contracts are approved by default, unless banned) */ contract BannedContractList is Initializable, OwnableUpgradeSafe { mapping(address => bool) banned; function initialize() public initializer { __Ownable_init(); } function isApproved(address toCheck) external view returns (bool) { return !banned[toCheck]; } function isBanned(address toCheck) external view returns (bool) { return banned[toCheck]; } function approveContract(address toApprove) external onlyOwner { banned[toApprove] = false; } function banContract(address toBan) external onlyOwner { banned[toBan] = true; } } // Dependency file: contracts/Defensible.sol // pragma solidity ^0.6.0; // import "contracts/BannedContractList.sol"; /* Prevent smart contracts from calling functions unless approved by the specified whitelist. */ contract Defensible { // Only smart contracts will be affected by this modifier modifier defend(BannedContractList bannedContractList) { require( (msg.sender == tx.origin) || bannedContractList.isApproved(msg.sender), "This smart contract has not been approved" ); _; } } // Dependency file: contracts/interfaces/IMushroomFactory.sol // pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; interface IMushroomFactory { function costPerMushroom() external returns (uint256); function getRemainingMintableForMySpecies(uint256 numMushrooms) external view returns (uint256); function growMushrooms(address recipient, uint256 numMushrooms) external; } // Dependency file: contracts/interfaces/IMission.sol // pragma solidity ^0.6.0; interface IMission { function sendSpores(address recipient, uint256 amount) external; function approvePool(address pool) external; function revokePool(address pool) external; } // Dependency file: contracts/interfaces/IMiniMe.sol // pragma solidity ^0.6.0; interface IMiniMe { /* ========== STANDARD ERC20 ========== */ function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /* ========== MINIME EXTENSIONS ========== */ function balanceOfAt(address account, uint256 blockNumber) external view returns (uint256); function totalSupplyAt(uint256 blockNumber) external view returns (uint256); } // Dependency file: contracts/interfaces/ISporeToken.sol // pragma solidity ^0.6.0; interface ISporeToken { /* ========== STANDARD ERC20 ========== */ function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /* ========== EXTENSIONS ========== */ function burn(uint256 amount) external; function mint(address to, uint256 amount) external; function addInitialLiquidityTransferRights(address account) external; function enableTransfers() external; function addMinter(address account) external; function removeMinter(address account) external; } // Root file: contracts/SporePool.sol pragma solidity ^0.6.0; // pragma experimental ABIEncoderV2; // import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol"; // import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; // import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol"; // import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol"; // import "@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol"; // import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; // import "contracts/Defensible.sol"; // import "contracts/interfaces/IMushroomFactory.sol"; // import "contracts/interfaces/IMission.sol"; // import "contracts/interfaces/IMiniMe.sol"; // import "contracts/interfaces/ISporeToken.sol"; // import "contracts/BannedContractList.sol"; /* Staking can be paused by the owner (withdrawing & harvesting cannot be paused) The mushroomFactory must be set by the owner before mushrooms can be harvested (optionally) It and can be modified, to use new mushroom spawning logic The rateVote contract has control over the spore emission rate. It can be modified, to change the voting logic around rate changes. */ contract SporePool is OwnableUpgradeSafe, ReentrancyGuardUpgradeSafe, PausableUpgradeSafe, Defensible { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ ISporeToken public sporeToken; IERC20 public stakingToken; uint256 public sporesPerSecond = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; uint256 public constant MAX_PERCENTAGE = 100; uint256 public devRewardPercentage; address public devRewardAddress; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 internal _totalSupply; mapping(address => uint256) internal _balances; IMushroomFactory public mushroomFactory; IMission public mission; BannedContractList public bannedContractList; uint256 public stakingEnabledTime; address public rateVote; IMiniMe public enokiToken; address public enokiDaoAgent; /* ========== CONSTRUCTOR ========== */ function initialize( address _sporeToken, address _stakingToken, address _mission, address _bannedContractList, address _devRewardAddress, address _enokiDaoAgent, uint256[3] memory uintParams ) public virtual initializer { __Context_init_unchained(); __Pausable_init_unchained(); __ReentrancyGuard_init_unchained(); __Ownable_init_unchained(); sporeToken = ISporeToken(_sporeToken); stakingToken = IERC20(_stakingToken); mission = IMission(_mission); bannedContractList = BannedContractList(_bannedContractList); /* [0] uint256 _devRewardPercentage, [1] uint256 stakingEnabledTime_, [2] uint256 initialRewardRate_, */ devRewardPercentage = uintParams[0]; devRewardAddress = _devRewardAddress; stakingEnabledTime = uintParams[1]; sporesPerSecond = uintParams[2]; enokiDaoAgent = _enokiDaoAgent; emit SporeRateChange(sporesPerSecond); } /* ========== VIEWS ========== */ function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address account) external view returns (uint256) { return _balances[account]; } // Rewards are turned off at the mission level function lastTimeRewardApplicable() public view returns (uint256) { return block.timestamp; } function rewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } // Time difference * sporesPerSecond return rewardPerTokenStored.add(lastTimeRewardApplicable().sub(lastUpdateTime).mul(sporesPerSecond).mul(1e18).div(_totalSupply)); } function earned(address account) public view returns (uint256) { return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]); } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount) external virtual nonReentrant defend(bannedContractList) whenNotPaused updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); require(now > stakingEnabledTime, "Cannot stake before staking enabled"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } // Withdrawing does not harvest, the rewards must be harvested separately function withdraw(uint256 amount) public virtual updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function harvest(uint256 mushroomsToGrow) public nonReentrant updateReward(msg.sender) returns ( uint256 toDev, uint256 toDao, uint256 remainingReward ) { uint256 reward = rewards[msg.sender]; if (reward > 0) { remainingReward = reward; toDev = 0; toDao = 0; rewards[msg.sender] = 0; // Burn some rewards for mushrooms if desired if (mushroomsToGrow > 0) { uint256 totalCost = mushroomFactory.costPerMushroom().mul(mushroomsToGrow); require(reward >= totalCost, "Not enough rewards to grow the number of mushrooms specified"); toDev = totalCost.mul(devRewardPercentage).div(MAX_PERCENTAGE); if (toDev > 0) { mission.sendSpores(devRewardAddress, toDev); emit DevRewardPaid(devRewardAddress, toDev); } toDao = totalCost.sub(toDev); mission.sendSpores(enokiDaoAgent, toDao); emit DaoRewardPaid(enokiDaoAgent, toDao); remainingReward = reward.sub(totalCost); mushroomFactory.growMushrooms(msg.sender, mushroomsToGrow); emit MushroomsGrown(msg.sender, mushroomsToGrow); } if (remainingReward > 0) { mission.sendSpores(msg.sender, remainingReward); emit RewardPaid(msg.sender, remainingReward); } } } // Withdraw, forfietting all rewards function emergencyWithdraw() external nonReentrant { withdraw(_balances[msg.sender]); } /* ========== RESTRICTED FUNCTIONS ========== */ // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner { // Cannot recover the staking token or the rewards token require(tokenAddress != address(stakingToken) && tokenAddress != address(sporeToken), "Cannot withdraw the staking or rewards tokens"); //TODO: Add safeTransfer IERC20(tokenAddress).transfer(owner(), tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function setMushroomFactory(address mushroomFactory_) external onlyOwner { mushroomFactory = IMushroomFactory(mushroomFactory_); } function pauseStaking() external onlyOwner { _pause(); } function unpauseStaking() external onlyOwner { _unpause(); } function setRateVote(address _rateVote) external onlyOwner { rateVote = _rateVote; } function changeRate(uint256 percentage) external onlyRateVote { sporesPerSecond = sporesPerSecond.mul(percentage).div(MAX_PERCENTAGE); emit SporeRateChange(sporesPerSecond); } /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } modifier onlyRateVote() { require(msg.sender == rateVote, "onlyRateVote"); _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event DevRewardPaid(address indexed user, uint256 reward); event DaoRewardPaid(address indexed user, uint256 reward); event MushroomsGrown(address indexed user, uint256 number); event Recovered(address token, uint256 amount); event SporeRateChange(uint256 newRate); }
Withdraw, forfietting all rewards
function emergencyWithdraw() external nonReentrant { withdraw(_balances[msg.sender]); }
12,238,106
./full_match/43113/0x1a47Bae8d88f91A30d8BEd041eCC6bB76709B69F/sources/contracts/TokenPaymaster.sol
solhint-disable-next-line reason-string
function _verifyPaymasterData(GsnTypes.RelayRequest calldata relayRequest) internal virtual override view { require(relayRequest.relayData.paymasterData.length == 32, "paymasterData: invalid length for Uniswap v1 exchange address"); }
7,149,034
pragma solidity ^0.4.24; import "contracts/interface/ICouncil.sol"; import "contracts/interface/IReport.sol"; import "contracts/interface/IContent.sol"; import "contracts/interface/IDepositPool.sol"; import "contracts/utils/ExtendsOwnable.sol"; import "contracts/utils/ValidValue.sol"; import "contracts/utils/TimeLib.sol"; /** * @title Council contract * * @author Junghoon Seo - <[email protected]> */ contract Council is ExtendsOwnable, ValidValue, ICouncil { struct PictionValue { uint256 initialDeposit; uint256 reportRegistrationFee; uint256 depositReleaseDelay; bool fundAvailable; } struct PictionRate { uint256 cdRate; uint256 userPaybackRate; } struct PictionAddress { address userPaybackPool; address depositPool; address supporterPool; address pixelDistributor; address report; address contentsDistributor; } struct ManagerAddress { address contentsManager; address fundManager; address accountManager; } struct ApiAddress { address apiContents; address apiReport; address apiFund; } address token; PictionValue pictionValue; PictionRate pictionRate; PictionAddress pictionAddress; ManagerAddress managerAddress; ApiAddress apiAddress; mapping (address => bool) members; constructor( address _token) public validAddress(_token) { token = _token; members[msg.sender] = true; emit RegisterCouncil(msg.sender, _token); } function setMember(address _member, bool _allow) external onlyOwner { members[_member] = _allow; emit SetMember(_member, _allow); } function isMember(address _member) external view returns(bool allow_) { allow_ = members[_member]; } function initialValue( uint256 _initialDeposit, uint256 _reportRegistrationFee, uint256 _depositReleaseDelay, bool _fundAvailable) external onlyOwner validRange(_initialDeposit) validRange(_reportRegistrationFee) { pictionValue = PictionValue(_initialDeposit, _reportRegistrationFee, _depositReleaseDelay, _fundAvailable); emit InitialValue(_initialDeposit, _reportRegistrationFee, _depositReleaseDelay, _fundAvailable); } function initialRate( uint256 _cdRate, uint256 _userPaybackRate) external onlyOwner { pictionRate = PictionRate(_cdRate, _userPaybackRate); emit InitialRate(_cdRate, _userPaybackRate); } function initialPictionAddress( address _userPaybackPool, address _depositPool, address _supporterPool, address _pixelDistributor, address _report, address _contentsDistributor) external onlyOwner validAddress(_userPaybackPool) validAddress(_depositPool) validAddress(_supporterPool) validAddress(_pixelDistributor) validAddress(_report) validAddress(_contentsDistributor) { pictionAddress = PictionAddress(_userPaybackPool, _depositPool, _supporterPool, _pixelDistributor, _report, _contentsDistributor); emit InitialAddress(_userPaybackPool, _depositPool, _supporterPool, _pixelDistributor, _report, _contentsDistributor); } function initialManagerAddress( address _contentsManager, address _fundManager, address _accountManager) external onlyOwner validAddress(_contentsManager) validAddress(_fundManager) validAddress(_accountManager) { managerAddress = ManagerAddress(_contentsManager, _fundManager, _accountManager); emit InitialManagerAddress(_contentsManager, _fundManager, _accountManager); } function initialApiAddress( address _apiContents, address _apiReport, address _apiFund ) external onlyOwner validAddress(_apiContents) validAddress(_apiReport) validAddress(_apiFund) { apiAddress = ApiAddress(_apiContents, _apiReport, _apiFund); emit InitialApiAddress(_apiContents, _apiReport, _apiFund); } /** * @dev 위원회 등록된 전체 정보 조회 * @return address pxlAddress_ pxl token address * @return uint256[] pictionValue_ 상황 별 deposit token 수량 * @return uint256[] pictionRate_ 작품 판매시 분배 될 고정 비율 정보 * @return address[] pictionAddress_ piction network에서 사용되는 컨트랙트 주소 * @return address[] managerAddress_ 매니저 성격의 컨트랙트 주소 * @return address[] apiAddress_ piction network API 컨트랙트 주소 * @return bool fundAvailable_ piction network 투자 기능 사용 여부 */ function getPictionConfig() external view returns (address pxlAddress_, uint256[] pictionValue_, uint256[] pictionRate_, address[] pictionAddress_, address[] managerAddress_, address[] apiAddress_, bool fundAvailable_) { pictionValue_ = new uint256[](3); pictionRate_ = new uint256[](2); pictionAddress_ = new address[](5); managerAddress_ = new address[](3); apiAddress_ = new address[](3); pxlAddress_ = token; // 배열의 순서는 구조체 선언 순서 pictionValue_[0] = pictionValue.initialDeposit; pictionValue_[1] = pictionValue.reportRegistrationFee; pictionValue_[2] = pictionValue.depositReleaseDelay; pictionRate_[0] = pictionRate.cdRate; pictionRate_[1] = pictionRate.userPaybackRate; pictionAddress_[0] = pictionAddress.userPaybackPool; pictionAddress_[1] = pictionAddress.depositPool; pictionAddress_[2] = pictionAddress.pixelDistributor; pictionAddress_[3] = pictionAddress.report; pictionAddress_[4] = pictionAddress.contentsDistributor; managerAddress_[0] = managerAddress.contentsManager; managerAddress_[1] = managerAddress.fundManager; managerAddress_[2] = managerAddress.accountManager; apiAddress_[0] = apiAddress.apiContents; apiAddress_[1] = apiAddress.apiReport; apiAddress_[2] = apiAddress.apiFund; fundAvailable_ = pictionValue.fundAvailable; } enum ReportDisposalType {DEFAULT, CONTENT_BLOCK, WARNS_WRITER, PASS, DUPLICATE, WRONG_REPORT} /** * @dev 신고 목록을 처리함 * @param _index Report 인덱스 값 * @param _content 작품의 주소 * @param _reporter 신고자의 주소 * @param _type 처리 타입 : 1 작품 차단, 2 작가 경고, 3 신고 무효, 4 중복 신고, 5 잘못된 신고 * @param _description 처리내역 */ function reportDisposal(uint256 _index, address _content, address _reporter, uint256 _type, string _description) external returns (uint256 deductionAmount_) { require(apiAddress.apiReport == msg.sender, "msg sender is not apiReport"); if ((_type == uint256(ReportDisposalType.CONTENT_BLOCK)) || (_type == uint256(ReportDisposalType.WARNS_WRITER))) { bool contentBlock; (deductionAmount_, contentBlock) = IDepositPool(pictionAddress.depositPool).reportReward(_content, _reporter, _type, _description); if (contentBlock) { contentBlocking(_content, true); } } else if (_type == uint256(ReportDisposalType.WRONG_REPORT)) { deductionAmount_ = IReport(pictionAddress.report).deduction(_reporter); } IReport(pictionAddress.report).completeReport(_index, _type, deductionAmount_); emit ReportDisposal(TimeLib.currentTime(), _index, _content, _reporter, _type, _description, deductionAmount_); } function contentBlocking(address _contentAddress, bool _isBlocked) public { require(apiAddress.apiReport == msg.sender || members[msg.sender], "Content blocking failed : access denied"); IContent(_contentAddress).setIsBlocked(_isBlocked); emit ContentBlocking(msg.sender, _contentAddress, _isBlocked); } function getToken() external view returns (address token_) { return token; } function getInitialDeposit() external view returns (uint256 initialDeposit_) { return pictionValue.initialDeposit; } function getReportRegistrationFee() view external returns (uint256 reportRegistrationFee_) { return pictionValue.reportRegistrationFee; } function getDepositReleaseDelay() external view returns (uint256 depositReleaseDelay_) { return pictionValue.depositReleaseDelay; } function getFundAvailable() external view returns (bool fundAvailable_) { return pictionValue.fundAvailable; } function getCdRate() external view returns (uint256 cdRate_) { return pictionRate.cdRate; } function getUserPaybackRate() external view returns (uint256 userPaybackRate_) { return pictionRate.userPaybackRate; } function getUserPaybackPool() external view returns (address userPaybackPool_) { return pictionAddress.userPaybackPool; } function getDepositPool() external view returns (address depositPool_) { return pictionAddress.depositPool; } function getSupporterPool() external view returns (address supporterPool_) { return pictionAddress.supporterPool; } function getContentsManager() external view returns (address contentsManager_) { return managerAddress.contentsManager; } function getFundManager() external view returns (address fundManager_) { return managerAddress.fundManager; } function getAccountManager() external view returns (address accountManager_) { return managerAddress.accountManager; } function getPixelDistributor() external view returns (address pixelDistributor_) { return pictionAddress.pixelDistributor; } function getReport() external view returns (address report_) { return pictionAddress.report; } function getContentsDistributor() external view returns (address contentsDistributor_) { return pictionAddress.contentsDistributor; } function getApiContents() external view returns (address apiContents_) { return apiAddress.apiContents; } function getApiReport() external view returns (address apiReport_) { return apiAddress.apiReport; } function getApiFund() external view returns (address apiFund_) { return apiAddress.apiFund; } }
위원회 등록된 전체 정보 조회 return address pxlAddress_ pxl token address return uint256[] pictionValue_ 상황 별 deposit token 수량 return uint256[] pictionRate_ 작품 판매시 분배 될 고정 비율 정보 return address[] pictionAddress_ piction network에서 사용되는 컨트랙트 주소 return address[] managerAddress_ 매니저 성격의 컨트랙트 주소 return address[] apiAddress_ piction network API 컨트랙트 주소 return bool fundAvailable_ piction network 투자 기능 사용 여부/ 배열의 순서는 구조체 선언 순서
function getPictionConfig() external view returns (address pxlAddress_, uint256[] pictionValue_, uint256[] pictionRate_, address[] pictionAddress_, address[] managerAddress_, address[] apiAddress_, bool fundAvailable_) { pictionValue_ = new uint256[](3); pictionRate_ = new uint256[](2); pictionAddress_ = new address[](5); managerAddress_ = new address[](3); apiAddress_ = new address[](3); pxlAddress_ = token; pictionValue_[0] = pictionValue.initialDeposit; pictionValue_[1] = pictionValue.reportRegistrationFee; pictionValue_[2] = pictionValue.depositReleaseDelay; pictionRate_[0] = pictionRate.cdRate; pictionRate_[1] = pictionRate.userPaybackRate; pictionAddress_[0] = pictionAddress.userPaybackPool; pictionAddress_[1] = pictionAddress.depositPool; pictionAddress_[2] = pictionAddress.pixelDistributor; pictionAddress_[3] = pictionAddress.report; pictionAddress_[4] = pictionAddress.contentsDistributor; managerAddress_[0] = managerAddress.contentsManager; managerAddress_[1] = managerAddress.fundManager; managerAddress_[2] = managerAddress.accountManager; apiAddress_[0] = apiAddress.apiContents; apiAddress_[1] = apiAddress.apiReport; apiAddress_[2] = apiAddress.apiFund; fundAvailable_ = pictionValue.fundAvailable; }
6,460,360
./full_match/5/0xBE030626Ff369F4dd8FE5c272EFfEDE7a5A08c69/sources/contracts/abstracts/ERC20Abstract.sol
Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address./
function increaseAllowance( address spender, uint256 addedValue ) public virtual returns (bool) { address owner = msg.sender; _approve(owner, spender, allowance(owner, spender) + addedValue); return true; }
1,882,335
pragma solidity 0.4.24; /** * @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; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner, "Not the 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), "Zero address received"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } interface IERC20 { function transfer(address _to, uint _value) external returns (bool success); function balanceOf(address _owner) external view returns (uint256 balance); } contract Airdrop is Ownable { using SafeMath for uint256; IERC20 public token; event Airdropped(address to, uint256 token); event TokenContractSet(IERC20 newToken); /** * @dev The Airdrop constructor sets the address of the token contract */ constructor (IERC20 _tokenAddr) public { require(address(_tokenAddr) != address(0), "Zero address received"); token = _tokenAddr; emit TokenContractSet(_tokenAddr); } /** * @dev Allows the tokens to be dropped to the respective beneficiaries * @param beneficiaries An array of beneficiary addresses that are to receive tokens * @param values An array of the amount of tokens to be dropped to respective beneficiaries * @return Returns true if airdrop is successful */ function drop(address[] beneficiaries, uint256[] values) external onlyOwner returns (bool) { require(beneficiaries.length == values.length, "Array lengths of parameters unequal"); for (uint i = 0; i < beneficiaries.length; i++) { require(beneficiaries[i] != address(0), "Zero address received"); require(getBalance() >= values[i], "Insufficient token balance"); token.transfer(beneficiaries[i], values[i]); emit Airdropped(beneficiaries[i], values[i]); } return true; } /** * @dev Used to check contract's token balance */ function getBalance() public view returns (uint256 balance) { balance = token.balanceOf(address(this)); } /** * @dev Sets the address of the token contract * @param newToken The address of the token contract */ function setTokenAddress(IERC20 newToken) public onlyOwner { require(address(newToken) != address(0), "Zero address received"); token = newToken; emit TokenContractSet(newToken); } }
Allows the current owner to transfer control of the contract to a newOwner. newOwner The address to transfer ownership to./
function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Zero address received"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; }
7,236,916
./full_match/5/0x84510F2570a786370072a26201516c6C8d28ec8F/sources/contracts/SoulboundSecurity_flattened.sol
Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override. WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant being that for any address `a` the value returned by `balanceOf(a)` must be equal to the number of tokens such that `ownerOf(tokenId)` is `a`./ solhint-disable-next-line func-name-mixedcase
function __unsafe_increaseBalance(address account, uint256 amount) internal { _balances[account] += amount; }
1,910,268
pragma solidity ^0.5.16; import '../core/Ownable.sol'; import '../accesscontrol/GrowerRole.sol'; import '../accesscontrol/TesterRole.sol'; import '../accesscontrol/DistributorRole.sol'; import '../accesscontrol/RetailerRole.sol'; import '../accesscontrol/ConsumerRole.sol'; contract SupplyChainBase is Ownable, GrowerRole, TesterRole, DistributorRole, RetailerRole, ConsumerRole { // // define structs for items of interest // We assume our cannabis is grown in bulk in one of 4 varieties/strains: // 1. Trippy Purple Bubblegum Haze (a sativa) // 2. Vulcan Mind Melt (a hybrid) // 3. Catatonic Couchlock Kush (an indica) // 4. Snoozy Woozy (a high CBD, lower THC strain) // We can assign each strain a UPC which differentiates it from other strains. // We assume a very simple mapping between UPC and Strain: the UPC is always a positive integer and // the ending digit indicates the Strain as follows: // - UPC ending in 0,1,2 = Trippy Purple Bubblegum Haze // - UPC ending in 3,4,5 = Vulcan Mind Melt // - UPC ending in 6,7 = Catatonic Couchlock Kush // - UPC ending in 8,9 = Snoozy Woozy // So from the UPC we can always find the Strain, and in the UI we specifiy the Strain by choosing the UPC. // // Like coffee, cannabis is a bulk item that gets segmented into retail-sized units later in the process. // So, an Item in cannabis (or coffee) must also indicate the size we are talking about. Furthermore, // a single bulk quantity (bale) of cannabis will be processed into a large number of individually sized // retail packages, so there will be N retail-sized packages for each bale. None of this logic was properly // considered by Udacity in their starter code, so it is added here. // // How I Handle IDs: // - Each strain is associated with one or more UPC's. The last digit of the UPC indicates the strain. // - The UPC for a given strain refers to some undetermined bulk quantity of canabis. In order for // the cannabis to be any sort of "item", it must be segmented first into some number of (say) 10 kg "bales". // - Each bale from the above bulk cannabis will be uniquely identified by the UPC and a bale ID (a uint). // It is perfectly possible and acceptable for two bales with different UPCs to have the same value for bale ID, // ie the bale ID is unique only to the UPC. Again, it is the combination of UPC and bale ID that uniquely identifies the bale. // - A sample is just a small quantity from a given bale that is sent for testing. Each sample has its own // sample ID that is unique only to the bale. In our simplified chain, we will only ever have a single sample from a given // bale. // - When the bale is processed, it creates some number of retail-sized items. In real life, a bale // would create a large number (thousands) of retail-sized (say 3 gram) retail packages. For simplicity // in this project, I reduce that number drastically to 10. In other words, when the cannabis is processed // it gets converted from a single bale into 10 retail sized (3 gram) retail products. // - Each retail (3 gram) jar of canabis has its own item ID that is unique only to that bale. The combination of // item ID, bale ID, and UPC uniquely determines the retail item (the liitle 3 gram jar of weed you buy at the dispensary). // // // Define a variable called 'autosku' which is how we automatically generate SKU. // In real life, various parties would create their own values, but to keep it simple we just auto-generate this uint autosku; enum Strain { TrippyPurpleBubblegumHaze, // 0 VulcanMindMelt, // 1 CatatonicCouchlockKush, // 2 SnoozyWoozy // 3 } // // The cannabis starts out as a bale-sized chunk of plants. It gets processed into a an actual bale (say a 10kg sized chunk). // Next it gets sampled, tested, and eventually packed. // When it is packed, it basically ceases to exist as a bale, instead it is now in the form of a large number of retail sized packages // In this simplified supply chain, each bale creates exactly 10 retail packages (the number in real life will be much larger). // enum State { Harvested, // 0 Bale-sized cannabis is now in the form of a bunch of harvested plants Processed, // 1 Plants processed to extract the flower and remove unusable matter, formed into a bale Sampled, // 2 Bale is sampled for testing. Sample is created with state Sampled SampleRequested, // 3 Tester has requested the sample for testing. SentToTester, // 4 Bale is sampled and the sample is sent to the tester to check quality, THC and CBD content etc ReceivedByTester, // 5 Sample received by tester InTesting, // 6 Sample in testing Approved, // 7 Sample approved, approval sent back to grower/farmer Productized, // 8 Bale of cannabis productized/converted to retail packages. Each new retail package has state Productized ForSaleByGrower, // 9 Bale and its retail packages are now for sale to distributor. SoldByGrower, // 10 Sold to distributor. The owner of the bale and its retail packages is now the Distributor ShippedToDistributor, // 11 Shipped to retailer/dispensary ReceivedByDistributor, // 12 Received by retailer/dispensary. ForSaleByDistributor, // 13 Bales and retail items now for sale to retailer SoldByDistributor, // 14 Bales and retail items now sold to retailer. Owner is now the retailer ShippedToRetailer, // 15 Shipped to retailer/dispensary ReceivedByRetailer, // 16 Received by retailer/dispensary. ForSaleByRetailer, // 17 Retailer/dispensary puts individual package onto its shelves for sale PurchasedByConsumer // 18 Consumer buys a retail package } struct FarmInfo { string originFarmName; // Grower Name string originFarmInformation; // Grower Information string originFarmLatitude; // Grow Latitude string originFarmLongitude; // Grow Longitude } struct BaleAddresses { address payable ownerID; // Metamask-Ethereum address of the current owner as the product moves through various stages address payable originGrowerID; // Metamask-Ethereum address of the Grower/Farmer address payable growerID; // Metamask-Ethereum address of the Grower address payable testerID; // Metamask-Ethereum address of the Tester address payable distributorID; // Metamask-Ethereum address of the Distributor address payable retailerID; // Metamask-Ethereum address of the Retailer } // // Define a struct 'BaleItem' // struct BaleItem { uint sku; // Stock Keeping Unit (SKU), generated automatically uint upc; // Universal Product Code (UPC), generated by the Farmer, goes on the package, can be verified by the Consumer uint baleId; // ID unique to bale, set by grower string strainName; uint thcPct; uint cbdPct; string productNotes; // Product Notes uint growerPrice; // Price charged by grower for distributor to buy bale uint distributorPrice; // Price charged by distributor to retailer to buy bale uint numRetailProducts; // Number of retail products created for this bale (eg 10) State itemState; // Product State as represented in the enum above BaleAddresses baleAddresses; } // // Define a struct 'SampleItem'. We only store testerID in addresses because the other addresses we can get from the bale. // struct SampleItem { uint upc; // Universal Product Code (UPC), generated by the Grower/Farmer, goes on the package, can be verified by the Consumer uint baleId; // ID unique to bale, set by grower uint sampleId; // ID unique to this sample for the given bale address payable ownerID; // Metamask-Ethereum address of the current owner as the product moves through various stages State itemState; // Product State as represented in the enum above address payable testerID; // Metamask-Ethereum address of the Tester } // // Define a struct 'RetailItem'. We only store consumerID in addresses because the other addresses we can get from the bale. // struct RetailItem { uint sku; // Stock Keeping Unit (SKU), generated automatically uint upc; // Universal Product Code (UPC), generated by the Farmer, goes on the package, can be verified by the Consumer uint baleId; // ID unique to bale, set by grower uint retailId; // ID unique to this retail package for the given bale uint retailPrice; // Product Price for each retail item address payable ownerID; // Metamask-Ethereum address of the current owner as the product moves through various stages State itemState; // Product State as represented in the enum above address payable consumerID; // Metamask-Ethereum address of the Consumer } // // mapping for info about growers // mapping (address => FarmInfo) farmsInfo; // // mappings for items // // store BaleItem by [upc][baleId]. // mapping (uint => mapping(uint => BaleItem)) bales; // // store SampleItem by [upc][baleId][sampleId] // mapping (uint => mapping(uint => mapping(uint => SampleItem))) samples; mapping (uint => mapping(uint => SampleItem[])) samplesForBale; // // store RetailItem by [upc][baleId][retailId] // mapping (uint => mapping(uint => mapping(uint => RetailItem))) retailItems; mapping (uint => mapping(uint => RetailItem[])) retailItemsForBale; // // Define public mappings 'baleItemsHistory', 'sampleItemsHistory, 'retailItemsHistory' // that map the UPC and Ids to an array of TxHash, // that track the item's journey through the supply chain -- to be sent from DApp. // mapping (uint => mapping(uint => string[])) baleItemsHistory; mapping (uint => mapping(uint => mapping(uint => string[]))) sampleItemsHistory; mapping (uint => mapping(uint => mapping(uint => string[]))) retailItemsHistory; mapping (uint => string) statesAsStrings; // // Define 21 events: 19 events with the same 19 state values plus two creation events: SampleCreated and RetailItemCreated // event Harvested(uint upc, uint baleId, uint _state, string _stateStr, string _strainStr); event Processed(uint upc, uint baleId, uint _state, string _stateStr); event Sampled(uint upc, uint baleId); event SampleCreated(uint upc, uint baleId, uint sampleId); event SampleRequested(uint upc, uint baleId, uint sampleId); event SentToTester(uint upc, uint baleId, uint sampleId); event ReceivedByTester(uint upc, uint baleId, uint sampleId); event InTesting(uint upc, uint baleId, uint sampleId); event Approved(uint upc, uint baleId, uint sampleId); event Productized(uint upc, uint baleId); event RetailItemCreated(uint upc, uint baleId, uint retailId); event ForSaleByGrower(uint upc, uint baleId, uint growerPrice); event SoldByGrower(uint upc, uint baleId); event ShippedToDistributor(uint upc, uint baleId); event ReceivedByDistributor(uint upc, uint baleId); event ForSaleByDistributor(uint upc, uint baleId, uint distributorPrice); event SoldByDistributor(uint upc, uint baleId); event ShippedToRetailer(uint upc, uint baleId); event ReceivedByRetailer(uint upc, uint baleId); event ForSaleByRetailer(uint upc, uint baleId, uint retailId, uint retailPrice); event PurchasedByConsumer(uint upc, uint baleId, uint retailId); ///////////////////////// ///////////////////////// // Define modifiers ///////////////////////// ///////////////////////// ///////////////////////////// // price checking modifiers ///////////////////////////// // Define a modifer that verifies the Caller modifier verifyCaller (address _address) { require(msg.sender == _address); _; } // Define a modifer that verifies the distributor for shipping modifier verifyDistributor(uint _upc, uint _baleId, address _address) { require(bales[_upc][_baleId].baleAddresses.distributorID == _address); _; } // Define a modifer that verifies the retailer for shipping or consumer purchase modifier verifyRetailer(uint _upc, uint _baleId, address _address) { require(bales[_upc][_baleId].baleAddresses.retailerID == _address); _; } // Define a modifier that checks if the paid amount is sufficient to cover the price modifier paidEnough(uint _price) { require(msg.value >= _price); _; } // Need a function version to get around stack too deep issue function paidEnoughFunc(uint _price) internal view { require(msg.value >= _price); } // Define a modifier that checks the price and refunds the remaining balance to the buyer (the distributor buys bales from grower) modifier checkGrowerValue(uint _upc, uint baleId) { uint _price = bales[_upc][baleId].growerPrice; uint amountToReturn = msg.value - _price; bales[_upc][baleId].baleAddresses.distributorID.transfer(amountToReturn); _; } // Define a modifier that checks the price and refunds the remaining balance to the buyer (the retailer buys bales from distributor) modifier checkDistributorValue(uint _upc, uint baleId) { uint _price = bales[_upc][baleId].distributorPrice; uint amountToReturn = msg.value - _price; bales[_upc][baleId].baleAddresses.distributorID.transfer(amountToReturn); _; } // Define a modifier that checks the price and refunds the remaining balance to the buyer (the consumer buys retail items) modifier checkRetailerValue(uint _upc, uint baleId, uint retailId) { uint _price = retailItems[_upc][baleId][retailId].retailPrice; uint amountToReturn = msg.value - _price; retailItems[_upc][baleId][retailId].consumerID.transfer(amountToReturn); _; } // Need a function version to get around stack too deep issue function checkRetailerValueFunc(uint _upc, uint baleId, uint retailId) internal { uint _price = retailItems[_upc][baleId][retailId].retailPrice; uint amountToReturn = msg.value - _price; retailItems[_upc][baleId][retailId].consumerID.transfer(amountToReturn); } ///////////////////////////// // state checking modifiers ///////////////////////////// // // Define a modifier that checks if this bale exists at all yet // In Solidity, accessing a mapping element will always return something (in this case a struct) // but if that element has not been written to (was not created in code) it will have values 0 // (in this case all struct elements == 0) // // So, this bale will not exist if the sku is 0 // modifier noSuchBale(uint _upc, uint baleId) { require(bales[_upc][baleId].sku == 0); _; } // Define a modifier that checks if a bale state is Harvested modifier harvested(uint _upc, uint baleId) { require(bales[_upc][baleId].itemState == State.Harvested); _; } // Define a modifier that checks if a bale state is Processed modifier processed(uint _upc, uint baleId) { require(bales[_upc][baleId].itemState == State.Processed); _; } // Define a modifier that checks if a bale state is Sampled modifier sampled(uint _upc, uint baleId) { require(bales[_upc][baleId].itemState == State.Sampled); _; } // Define a modifier that checks if a bale state is SampleRequested modifier sampleRequested(uint _upc, uint baleId) { require(bales[_upc][baleId].itemState == State.SampleRequested); _; } // Define a modifier that checks if the sample state is SentToTester modifier sentToTester(uint _upc, uint baleId, uint sampleId) { require(samples[_upc][baleId][sampleId].itemState == State.SentToTester); _; } // Define a modifier that checks if the sample state is ReceivedByTester modifier receivedByTester(uint _upc, uint baleId, uint sampleId) { require(samples[_upc][baleId][sampleId].itemState == State.ReceivedByTester); _; } // Define a modifier that checks if the sample state is InTesting modifier inTesting(uint _upc, uint baleId, uint sampleId) { require(samples[_upc][baleId][sampleId].itemState == State.InTesting); _; } // Define a modifier that checks if the bale state is Approved // Note: As soon as tester approves sample, the state of both the sample and the bale are set to Approved modifier approved(uint _upc, uint baleId) { require(bales[_upc][baleId].itemState == State.Approved); _; } // Define a modifier that checks if the bale state is Productized modifier productized(uint _upc, uint baleId) { require(bales[_upc][baleId].itemState == State.Productized); _; } // Define a modifier that checks if the bale state is ForSaleByGrower modifier forSaleByGrower(uint _upc, uint baleId) { require(bales[_upc][baleId].itemState == State.ForSaleByGrower); _; } // Define a modifier that checks if the bale state is SoldByGrower modifier soldByGrower(uint _upc, uint baleId) { require(bales[_upc][baleId].itemState == State.SoldByGrower); _; } // Define a modifier that checks if the bale state is ShippedToDistributor modifier shippedToDistributor(uint _upc, uint baleId) { require(bales[_upc][baleId].itemState == State.ShippedToDistributor); _; } // Define a modifier that checks if the bale state is ReceivedByDistributor modifier receivedByDistributor(uint _upc, uint baleId) { require(bales[_upc][baleId].itemState == State.ReceivedByDistributor); _; } // Define a modifier that checks if the bale state is ForSaleByDistributor modifier forSaleByDistributor(uint _upc, uint baleId) { require(bales[_upc][baleId].itemState == State.ForSaleByDistributor); _; } // Define a modifier that checks if the bale state is SoldByDistributor modifier soldByDistributor(uint _upc, uint baleId) { require(bales[_upc][baleId].itemState == State.SoldByDistributor); _; } // Define a modifier that checks if the bale state is ShippedToRetailer modifier shippedToRetailer(uint _upc, uint baleId) { require(bales[_upc][baleId].itemState == State.ShippedToRetailer); _; } // // Define a modifier that checks if the bale state is ReceivedByRetailer // This is the final state of the bale // modifier receivedByRetailer(uint _upc, uint baleId) { require(bales[_upc][baleId].itemState == State.ReceivedByRetailer); _; } // Define a modifier that checks if the retail item state is ForSaleByRetailer modifier forSaleByRetailer(uint _upc, uint baleId, uint retailId) { require(retailItems[_upc][baleId][retailId].itemState == State.ForSaleByRetailer); _; } // Need a function version to get around stack too deep issue function forSaleByRetailerFunc(uint _upc, uint baleId, uint retailId) internal view { require(retailItems[_upc][baleId][retailId].itemState == State.ForSaleByRetailer); } // Define a modifier that checks if the retail item state is PurchasedByConsumer modifier purchasedByConsumer(uint _upc, uint baleId, uint retailId) { require(retailItems[_upc][baleId][retailId].itemState == State.PurchasedByConsumer); _; } // // In the constructor set 'autosku' to 1 and call fillStateDescriptions // constructor() public payable { autosku = 1; fillStateDescriptions(); } // Define a function 'kill' if required function kill() onlyOwner public { selfdestruct(owner()); } ///////////////////////////////////////////// // cannabis specific functions ///////////////////////////////////////////// function fillStateDescriptions() internal { statesAsStrings[uint(State.Harvested)] = "Harvested"; statesAsStrings[uint(State.Processed)] = "Processed"; statesAsStrings[uint(State.Sampled)] = "Sampled"; statesAsStrings[uint(State.SampleRequested)] = "Sample Requested"; statesAsStrings[uint(State.SentToTester)] = "Sent To Tester"; statesAsStrings[uint(State.ReceivedByTester)] = "Received By Tester"; statesAsStrings[uint(State.InTesting)] = "In Testing"; statesAsStrings[uint(State.Approved)] = "Approved"; statesAsStrings[uint(State.Productized)] = "Productized"; statesAsStrings[uint(State.ForSaleByGrower)] = "For Sale By Grower"; statesAsStrings[uint(State.SoldByGrower)] = "Sold By Grower"; statesAsStrings[uint(State.ShippedToDistributor)] = "Shipped To Distributor"; statesAsStrings[uint(State.ReceivedByDistributor)] = "Received By Distributor"; statesAsStrings[uint(State.ForSaleByDistributor)] = "For Sale By Distributor"; statesAsStrings[uint(State.SoldByDistributor)] = "Sold By Distributor"; statesAsStrings[uint(State.ShippedToRetailer)] = "Shipped To Retailer"; statesAsStrings[uint(State.ReceivedByRetailer)] = "Received By Retailer"; statesAsStrings[uint(State.ForSaleByRetailer)] = "For Sale By Retailer"; statesAsStrings[uint(State.PurchasedByConsumer)] = "Purchased By Consumer"; } function getStateString(State state) internal view returns (string memory) { return statesAsStrings[uint(state)]; } function getStrainFromUPC(uint upc) internal pure returns (Strain) { uint s = upc % 10; if (s <= 2) { return Strain.TrippyPurpleBubblegumHaze; } else if (s <= 5) { return Strain.VulcanMindMelt; } else if (s <= 7) { return Strain.CatatonicCouchlockKush; } else { return Strain.SnoozyWoozy; } } function getStrainString(Strain strain) internal pure returns (string memory) { if (strain == Strain.TrippyPurpleBubblegumHaze) { return "Trippy Purple Bubblegum Haze"; } else if (strain == Strain.VulcanMindMelt) { return "Vulcan Mind Melt"; } else if (strain == Strain.CatatonicCouchlockKush) { return "Catatonic Couchlock Kush"; } else { return "Snoozy Woozy"; } } function setMockTestResultsForStrain(uint upc) internal pure returns ( uint thcPct, uint cbdPct) { Strain strain = getStrainFromUPC(upc); if (strain == Strain.TrippyPurpleBubblegumHaze) { thcPct = 30; cbdPct = 1; } else if (strain == Strain.VulcanMindMelt) { thcPct = 25; cbdPct = 2; } else if (strain == Strain.CatatonicCouchlockKush) { thcPct = 20; cbdPct = 3; } else { // SnoozyWoozy thcPct = 5; cbdPct = 20; } } /////////////////////////////////// // action functions /////////////////////////////////// // // Define a function 'setGrowerInfo' that sets information aboutthe Farm/Grower // function addGrowerInfo(address _growerID, string memory _originFarmName, string memory _originFarmInformation, string memory _originFarmLatitude, string memory _originFarmLongitude) public onlyGrower() { FarmInfo memory farmInfo = FarmInfo({ originFarmName: _originFarmName, originFarmInformation: _originFarmInformation, originFarmLatitude: _originFarmLatitude, originFarmLongitude: _originFarmLongitude }); farmsInfo[_growerID] = farmInfo; } // // Define a function 'harvestWeed' that allows a grower to mark a bale 'Harvested' // function harvestWeed(uint _upc, uint _baleId, address payable _originGrowerID, string memory _productNotes) public onlyGrower() noSuchBale(_upc,_baleId) returns (uint state, string memory stateStr, string memory strainStr) { Strain strain = getStrainFromUPC(_upc); strainStr = getStrainString(strain); // // Add the new item as part of Harvest // BaleAddresses memory baleAddresses = BaleAddresses({ ownerID: _originGrowerID, originGrowerID: _originGrowerID, growerID: _originGrowerID, testerID: address(0), distributorID: address(0), retailerID: address(0) }); bales[_upc][_baleId] = BaleItem({ sku: autosku, upc: _upc, baleId: _baleId, strainName: strainStr, thcPct: 0, cbdPct: 0, productNotes: _productNotes, growerPrice: 0, distributorPrice: 0, numRetailProducts: 0, itemState: State.Harvested, baleAddresses: baleAddresses }); // // Increment sku // autosku = autosku + 1; // Emit the appropriate event emit Harvested(_upc,_baleId,uint(State.Harvested), stateStr, strainStr); stateStr = getStateString(State.Harvested); return (uint(State.Harvested), stateStr, strainStr); } // // Define a function 'processtWeed' that allows a grower/farmer to mark an item 'Processed' // function processWeed(uint _upc, uint _baleId) public onlyGrower() harvested(_upc,_baleId) verifyCaller(bales[_upc][_baleId].baleAddresses.originGrowerID) returns (uint state, string memory stateStr) { // Update the appropriate fields bales[_upc][_baleId].itemState = State.Processed; // Emit the appropriate event emit Processed(_upc,_baleId, uint(State.Processed), stateStr); stateStr = getStateString(State.Processed); return (uint(State.Processed), stateStr); } // // Define a function 'sampleWeed' that creates a sample for testing and allows a grower/farmer to mark bale as 'Sampled' // function sampleWeed(uint _upc, uint _baleId, address payable testerAddr) public onlyGrower() processed(_upc,_baleId) verifyCaller(bales[_upc][_baleId].baleAddresses.originGrowerID) returns (uint state, string memory stateStr, uint newSampleId) { // Update the appropriate fields bales[_upc][_baleId].baleAddresses.testerID = testerAddr; bales[_upc][_baleId].itemState = State.Sampled; newSampleId = 1; samples[_upc][_baleId][newSampleId] = SampleItem({ upc: _upc, baleId: _baleId, sampleId: newSampleId, ownerID: bales[_upc][_baleId].baleAddresses.ownerID, itemState: State.Sampled, testerID: address(0) }); samplesForBale[_upc][_baleId].push(samples[_upc][_baleId][newSampleId]); // Emit the appropriate event emit Sampled(_upc,_baleId); emit SampleCreated(_upc,_baleId,newSampleId); stateStr = getStateString(State.Sampled); return (uint(State.Sampled), stateStr, newSampleId); } // // Define a function 'requestSample' that let's the tester request a sample from the bale. // It basically just sets the address for the tester // function requestSample(uint _upc, uint _baleId) public onlyTester() sampled(_upc,_baleId) verifyCaller(bales[_upc][_baleId].baleAddresses.testerID) returns (uint state, string memory stateStr) { // Update the appropriate fields bales[_upc][_baleId].baleAddresses.testerID = msg.sender; bales[_upc][_baleId].itemState = State.SampleRequested; uint sampleId = samplesForBale[_upc][_baleId][0].sampleId; samples[_upc][_baleId][sampleId].itemState = State.SampleRequested; samplesForBale[_upc][_baleId][0].itemState = State.SampleRequested; // Emit the appropriate event emit SampleRequested(_upc,_baleId,sampleId); stateStr = getStateString(State.SampleRequested); return (uint(State.SampleRequested), stateStr); } // // Define a function 'sendSampleToTester' that let's the grower send the sample to the tester. // function sendSampleToTester(uint _upc, uint _baleId, uint _sampleId) public onlyGrower() sampleRequested(_upc,_baleId) verifyCaller(bales[_upc][_baleId].baleAddresses.originGrowerID) returns (uint state, string memory stateStr) { // Update the appropriate fields bales[_upc][_baleId].itemState = State.SentToTester; samples[_upc][_baleId][_sampleId].itemState = State.SentToTester; // Emit the appropriate event emit SentToTester(_upc,_baleId,_sampleId); stateStr = getStateString(State.SentToTester); return (uint(State.SentToTester), stateStr); } // // Define a function 'receivedByTester' that let's the tester receive the sample. // function setReceivedByTester(uint _upc, uint _baleId, uint _sampleId) public onlyTester() sentToTester(_upc,_baleId,_sampleId) verifyCaller(bales[_upc][_baleId].baleAddresses.testerID) returns (uint state, string memory stateStr) { // Update the appropriate fields bales[_upc][_baleId].itemState = State.ReceivedByTester; samples[_upc][_baleId][_sampleId].itemState = State.ReceivedByTester; // Emit the appropriate event emit ReceivedByTester(_upc,_baleId,_sampleId); stateStr = getStateString(State.ReceivedByTester); return (uint(State.ReceivedByTester), stateStr); } // // Define a function 'testSample' that let's the tester start testing the sample // function testSample(uint _upc, uint _baleId, uint _sampleId) public onlyTester() receivedByTester(_upc,_baleId,_sampleId) verifyCaller(bales[_upc][_baleId].baleAddresses.testerID) returns (uint state, string memory stateStr) { // Update the appropriate fields bales[_upc][_baleId].itemState = State.InTesting; samples[_upc][_baleId][_sampleId].itemState = State.InTesting; // Emit the appropriate event emit InTesting(_upc,_baleId,_sampleId); stateStr = getStateString(State.InTesting); return (uint(State.InTesting), stateStr); } // // Define a function 'approveSample' that let's the tester approve the sample and bale // It also uses (Mock) test results to set THC and CBD content // function approveSample(uint _upc, uint _baleId, uint _sampleId) public onlyTester() inTesting(_upc,_baleId,_sampleId) verifyCaller(bales[_upc][_baleId].baleAddresses.testerID) returns (uint state, string memory stateStr, uint thcPct, uint cbdPct) { (thcPct, cbdPct) = setMockTestResultsForStrain(_upc); // Update the appropriate fields samples[_upc][_baleId][_sampleId].itemState = State.Approved; bales[_upc][_baleId].thcPct = thcPct; bales[_upc][_baleId].cbdPct = cbdPct; bales[_upc][_baleId].itemState = State.Approved; // Emit the appropriate event emit Approved(_upc,_baleId,_sampleId); stateStr = getStateString(State.Approved); return (uint(State.Approved), stateStr, thcPct, cbdPct); } // // Define a function 'productize' that allows a grower to create retail-sized packages from the bale // and mark an item 'Productized' // function productize(uint _upc, uint _baleId ) public onlyGrower() approved(_upc,_baleId) verifyCaller(bales[_upc][_baleId].baleAddresses.originGrowerID) returns (uint state, string memory stateStr, uint numRetailProducts) { // // create 10 retail sized units (yes in real life we would be creating many more!) // for (uint retailId = 1; retailId <=10; retailId++) { retailItems[_upc][_baleId][retailId] = RetailItem({ sku: bales[_upc][_baleId].sku, upc: _upc, baleId: _baleId, retailId: retailId, retailPrice: 0, ownerID: bales[_upc][_baleId].baleAddresses.ownerID, itemState: State.Productized, consumerID: address(0) }); retailItemsForBale[_upc][_baleId].push(retailItems[_upc][_baleId][retailId]); // Emit the appropriate creation event emit RetailItemCreated(_upc,_baleId,retailId); } // Update the appropriate fields numRetailProducts=10; bales[_upc][_baleId].numRetailProducts = numRetailProducts; bales[_upc][_baleId].itemState = State.Productized; // emit Productized event emit Productized(_upc,_baleId); stateStr = getStateString(State.Productized); return (uint(State.Productized), stateStr, numRetailProducts); } // // Define a function 'setForSaleByGrower' that allows a grower to mark an item 'ForSaleByGrower' // function setForSaleByGrower(uint _upc, uint _baleId, uint _price) public onlyGrower() productized(_upc,_baleId) verifyCaller(bales[_upc][_baleId].baleAddresses.originGrowerID) returns (uint state, string memory stateStr, uint growerPrice) { // Update the appropriate fields bales[_upc][_baleId].itemState = State.ForSaleByGrower; growerPrice = _price; bales[_upc][_baleId].growerPrice = growerPrice; // Emit the appropriate event emit ForSaleByGrower(_upc,_baleId, growerPrice); stateStr = getStateString(State.ForSaleByGrower); return (uint(State.ForSaleByGrower), stateStr, growerPrice); } // // Define a function 'buyBaleFromGrower' that allows the distributor to mark an item 'SoldByGrower' // Use the above defined modifiers to check if the item is available for sale, if the buyer has paid enough, // and any excess ether sent is refunded back to the buyer // function buyBaleFromGrower(uint _upc, uint _baleId) public payable onlyDistributor() forSaleByGrower(_upc,_baleId) paidEnough(bales[_upc][_baleId].growerPrice) checkGrowerValue(_upc,_baleId) returns (uint state, string memory stateStr) { // Update the appropriate fields - ownerID, distributorID, itemState bales[_upc][_baleId].baleAddresses.ownerID = msg.sender; bales[_upc][_baleId].baleAddresses.distributorID = msg.sender; bales[_upc][_baleId].itemState = State.SoldByGrower; // Transfer money to grower bales[_upc][_baleId].baleAddresses.originGrowerID.transfer(bales[_upc][_baleId].growerPrice); // emit the appropriate event emit SoldByGrower(_upc,_baleId); stateStr = getStateString(State.SoldByGrower); return (uint(State.SoldByGrower), stateStr); } // // Define a function 'shipToDistributor' that allows the distributor to mark an item 'Shipped' // Use the above modifers to check if the item is sold // function shipToDistributor(uint _upc, uint _baleId) public onlyGrower() soldByGrower(_upc,_baleId) verifyCaller(bales[_upc][_baleId].baleAddresses.originGrowerID) returns (uint state, string memory stateStr) { // Update the appropriate fields bales[_upc][_baleId].itemState = State.ShippedToDistributor; // Emit the appropriate event emit ShippedToDistributor(_upc,_baleId); stateStr = getStateString(State.ShippedToDistributor); return (uint(State.ShippedToDistributor), stateStr); } // // Define a function 'receivedByDistributor' that allows the distributor to mark an item 'ReceivedByDistributor' // Use the above modifers to check if the item is shipped // function setReceivedByDistributor(uint _upc, uint _baleId) public onlyDistributor() shippedToDistributor(_upc,_baleId) verifyCaller(bales[_upc][_baleId].baleAddresses.distributorID) returns (uint state, string memory stateStr) { // Update the appropriate fields bales[_upc][_baleId].itemState = State.ReceivedByDistributor; // Emit the appropriate event emit ReceivedByDistributor(_upc,_baleId); stateStr = getStateString(State.ReceivedByDistributor); return (uint(State.ReceivedByDistributor), stateStr); } // // Define a function 'setForSaleByDistributor' that allows a distributor to mark an item 'ForSaleByDistributor' // function setForSaleByDistributor(uint _upc, uint _baleId, uint _distributorPrice) public onlyDistributor() receivedByDistributor(_upc,_baleId) verifyCaller(bales[_upc][_baleId].baleAddresses.distributorID) returns (uint state, string memory stateStr, uint distributorPrice) { // Update the appropriate fields bales[_upc][_baleId].itemState = State.ForSaleByDistributor; distributorPrice = _distributorPrice; bales[_upc][_baleId].distributorPrice = distributorPrice; // Emit the appropriate event emit ForSaleByDistributor(_upc,_baleId, distributorPrice); stateStr = getStateString(State.ForSaleByDistributor); return (uint(State.ForSaleByDistributor), stateStr, distributorPrice); } // // Define a function 'buyBaleFromDistributor' that allows the distributor to mark an item 'SoldByDistributor' // Use the above defined modifiers to check if the item is available for sale, if the buyer has paid enough, // and any excess ether sent is refunded back to the buyer // function buyBaleFromDistributor(uint _upc, uint _baleId) public payable onlyRetailer() forSaleByDistributor(_upc,_baleId) paidEnough(bales[_upc][_baleId].distributorPrice) checkDistributorValue(_upc,_baleId) returns (uint state, string memory stateStr) { // Update the appropriate fields - ownerID, retailerID, itemState bales[_upc][_baleId].baleAddresses.ownerID = msg.sender; bales[_upc][_baleId].baleAddresses.retailerID = msg.sender; bales[_upc][_baleId].itemState = State.SoldByDistributor; // Transfer money to distributor bales[_upc][_baleId].baleAddresses.distributorID.transfer(bales[_upc][_baleId].distributorPrice); // emit the appropriate event emit SoldByDistributor(_upc,_baleId); stateStr = getStateString(State.SoldByDistributor); return (uint(State.SoldByDistributor), stateStr); } // // Define a function 'shipToRetailer' that allows the distributor to mark an item 'ShippedToRetailer' // Use the above modifers to check if the item is sold // function shipToRetailer(uint _upc, uint _baleId) public onlyDistributor() soldByDistributor(_upc,_baleId) verifyCaller(bales[_upc][_baleId].baleAddresses.distributorID) returns (uint state, string memory stateStr) { // Update the appropriate fields bales[_upc][_baleId].itemState = State.ShippedToRetailer; // Emit the appropriate event emit ShippedToRetailer(_upc,_baleId); stateStr = getStateString(State.ShippedToRetailer); return (uint(State.ShippedToRetailer), stateStr); } // // Define a function 'receivedByRetailer' that allows the retailer to mark an item 'ReceivedByRetailer' // Use the above modifers to check if the item is shipped // function setReceivedByRetailer(uint _upc, uint _baleId) public onlyRetailer() shippedToRetailer(_upc,_baleId) verifyCaller(bales[_upc][_baleId].baleAddresses.retailerID) returns (uint state, string memory stateStr) { // Update the appropriate fields bales[_upc][_baleId].itemState = State.ReceivedByRetailer; // Emit the appropriate event emit ReceivedByRetailer(_upc,_baleId); stateStr = getStateString(State.ReceivedByRetailer); return (uint(State.ReceivedByRetailer), stateStr); } // // Define a function 'setForSaleByRetailer' that allows a distributor to mark the retail items as 'ForSaleByRetailer' // function setForSaleByRetailer(uint _upc, uint _baleId, uint _retailPrice) public onlyRetailer() receivedByRetailer(_upc,_baleId) verifyCaller(bales[_upc][_baleId].baleAddresses.retailerID) returns (uint state, string memory stateStr, uint retailPrice) { // // set retail price for each item // Apply markup percentage to bale price and divide by number of retail products to get retail price of each retail product // uint retailId; uint n = bales[_upc][_baleId].numRetailProducts; retailPrice = _retailPrice; // // Update the appropriate fields on the retail items for this bale // for (uint i = 0; i<n; i++) { retailId = retailItemsForBale[_upc][_baleId][i].retailId; retailItems[_upc][_baleId][retailId].retailPrice = retailPrice; retailItems[_upc][_baleId][retailId].itemState = State.ForSaleByRetailer; // Emit the appropriate event emit ForSaleByRetailer(_upc,_baleId,retailId, retailPrice); } bales[_upc][_baleId].itemState = State.ForSaleByRetailer; stateStr = getStateString(State.ForSaleByRetailer); return (uint(State.ForSaleByRetailer), stateStr, retailPrice); } // // Define a function 'purchaseRetailItem' that allows the consumer to mark an item 'PurchasedByConsumer' // NOTE: We use function versions of modifiers to avoid stack too deep error // function purchaseItem(uint _upc, uint _baleId, uint _retailId) public payable onlyConsumer() returns (uint state, string memory stateStr) { // // modifier function checks // forSaleByRetailerFunc(_upc,_baleId,_retailId); paidEnoughFunc(retailItems[_upc][_baleId][_retailId].retailPrice); checkRetailerValueFunc(_upc,_baleId,_retailId); // Update the appropriate fields - ownerID, retailerID, itemState retailItems[_upc][_baleId][_retailId].ownerID = msg.sender; retailItems[_upc][_baleId][_retailId].consumerID = msg.sender; retailItems[_upc][_baleId][_retailId].itemState = State.PurchasedByConsumer; // Transfer money to retailer bales[_upc][_baleId].baleAddresses.retailerID.transfer(retailItems[_upc][_baleId][_retailId].retailPrice); // emit the appropriate event emit PurchasedByConsumer(_upc,_baleId,_retailId); stateStr = getStateString(State.ForSaleByRetailer); return (uint(State.ForSaleByRetailer), stateStr); } ////////// }
Need a function version to get around stack too deep issue
function forSaleByRetailerFunc(uint _upc, uint baleId, uint retailId) internal view { require(retailItems[_upc][baleId][retailId].itemState == State.ForSaleByRetailer); }
7,238,395
//SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma abicoder v2; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; // GraffitETH is an NFT contract in which each token represents a pixel. The owner has the right // to change the pixel color. Pixel ownership is governed by the Harberger tax mechanism, i.e., // - every pixel can be bought at any time at a price the owner has to set // - the owner has to pay a tax proportional to the pixel price // // In order to facilitate tax payments, the contract manages accounts. Each account stores a // balance and the tax base. The tax base is the sum of the prices of all pixels the account owns. // It is used to calculate the tax burden (tax base * tax rate per second = tax burden per second). // The balance is increased by depositing or by selling pixels. It is decreased by withdrawing, by // paying taxes, and by buying pixels. // // The account also stores the time at which the last tax payment has been carried out. This is // used to calculate the timespan for which taxes have to be paid next time. The contract ensures // that taxes are paid whenever the balance or tax base changes. This means that the "missing" tax // is always simply tax base * tax rate * time since last tax payment. // // Account balances become negative if the deposit does not cover the tax burden. In this case, // new deposits go directly to the tax receiver's account until the account balance is zero again. // // If an account balance is negative (i.e. taxes have not been paid), the account's pixels can be // bought for free by anyone with a non-negative balance. // // All amounts and prices are stored in GWei and usually as uint64's. In order to avoid overflows, // in most cases math is carried out "clamped", i.e., if numbers would go above the maximum (or // below the minimum) we just treat them as if they would be exactly at the maximum (minimum). This // means very large or very low numbers are not necessarily accurate. However, the positive maximum // is realistically never going to be reached (it corresponds to ~18B ETH/xDai). The negative // maximum can be reached by setting a pixel price extremely high and accumulating the debt. In // this case, the clamping would save the account some taxes, but only when it's already so much // in debt that it will likely never be repaid anyway. // // The clamping math is an alternative to the usual approach of reverting transactions when numbers // run out of bounds. The latter might be a way for an owner to prevent their pixels from being // sold. // // The main exception from using clamped math is for calculating the tax base as the sum of all // pixel prices. Otherwise, one could do the following: // 1) set the price of two pixels to 2**64 - 1, meaning the tax base would be clamped // at 2**64 - 1. // 2) set the price of one of the pixels to 0, meaning the tax base is zero. Thus, // one would have to pay no taxes despite owning one pixel at price 2**64 - 1. // Instead, we revert if the sum would exceed the maximum allowed value, so that the user can // choose a lower value. // // The contract tracks the total amount of taxes an account has paid. This allows them to claim a // proportional amount of DAO shares in a separate contract. // // Freely transferring pixels is prevented as it would not only transfer value, but also the // obligation to pay taxes. Instead, we allow pixel owners to "earmark" pixels for other users. The // earmark stores the receiver's address and an additional amount. The receiver can claim any // pixel that is earmarked to them. If they do, the pixel as well as the deposit amount is // transferred to them. // // We inherit the approve and approve-for-all functionality from the ERC721 standard. Accounts that // are approved for an individual pixel can set its price and color. In addition, accounts approved // for all, have access to the approver's balance, i.e., can withdraw, buy pixels, and earmark on // their behalf. // Every user of the system gets one account that tracks their balance and tax payments. struct Account { int64 balance; uint64 taxBase; uint64 lastTaxPayment; uint64 totalTaxesPaid; } // An earmark is created by a pixel's owner and allows the receiver to claim the pixel along with // a part of their deposit. struct Earmark { address receiver; uint64 amount; } // Structs grouping arguments used to circumvent stack limit. struct PixelBuyArgs { uint256 pixelID; uint64 maxPrice; uint64 newPrice; uint8 color; } struct SetColorArgs { uint256 pixelID; uint8 newColor; } struct SetPriceArgs { uint256 pixelID; uint64 newPrice; } // RugPull is a safety hatch. It allows the owner to withdraw all funds from a contract in case of // a bug, in particular to be able to withdraw stuck funds. This action must be announced a certain // time in advance (e.g., a month, configurable) in order to allow users that don't trust the owner // to withdraw their deposits first. The safety hatch can be disabled once the contract has proven // to work reliably. // // This contract is intended to be a base from which other contracts inherit from. It does not // implement any access control, but instead exposes rugpull functions as internal functions. contract RugPull { event RugPullAnnounced( address indexed sender, uint256 timestamp, uint256 rugPullTime ); event RugPulled( address indexed sender, address indexed receiver, uint256 value ); event RugPullDisabled(address indexed sender); uint256 private _rugPullHeadsUp; uint256 private _rugPullTime; bool private _rugPullDisabled; constructor(uint256 headsUp) { // avoid overflow if heads up is chosen extremely large require(headsUp <= 5 * 365 * 24 * 60 * 60, "RugPull: heads up too big"); _rugPullHeadsUp = headsUp; _rugPullDisabled = false; _rugPullTime = 0; } function _disableRugPull() internal { require(!_rugPullDisabled, "RugPull: already disabled"); _rugPullDisabled = true; emit RugPullDisabled(msg.sender); } function _announceRugPull() internal { require(!_rugPullDisabled, "RugPull: disabled"); require(_rugPullTime == 0, "RugPull: already announced"); _rugPullTime = block.timestamp + _rugPullHeadsUp; emit RugPullAnnounced({ sender: msg.sender, timestamp: block.timestamp, rugPullTime: _rugPullTime }); } function _performRugPull(address receiver, uint256 value) internal { require(!_rugPullDisabled, "RugPull: disabled"); require(_rugPullTime != 0, "RugPull: not announced yet"); require( block.timestamp >= _rugPullTime, "RugPull: heads up not passed yet" ); (bool success, ) = receiver.call{value: value}(""); require(success, "RugPull: sending funds failed"); emit RugPulled({sender: msg.sender, receiver: receiver, value: value}); } /// @dev Get the minimum time interval in seconds between announcement and the first block at /// which the owner can perform the rug pull. function getRugPullHeadsUp() public view returns (uint256) { return _rugPullHeadsUp; } /// @dev Get the earliest timestamp at which the owner can perform the rug pull or zero if the /// rug pull has not been announced yet. function getRugPullTime() public view returns (uint256) { return _rugPullTime; } /// @dev Check if the rug pull safety hatch is disabled or not. function checkRugPullDisabled() public view returns (bool) { return _rugPullDisabled; } /// @dev Check if a rug pull has already been announced. function checkRugPullAnnounced() public view returns (bool) { return _rugPullTime != 0; } } contract GraffitETH2 is ERC721, Ownable, RugPull { // // Events // event Deposited( address indexed account, address indexed depositor, uint64 amount, int64 balance ); event Withdrawn( address indexed account, address indexed receiver, uint64 amount, int64 balance ); event ColorChanged( uint256 indexed pixelID, address indexed owner, uint8 color ); event PriceChanged( uint256 indexed pixelID, address indexed owner, uint64 price ); event Bought( uint256 indexed pixelID, address indexed seller, address indexed buyer, uint64 price ); event TaxWithdrawn(uint256 amount, address indexed receiver); event Earmarked( uint256 indexed pixelID, address indexed owner, address indexed receiver, uint64 amount ); event PixelClaimed( uint256 indexed pixelID, address indexed oldOwner, address indexed newOwner, uint64 amount ); // // State variables // // the tax rate per second is _taxRateNumerator / _taxRateDenominator uint256 private _taxRateNumerator; uint256 private _taxRateDenominator; uint64 private _taxStartTime; // timestamp before which no taxes have to be paid uint256 private _maxPixelID; // pixel ids range from 0 to _maxPixelID (inclusive) uint64 private _initialPrice; // initial price at which pixels are first sold // during initialization the owner can set owners, prices, and colors of pixels. bool private _initializing; mapping(uint256 => uint64) private _pixelPrices; mapping(address => Account) private _accounts; mapping(uint256 => Earmark) private _earmarks; uint64 private _totalInitialSaleRevenue; // amount raised for owner by selling pixels for first time uint64 private _totalTaxesPaid; // sum of all taxes paid // amount withdrawn by owner so far, both from taxes and initial sales uint64 private _totalWithdrawnByOwner; // // constructor // constructor( uint128 width, uint128 height, uint256 taxRateNumerator, uint256 taxRateDenominator, uint64 taxStartTime, uint64 initialPrice, uint256 rugPullHeadsUp ) ERC721("Pixel", "PXL") RugPull(rugPullHeadsUp) { require(width > 0, "GraffitETH2: width must not be zero"); require(height > 0, "GraffitETH2: height must not be zero"); // this avoids a theoretical overflow during tax computation require( taxRateNumerator <= type(uint64).max, "GraffitETH2: tax rate numerator must not be too large" ); require( taxRateDenominator > 0, "GraffitETH2: tax rate denominator must not be zero" ); _initializing = true; _maxPixelID = width * height - 1; _taxRateNumerator = taxRateNumerator; _taxRateDenominator = taxRateDenominator; _taxStartTime = taxStartTime; _initialPrice = initialPrice; } // // Getters (functions that let other random contracts and stuff read the state) // /// @dev Check if a pixel exists, i.e., has an owner. function exists(uint256 pixelID) public view returns (bool) { return _exists(pixelID); } /// @dev Get the nominal price of a pixel in GWei. The nominal price is the price at which the /// owner wants to sell it (the actual price might be different if the owner is indebted), /// or the initial price if there is no owner yet. function getNominalPrice(uint256 pixelID) public view returns (uint64) { if (!_exists(pixelID)) { return _initialPrice; } return _pixelPrices[pixelID]; } /// @dev Get the price for which anyone can buy a pixel in GWei. For non-existant pixels it is /// the initial price. For all other pixels, it is the nominal price if the owner isn't /// indebted, or zero if they are. function getPrice(uint256 pixelID) public view returns (uint64) { if (!_exists(pixelID)) { return _initialPrice; } address owner = ownerOf(pixelID); if (getBalance(owner) < 0) { return 0; } return _pixelPrices[pixelID]; } /// @dev Get the maximum valid pixel id. function getMaxPixelID() public view returns (uint256) { return _maxPixelID; } /// @dev Get the tax rate per second as nominator-denominator-tuple. function getTaxRate() public view returns (uint256, uint256) { return (_taxRateNumerator, _taxRateDenominator); } /// @dev Get the time from which on taxes have to be paid. function getTaxStartTime() public view returns (uint64) { return _taxStartTime; } /// @dev Get the initial pixel price in GWei. function getInitialPrice() public view returns (uint64) { return _initialPrice; } /// @dev Get the tax base in GWei of an account. The tax base is the sum of the nominal prices /// of all pixels owned by the account. The tax an account has to pay per time interval is /// the tax rate times the tax base. Untouched accounts have a tax base of zero. function getTaxBase(address account) public view returns (uint64) { return _accounts[account].taxBase; } /// @dev Get the time at which the last tax payment has been recorded for the given account. /// For untouched accounts, this returns zero. function getLastTaxPayment(address account) public view returns (uint64) { return _accounts[account].lastTaxPayment; } /// @dev Get the current balance of an account in GWei. This includes all tax payments up to /// now, including tax debt since lastTaxPayment, i.e., tax debt not reflected in the /// balance stored in the contract state. For untouched accounts, this returns 0. function getBalance(address account) public view returns (int64) { Account memory acc = _accounts[account]; uint64 taxPaid; (acc, taxPaid) = _payTaxes(acc); return acc.balance; } /// @dev Get the balance of the given account as it is stored in the contract. This does not /// include outstanding tax payments, so it may be greater than the actual balance. For /// untouched accounts, this returns 0. function getRecordedBalance(address account) public view returns (int64) { return _accounts[account].balance; } /// @dev Get the total money withdrawn by the owner in GWei, both from taxes and initial pixel /// sales. function getTotalWithdrawnByOwner() public view returns (uint256) { return _totalWithdrawnByOwner; } /// @dev Get the total amount of taxes paid in GWei. This only include taxes paid explicitly, /// i.e., it increases whenever the balance stored in the contract decreases due to a tax /// payment. function getTotalTaxesPaid() public view returns (uint64) { return _totalTaxesPaid; } /// @dev Get the total amount of taxes paid by the given account in GWei. This only includes /// taxes paid until the accounts's last tax payment timestamp. For untouched accounts, /// this returns 0. function getTotalTaxesPaidBy(address account) public view returns (uint64) { return _accounts[account].totalTaxesPaid; } /// @dev Get the total taxes paid of the given account in GWei, assuming an immediate tax /// payment. The amount is virtual in the sense that it cannot be withdrawn by the /// contract owner without calling payTaxes first. function getVirtualTotalTaxesPaidBy(address account) public view returns (uint64) { Account memory acc = _accounts[account]; uint64 taxPaid; (acc, taxPaid) = _payTaxes(acc); return acc.totalTaxesPaid; } /// @dev Get the maximum amount of funds (from both initial pixel sales and from taxes) in /// GWei that the owner can withdraw at the moment. function getOwnerWithdrawableAmount() public view returns (uint64) { uint64 totalRevenue = ClampedMath.addUint64(_totalTaxesPaid, _totalInitialSaleRevenue); assert(_totalWithdrawnByOwner <= totalRevenue); uint64 amount = totalRevenue - _totalWithdrawnByOwner; return amount; } /// @dev Get the total money raised by initial pixel sales in GWei. function getTotalInitialSaleRevenue() public view returns (uint256) { return _totalInitialSaleRevenue; } /// @dev Get the address for which a pixel is earmarked. For non-existent pixels or those that /// haven't been earmarked, this returns the zero address. function getEarmarkReceiver(uint256 pixelID) public view returns (address) { return _earmarks[pixelID].receiver; } /// @dev Get the amount in GWei a claimer is allowed to take over from the earmarker. For /// non-existent pixels or those that haven't been earmarked, this returns 0. function getEarmarkAmount(uint256 pixelID) public view returns (uint64) { return _earmarks[pixelID].amount; } /// @dev Check if the contract is in its initialization phase. function isInitializing() public view returns (bool) { return _initializing; } // // Public interface // /// @dev Edit the canvas by buying new pixels and changing price and color of ones already /// owned. The given buyer address must either be the sender or the sender must have been /// approved-for-all by the buyer address. Bought pixels will be transferred to the given /// buyer address. This function works for both existant and non-existant pixels. function edit( address buyerAddress, PixelBuyArgs[] memory buyArgss, SetColorArgs[] memory setColorArgss, SetPriceArgs[] memory setPriceArgss ) public { _buyMany(msg.sender, buyerAddress, buyArgss); _setColorMany(msg.sender, setColorArgss); _setPriceMany(msg.sender, setPriceArgss); } /// @dev Deposit some funds and edit the canvas by buying new pixels and changing price and /// color of ones already owned. Only the buyer address or an account approved-for-all by /// the buyer address can call this function. Deposited funds and bought pixels will go to /// the given buyer address. This function works for both existant and non-existant pixels. /// The sent amount must be a multiple of 1 GWei. function depositAndEdit( address buyerAddress, PixelBuyArgs[] memory buyArgss, SetColorArgs[] memory setColorArgss, SetPriceArgs[] memory setPriceArgss ) public payable { _depositTo(msg.sender, buyerAddress); _buyMany(msg.sender, buyerAddress, buyArgss); _setColorMany(msg.sender, setColorArgss); _setPriceMany(msg.sender, setPriceArgss); } /// @dev Explicitly update the balance of the given account to reflect tax debt for the time /// between last tax payment and now. This function can be called by anyone and in /// particular the contract owner so that they can withdraw taxes. function payTaxes(address account) public { Account memory acc = _accounts[account]; uint64 taxesPaid; (acc, taxesPaid) = _payTaxes(acc); _accounts[account] = acc; _totalTaxesPaid = ClampedMath.addUint64(_totalTaxesPaid, taxesPaid); } /// @dev Deposit money to the given account. The amount sent must be a multiple of 1 GWei. function depositTo(address account) public payable { _depositTo(msg.sender, account); } /// @dev Deposit money for the sender. The amount sent must be a multiple of 1 GWei. function deposit() public payable { _depositTo(msg.sender, msg.sender); } /// @dev Withdraw an amount of GWei from the given account and send it to the given receiver /// address. Only the account itself or an account "approved for all" by the account can /// call this function. The amount must not exceed the account's current balance. function withdraw( address account, uint64 amount, address receiver ) public { _withdraw(msg.sender, account, amount, receiver); } /// @dev Withdraw the maximum possible amount of GWei from the given account and send it to /// the given receiver address. Only the account itself or an account "approved for all" /// by the owner can call this function. function withdrawMax(address account, address receiver) public { _withdrawMax(msg.sender, account, receiver); } /// @dev Withdraw a part of the taxes and income from initial sales and send it to the given /// receiver address. The withdrawal amount is specified in GWei. Only the contract /// owner is allowed to do this. function withdrawOwner(uint64 amount, address receiver) public onlyOwner { _withdrawOwner(amount, receiver); } /// @dev Withdraw all of the taxes and income from initial sales and send it to the given /// address. Only the contract owner is allowed to do this. function withdrawMaxOwner(address receiver) public onlyOwner { _withdrawOwner(getOwnerWithdrawableAmount(), receiver); } /// @dev Earmark a pixel so that the specified account can claim it. Only the pixel owner or an /// all-approved account can earmark a pixel. In addition to the pixel, the receiver can /// also claim the specified amount in GWei from the deposit. function earmark( uint256 pixelID, address receiver, uint64 amount ) public { require(_exists(pixelID), "GraffitETH2: pixel does not exist"); address owner = ownerOf(pixelID); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "GraffitETH2: only pixel owner or approved account can set earmark" ); require(receiver != owner, "GraffitETH2: cannot earmark for owner"); _earmark(pixelID, owner, receiver, amount); } /// @dev Claim a pixel previously earmarked to the caller. This will transfer the pixel to the /// claimer, without changing price or color. In addition, a part of the deposit of the /// original owner will be transferred to the claimer's account, depending on the amount /// the earmarker allowed and their balance. The pixel is only claimed if its price in GWei /// does not exceed `maxPrice` and the transferred deposit is at least `minAmount`. function claim( uint256 pixelID, uint64 maxPrice, uint64 minAmount ) public { _claim(msg.sender, pixelID, maxPrice, minAmount); } /// @dev Freely set the initial owner, price, and color of a set of pixels. Only the owner can /// do this and only during the initialization phase. Each pixel can only be initialized /// once. function init( uint256[] memory pixelIDs, address[] memory owners, uint64[] memory prices, uint8[] memory colors ) public onlyOwner { require( _initializing, "GraffitETH2: initialization phase already over" ); uint256 n = pixelIDs.length; require( owners.length == n, "GraffitETH2: number of owners different from number of pixels" ); require( prices.length == n, "GraffitETH2: number of prices different from number of pixels" ); require( colors.length == n, "GraffitETH2: number of colors different from number of pixels" ); for (uint256 i = 0; i < n; i++) { uint256 pixelID = pixelIDs[i]; address owner = owners[i]; uint64 price = prices[i]; uint8 color = colors[i]; require( !_exists(pixelID), "GraffitETH2: pixel already initialized" ); _mint(owner, pixelID); Account memory acc = _accounts[owner]; uint64 taxesPaid; (acc, taxesPaid) = _payTaxes(acc); acc = _increaseTaxBase(acc, price); _pixelPrices[pixelID] = price; _accounts[owner] = acc; if (taxesPaid > 0) { _totalTaxesPaid = ClampedMath.addUint64( _totalTaxesPaid, taxesPaid ); } emit PriceChanged({pixelID: pixelID, owner: owner, price: price}); emit ColorChanged({pixelID: pixelID, owner: owner, color: color}); } } /// @dev Stop the initialization phase. Only the owner can do this. function stopInitialization() public onlyOwner { require( _initializing, "GraffitETH2: initialization phase already over" ); _initializing = false; } /// @dev Disable the rug pull mechanic for good. function disableRugPull() public onlyOwner { _disableRugPull(); } /// @dev Announce a rug pull to happen after the rug pull heads up. function announceRugPull() public onlyOwner { _announceRugPull(); } /// @dev Withdraw funds from contract after a rug pull has been announced. function performRugPull(address receiver, uint256 value) public onlyOwner { _performRugPull(receiver, value); } // // Internal functions // function _payTaxes(Account memory account) internal view returns (Account memory, uint64) { return Taxes.payTaxes( account, _taxRateNumerator, _taxRateDenominator, _taxStartTime ); } function _payMoreTaxes(Account memory account, uint64 taxesPaid) internal view returns (Account memory, uint64) { return Taxes.payMoreTaxes( account, taxesPaid, _taxRateNumerator, _taxRateDenominator, _taxStartTime ); } function _increaseTaxBase(Account memory account, uint64 newPixelPrice) internal pure returns (Account memory) { require( newPixelPrice <= type(uint64).max - account.taxBase, "GraffitETH2: pixel price too high, tax base max exceeded" ); account.taxBase += newPixelPrice; return account; } function _decreaseTaxBase(Account memory account, uint64 oldPixelPrice) internal pure returns (Account memory) { assert(account.taxBase >= oldPixelPrice); account.taxBase -= oldPixelPrice; return account; } function _increaseBalance( Account memory account, uint64 amount, uint64 taxesPaid ) internal pure returns (Account memory, uint64) { // if the balance is negative, the account owes taxes, so the increase in balance has to // go towards taxesPaid if (account.balance < 0) { // balance is int64 which can't represent -type(int64).min. Therefore, convert to // int256 before flipping the sign. int256 taxesOwed = -int256(account.balance); uint64 taxes; if (taxesOwed >= amount) { taxes = amount; } else { assert(taxesOwed <= type(uint64).max); // taxesOwed < amount <= uint64.max taxes = uint64(taxesOwed); } taxesPaid = ClampedMath.addUint64(taxesPaid, taxes); account.totalTaxesPaid = ClampedMath.addUint64( account.totalTaxesPaid, taxes ); } account.balance = ClampedMath.addInt64(account.balance, amount); return (account, taxesPaid); } function _decreaseBalance(Account memory account, uint64 amount) internal pure returns (Account memory) { account.balance = ClampedMath.subInt64(account.balance, amount); return account; } function _buyMany( address sender, address buyerAddress, PixelBuyArgs[] memory argss ) internal { require( sender == buyerAddress || isApprovedForAll(buyerAddress, sender), "GraffitETH2: sender is neither buyer nor approved" ); if (argss.length == 0) { return; } // Keep track of buyer and seller accounts in memory so that we can persist them to the // state eventually. This is more gas efficient than storing intermediate accounts in the // state. Account memory buyer = _accounts[buyerAddress]; uint256 numSellers = 0; // number of distinct sellers known so far address[] memory sellerAddresses = new address[](argss.length); Account[] memory sellers = new Account[](argss.length); // also keep track of taxes paid and income from initial sales uint64 taxesPaid = 0; uint64 initialSaleRevenue = 0; // pay taxes of buyer so that balance is up to date and we can safely update tax base (buyer, taxesPaid) = _payMoreTaxes(buyer, taxesPaid); for (uint256 i = 0; i < argss.length; i++) { // Make sure pixel ids are sorted and, in particular, no pixel is bought twice. require( i == 0 || argss[i].pixelID > argss[i - 1].pixelID, "GraffitETH2: pixel ids not sorted" ); uint64 price = getPrice(argss[i].pixelID); require( price <= argss[i].maxPrice, "GraffitETH2: pixel price exceeds max price" ); require( int128(buyer.balance) >= price, "GraffitETH2: buyer cannot afford pixel" ); // reduce buyer's balance and increase buyer's tax base buyer = _decreaseBalance(buyer, price); buyer = _increaseTaxBase(buyer, argss[i].newPrice); address sellerAddress; if (_exists(argss[i].pixelID)) { sellerAddress = ownerOf(argss[i].pixelID); require( sellerAddress != buyerAddress, "GraffitETH2: buyer and seller are the same" ); Account memory seller; // Find seller account in sellers array by iterating over it. We should use a // mapping here, but solidity doesn't support mappings in memory. uint256 sellerIndex; for (sellerIndex = 0; sellerIndex < numSellers; sellerIndex++) { if (sellerAddresses[sellerIndex] == sellerAddress) { seller = sellers[sellerIndex]; break; } } assert(sellerIndex <= numSellers); if (sellerIndex == numSellers) { // Seller account is not in sellers array yet, so take it from state and add it // to the array. numSellers++; seller = _accounts[sellerAddress]; sellerAddresses[sellerIndex] = sellerAddress; // Pay tax for seller so that we can safely update its balance and tax base. // We only have to do this once per seller as no time passes during execution // and thus no new tax debt accumulates. (seller, taxesPaid) = _payMoreTaxes(seller, taxesPaid); } // update seller balance and tax base uint64 oldPrice = _pixelPrices[argss[i].pixelID]; (seller, taxesPaid) = _increaseBalance( seller, price, taxesPaid ); seller = _decreaseTaxBase(seller, oldPrice); sellers[sellerIndex] = seller; // perform transfer _earmark(argss[i].pixelID, sellerAddress, address(0), 0); // cancel any earmark _transfer(sellerAddress, buyerAddress, argss[i].pixelID); } else { sellerAddress = address(0); initialSaleRevenue = ClampedMath.addUint64( initialSaleRevenue, price ); require( argss[i].pixelID <= _maxPixelID, "GraffitETH2: max pixel ID exceeded" ); _mint(buyerAddress, argss[i].pixelID); // create the pixel } // update nominal price _pixelPrices[argss[i].pixelID] = argss[i].newPrice; emit Bought({ pixelID: argss[i].pixelID, seller: sellerAddress, buyer: buyerAddress, price: price }); emit ColorChanged({ pixelID: argss[i].pixelID, owner: buyerAddress, color: argss[i].color }); emit PriceChanged({ pixelID: argss[i].pixelID, owner: buyerAddress, price: argss[i].newPrice }); } // persist account changes, taxes paid, and initial sale revenue _accounts[buyerAddress] = buyer; assert(sellerAddresses.length == sellers.length); for (uint256 i = 0; i < sellerAddresses.length; i++) { address sellerAddress = sellerAddresses[i]; _accounts[sellerAddress] = sellers[i]; } _totalTaxesPaid = ClampedMath.addUint64(_totalTaxesPaid, taxesPaid); _totalInitialSaleRevenue = ClampedMath.addUint64( _totalInitialSaleRevenue, initialSaleRevenue ); } function _setColorMany(address sender, SetColorArgs[] memory argss) internal { for (uint256 i = 0; i < argss.length; i++) { uint256 pixelID = argss[i].pixelID; uint8 newColor = argss[i].newColor; require(_exists(pixelID), "GraffitETH2: pixel does not exist"); address owner = ownerOf(pixelID); require( _isApprovedOrOwner(sender, pixelID), "GraffitETH2: only pixel owner or approved account can set color" ); emit ColorChanged({ pixelID: pixelID, owner: owner, color: newColor }); } } function _setPriceMany(address sender, SetPriceArgs[] memory argss) internal { if (argss.length == 0) { return; } address accountAddress; Account memory account; uint64 taxesPaid; for (uint256 i = 0; i < argss.length; i++) { uint256 pixelID = argss[i].pixelID; uint64 newPrice = argss[i].newPrice; require(_exists(pixelID)); address owner = ownerOf(pixelID); require( _isApprovedOrOwner(sender, pixelID), "GraffitETH2: only pixel owner or approved account can set price" ); if (i == 0) { accountAddress = owner; account = _accounts[owner]; (account, taxesPaid) = _payTaxes(account); } else { // To keep the code simple, all pixels need to be owned by the same account. // Otherwise, we'd have to keep a list of updated accounts in memory instead of // just a single one, similar to what the buy function does. It's unlikely that // someone will want to change the price of pixels owned by two or more different // accounts (possible via one or more approvals), so we can live with it. require( owner == accountAddress, "GraffitETH2: pixels owned by different accounts" ); } uint64 oldPrice = _pixelPrices[pixelID]; account = _decreaseTaxBase(account, oldPrice); account = _increaseTaxBase(account, newPrice); _pixelPrices[pixelID] = newPrice; emit PriceChanged({ pixelID: pixelID, owner: owner, price: newPrice }); } _totalTaxesPaid = ClampedMath.addUint64(_totalTaxesPaid, taxesPaid); _accounts[accountAddress] = account; } function _depositTo(address depositor, address account) internal { if (msg.value == 0) { return; } Account memory acc = _accounts[account]; uint64 taxesPaid; (acc, taxesPaid) = _payTaxes(acc); require( msg.value % (1 gwei) == 0, "GraffitETH2: deposit amount must be multiple of 1 GWei" ); uint256 valueGWei = msg.value / (1 gwei); require( valueGWei <= type(uint64).max, "GraffitETH2: max deposit amount exceeded" ); uint64 amount = uint64(valueGWei); (acc, taxesPaid) = _increaseBalance(acc, amount, taxesPaid); _accounts[account] = acc; _totalTaxesPaid = ClampedMath.addUint64(_totalTaxesPaid, taxesPaid); emit Deposited({ account: account, depositor: depositor, amount: amount, balance: acc.balance }); } function _withdrawMax( address sender, address account, address receiver ) internal { int64 balance = getBalance(account); require( balance >= 0, "GraffitETH2: account balance must not be negative" ); assert(int128(balance) <= type(uint64).max); uint64 amount = uint64(balance); _withdraw(sender, account, amount, receiver); } function _withdraw( address sender, address account, uint64 amount, address receiver ) internal { require( sender == account || isApprovedForAll(account, sender), "GraffitETH2: sender not allowed to withdraw" ); Account memory acc = _accounts[account]; uint64 taxesPaid; (acc, taxesPaid) = _payTaxes(acc); require( int128(acc.balance) >= amount, "GraffitETH2: cannot withdraw more than balance" ); acc = _decreaseBalance(acc, amount); _accounts[account] = acc; _totalTaxesPaid = ClampedMath.addUint64(_totalTaxesPaid, taxesPaid); uint256 transferValue = uint256(amount) * (1 gwei); assert(transferValue / (1 gwei) == amount); (bool success, ) = receiver.call{value: transferValue}(""); require(success, "GraffitETH2: withdraw call reverted"); emit Withdrawn({ account: account, receiver: receiver, amount: amount, balance: acc.balance }); } /// @dev Earmarks a pixel. The caller should check that the pixel exists and that the current /// owner or an approved account requested the earmarking. function _earmark( uint256 pixelID, address owner, address receiver, uint64 amount ) internal { _earmarks[pixelID] = Earmark({receiver: receiver, amount: amount}); emit Earmarked({ pixelID: pixelID, owner: owner, receiver: receiver, amount: amount }); } function _withdrawOwner(uint64 amount, address receiver) internal { uint64 maxAmount = getOwnerWithdrawableAmount(); require( amount <= maxAmount, "GraffitETH2: not enough funds to withdraw" ); _totalWithdrawnByOwner = ClampedMath.addUint64( _totalWithdrawnByOwner, amount ); uint256 transferValue = uint256(amount) * (1 gwei); assert(transferValue <= address(this).balance); assert(transferValue / (1 gwei) == amount); (bool success, ) = receiver.call{value: transferValue}(""); require(success, "GraffitETH2: withdraw taxes call reverted"); emit TaxWithdrawn({amount: amount, receiver: receiver}); } function _claim( address claimer, uint256 pixelID, uint64 maxPrice, uint64 minAmount ) internal { require(_exists(pixelID), "GraffitETH2: pixel does not exist"); address owner = ownerOf(pixelID); Earmark memory em = _earmarks[pixelID]; require( claimer == em.receiver, "GraffitETH2: account not allowed to claim pixel" ); uint64 taxesPaid = 0; Account memory sender = _accounts[owner]; Account memory receiver = _accounts[claimer]; (sender, taxesPaid) = _payMoreTaxes(sender, taxesPaid); (receiver, taxesPaid) = _payMoreTaxes(receiver, taxesPaid); uint64 price = getNominalPrice(pixelID); require(price <= maxPrice, "GraffitETH2: pixel is too expensive"); sender = _decreaseTaxBase(sender, price); receiver = _increaseTaxBase(receiver, price); // Transfer min(balance, em.amount) from owner to claimer, but only if it exceeds // minAmount. uint64 amount; if (int128(sender.balance) >= em.amount) { amount = em.amount; } else { if (sender.balance >= 0) { assert(int128(sender.balance) <= type(uint64).max); // balance < em.amount <= uint64.max amount = uint64(sender.balance); } else { amount = 0; } } require(amount >= minAmount, "GraffitETH2: amount is too small"); sender = _decreaseBalance(sender, amount); (receiver, taxesPaid) = _increaseBalance(receiver, amount, taxesPaid); _accounts[owner] = sender; _accounts[claimer] = receiver; _totalTaxesPaid = ClampedMath.addUint64(_totalTaxesPaid, taxesPaid); _transfer(owner, claimer, pixelID); _earmark(pixelID, owner, address(0), 0); emit PixelClaimed({ pixelID: pixelID, oldOwner: owner, newOwner: claimer, amount: amount }); } // // Transfer overrides from ERC721 // function transferFrom( address, address, uint256 ) public virtual override { assert(false); // transferring pixels is not possible } function safeTransferFrom( address, address, uint256 ) public virtual override { assert(false); // transferring pixels is not possible } function safeTransferFrom( address, address, uint256, bytes memory ) public virtual override { assert(false); // transferring pixels is not possible } } library ClampedMath { function addUint64(uint64 a, uint64 b) internal pure returns (uint64) { uint64 res; if (a <= type(uint64).max - b) { res = a + b; } else { res = type(uint64).max; } assert(res >= a && res >= b); assert(res <= uint256(a) + uint256(b)); return res; } function subUint64(uint64 a, uint64 b) internal pure returns (uint64) { uint64 res; if (a >= b) { res = a - b; } else { res = 0; } assert(res <= a); return res; } function addInt64(int64 a, uint64 b) internal pure returns (int64) { int256 resExact = int256(a) + b; int64 res; if (resExact > type(int64).max) { res = type(int64).max; } else { assert(resExact >= type(int64).min); res = int64(resExact); } assert(res >= a); return res; } function subInt64(int64 a, uint64 b) internal pure returns (int64) { int256 resExact = int256(a) - b; int64 res; if (resExact < type(int64).min) { res = type(int64).min; } else { assert(resExact <= type(int64).max); res = int64(resExact); } assert(res <= a); return res; } } library Taxes { function computeTaxes( uint256 taxRateNumerator, uint256 taxRateDenominator, uint64 taxBase, uint64 startTime, uint64 endTime ) internal pure returns (uint64) { if (endTime <= startTime) { return 0; } // This doesn't overflow because each of the terms is smaller than a uint64. For the // numerator, this is ensured by the constructor of the GraffitETH2 contract. uint256 num = uint256(endTime - startTime) * uint256(taxBase) * taxRateNumerator; uint256 taxes = num / taxRateDenominator; assert(taxes <= num); uint64 res; if (taxes <= type(uint64).max) { res = uint64(taxes); } else { res = type(uint64).max; } assert(res == taxes || (taxes > res && res == type(uint64).max)); return res; } function payTaxes( Account memory acc, uint256 taxRateNumerator, uint256 taxRateDenominator, uint64 taxStartTime ) internal view returns (Account memory, uint64) { uint64 startTime = acc.lastTaxPayment; if (startTime < taxStartTime) { startTime = taxStartTime; } uint64 unaccountedTaxes = computeTaxes( taxRateNumerator, taxRateDenominator, acc.taxBase, startTime, uint64(block.timestamp) ); // Compute the taxes that are actually paid. This is usually just `unaccountedTax`, unless // the account cannot afford it in part or in full. uint64 taxesPaid; if (int128(acc.balance) >= unaccountedTaxes) { taxesPaid = unaccountedTaxes; } else if (acc.balance >= 0) { assert(int128(acc.balance) <= type(uint64).max); // balance < unaccountedTaxes <= uint64.max taxesPaid = uint64(acc.balance); } else { taxesPaid = 0; } assert(taxesPaid <= unaccountedTaxes); assert( (acc.balance >= 0 && taxesPaid <= int128(acc.balance)) || (acc.balance < 0 && taxesPaid == 0) ); // Update the account record acc.balance = ClampedMath.subInt64(acc.balance, unaccountedTaxes); assert(block.timestamp >= acc.lastTaxPayment); acc.lastTaxPayment = uint64(block.timestamp); acc.totalTaxesPaid = ClampedMath.addUint64( acc.totalTaxesPaid, taxesPaid ); return (acc, taxesPaid); } function payMoreTaxes( Account memory acc, uint64 taxesPaid, uint256 taxRateNumerator, uint256 taxRateDenominator, uint64 taxStartTime ) internal view returns (Account memory, uint64) { uint64 addedTaxes; (acc, addedTaxes) = payTaxes( acc, taxRateNumerator, taxRateDenominator, taxStartTime ); taxesPaid = ClampedMath.addUint64(taxesPaid, addedTaxes); return (acc, taxesPaid); } }
Check if the rug pull safety hatch is disabled or not.
function checkRugPullDisabled() public view returns (bool) { return _rugPullDisabled; }
12,773,059
./partial_match/4/0x3461C7C1114c49eed3b54Df5BcFecbA21D29782A/sources/JAMACPool.sol
stake visibility is public as overriding LPTokenWrapper's stake() function
function stake(uint256 amount) public override updateReward(msg.sender) checkStart { require(amount > 0, 'JAMACPool: Cannot stake 0'); uint256 newDeposit = deposits[msg.sender].add(amount); require( newDeposit <= 20000e18, 'JAMACPool: deposit amount exceeds maximum 20000' ); deposits[msg.sender] = newDeposit; super.stake(amount); emit Staked(msg.sender, amount); }
8,561,378
/** *Submitted for verification at Etherscan.io on 2022-02-22 */ // █▄▄ █▀▀ ▀█▀ █░█ █▀▀ █▀█ █▀ █▀▀ // █▄█ ██▄ ░█░ ▀▄▀ ██▄ █▀▄ ▄█ ██▄ // website : https://www.betverse.finance/ // telegram : https://t.me/BetVerseEntryPortal // twitter : https://twitter.com/BetVerse_ // gitbook : https://betverse.gitbook.io/betverse/ // email : [email protected] /** *Submitted for verification at Etherscan.io & Contract Audit on 2022-02-22 */ // Sources flattened with hardhat v2.4.0 https://hardhat.org // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File @openzeppelin/contracts/utils/math/[email protected] pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * 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" ); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender] + addedValue ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require( currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero" ); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require( senderBalance >= amount, "ERC20: transfer amount exceeds balance" ); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: value}( data ); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall( target, data, "Address: low-level delegate call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/utils/[email protected] pragma solidity ^0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library 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" ); } } } // File contracts/interfaces/IUniswapRouter01.sol pragma solidity >=0.8.0; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // File contracts/interfaces/IUniswapRouter02.sol pragma solidity >=0.8.0; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } // File contracts/interfaces/IUniswapV2Factory.sol pragma solidity >=0.8.0; interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function setReflectionFeeTo(address) external; function setReflectionFeeToSetter(address) external; } pragma solidity >=0.8.0; contract BetVerse is ERC20("BetVerse", "BTVS"), Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; uint256 public constant MAX_SUPPLY = 10000000000 * 1e18; // 10B max supply uint16 private MAX_BP_RATE = 10000; uint16 private extraLottoTaxRate = 100; uint16 private extraLottoSellTaxRate = 200; uint16 private devTaxRate = 300; uint16 private devSellTaxRate = 300; uint16 private burnTaxRate = 100; uint16 private marketingTaxRate = 600; uint16 private marketingSellTaxRate = 800; uint16 private passiveIncomeRewardTaxRate = 500; uint256 public maxTransferAmountRate = 100; uint256 public maxWalletBPS = 200; uint256 public totalDividends; uint256 public increasedDividends; uint256 public orgMarketingRate = 600; uint256 public orgDevRate = 300; uint256 public orgLottoRate = 100; uint256 public claimablePeriod = 43200 seconds; address public deadAddress = 0x000000000000000000000000000000000000dEaD; IUniswapV2Router02 public uniswapRouter; // The trading pair address public uniswapPair; address public marketingWallet = 0x6A94a0bC84Bf5451D77B7EcA76f8f86a79b5F979; address public devWallet = 0x8092193FAB239Ced952A5452cDdFA4699a7CAd1b; // In swap and withdraw bool private _inSwapAndWithdraw; // The operator can only update the transfer tax rate address private _operator; // Automatic swap and liquify enabled bool public swapAndWithdrawEnabled = false; mapping(address => bool) private _isExcludedFromFee; mapping(address => bool) private _isExcludedFromMaxTx; mapping(address => bool) private _isExcludedFromMaxWallet; mapping (address => bool) private botWallets; bool botscantrade = false; bool private _tradingOpen = false; string public WEBSITE = "https://www.betverse.finance/"; string public TELEGRAM = "https://t.me/BetVerseEntryPortal"; string public TWITTER = "https://twitter.com/BetVerse_"; struct CoinTypeInfo { address coinAddress; address[] routerPath; } mapping(address => uint256) public claimed; // claimed amount by user mapping(address => uint256) public dividendsWhenClaim; // dividend amount when user are claiming mapping(address => uint256) public dividendsClaimableTimestamp; // storing the dividends claimable timestamp CoinTypeInfo[] public coins; modifier onlyOperator() { require(_operator == msg.sender, "!operator"); _; } modifier lockTheSwap() { _inSwapAndWithdraw = true; _; _inSwapAndWithdraw = false; } modifier transferTaxFree() { uint16 _extraLottoTaxRate = extraLottoTaxRate; uint16 _extraLottoSellTaxRate = extraLottoSellTaxRate; uint16 _burnTaxRate = burnTaxRate; uint16 _devTaxRate = devTaxRate; uint16 _devSellTaxRate = devSellTaxRate; uint16 _marketingTaxRate = marketingTaxRate; uint16 _marketingSellTaxRate = marketingSellTaxRate; uint16 _passiveIncomeRewardTaxRate = passiveIncomeRewardTaxRate; extraLottoTaxRate = 0; extraLottoSellTaxRate = 0; burnTaxRate = 0; devTaxRate = 0; devSellTaxRate = 0; marketingTaxRate = 0; marketingSellTaxRate = 0; passiveIncomeRewardTaxRate = 0; _; extraLottoTaxRate = _extraLottoTaxRate; extraLottoSellTaxRate = _extraLottoSellTaxRate; burnTaxRate = _burnTaxRate; devTaxRate = _devTaxRate; devSellTaxRate = _devSellTaxRate; marketingTaxRate = _marketingTaxRate; marketingSellTaxRate = _marketingSellTaxRate; passiveIncomeRewardTaxRate = _passiveIncomeRewardTaxRate; } constructor() { _operator = msg.sender; _mint(msg.sender, MAX_SUPPLY); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); // Create a uniswap pair for this new token uniswapPair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair( address(this), _uniswapV2Router.WETH() ); // set the rest of the contract variables uniswapRouter = _uniswapV2Router; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[msg.sender] = true; _isExcludedFromMaxTx[address(this)] = true; _isExcludedFromMaxTx[msg.sender] = true; _isExcludedFromMaxTx[deadAddress] = true; _isExcludedFromMaxWallet[address(this)] = true; _isExcludedFromMaxWallet[msg.sender] = true; } /** * @dev Returns the address of the current operator. */ function operator() public view returns (address) { return _operator; } /// @notice Burns `_amount` token fromo `_from`. Must only be called by the owner. function burn(address _from, uint256 _amount) public onlyOwner { _burn(_from, _amount); } function _transfer( address _sender, address _recepient, uint256 _amount ) internal override { require( _tradingOpen || _sender == owner() || _recepient == owner() || _sender == address(uniswapRouter), "!tradable" ); if(botWallets[_sender] || botWallets[_recepient]){ require(botscantrade, "bots arent allowed to trade"); } if ( swapAndWithdrawEnabled == true && _inSwapAndWithdraw == false && address(uniswapRouter) != address(0) && uniswapPair != address(0) && _sender != uniswapPair && _sender != address(uniswapRouter) && _sender != owner() && _sender != address(this) ) { swapAndWithdraw(); } uint256 _maxWallet = (totalSupply() * maxWalletBPS) / MAX_BP_RATE; uint256 _maxTxAmount = (totalSupply() * maxTransferAmountRate) / MAX_BP_RATE; require( _amount <= _maxTxAmount || _isExcludedFromMaxTx[_sender], "TX Limit Exceeded" ); if ( _sender != owner() && _recepient != address(this) && _recepient != address(deadAddress) && _recepient != uniswapPair ) { uint256 currentBalance = balanceOf(_recepient); require( _isExcludedFromMaxWallet[_recepient] || (currentBalance + _amount <= _maxWallet), "Max Wallet Limit Exceeded" ); } if (_isExcludedFromFee[_sender]) { super._transfer(_sender, _recepient, _amount); } else { uint256 extraLottoFee = _amount.mul(extraLottoTaxRate).div( MAX_BP_RATE ); uint256 extraLottoSellFee = _amount.mul(extraLottoSellTaxRate).div( MAX_BP_RATE ); uint256 burnFee = _amount.mul(burnTaxRate).div(MAX_BP_RATE); uint256 devFee = _amount.mul(devTaxRate).div(MAX_BP_RATE); uint256 devSellFee = _amount.mul(devSellTaxRate).div(MAX_BP_RATE); uint256 marketingFee = _amount.mul(marketingTaxRate).div( MAX_BP_RATE ); uint256 marketingSellFee = _amount.mul(marketingSellTaxRate).div( MAX_BP_RATE ); uint256 passiveIncomeRewardFee = _amount .mul(passiveIncomeRewardTaxRate) .div(MAX_BP_RATE); uint256 sellTotalFee = extraLottoSellFee + burnFee + devSellFee + marketingSellFee + passiveIncomeRewardFee; uint256 buyTotalFee = extraLottoFee + burnFee + devFee + marketingFee + passiveIncomeRewardFee; if (uniswapPair == _recepient) { if (_amount == balanceOf(_sender)){ setClaimableTimestamp(_sender, 0); } _amount = _amount.sub(sellTotalFee); super._transfer(_sender, _recepient, _amount); super._transfer(_sender, address(this), extraLottoSellFee); super._transfer(_sender, deadAddress, burnFee); super._transfer(_sender, address(this), devSellFee); super._transfer(_sender, address(this), marketingSellFee); super._transfer(_sender, address(this), passiveIncomeRewardFee); } else { _amount = _amount.sub(buyTotalFee); super._transfer(_sender, _recepient, _amount); super._transfer(_sender, address(this), extraLottoFee); super._transfer(_sender, deadAddress, burnFee); super._transfer(_sender, address(this), devFee); super._transfer(_sender, address(this), marketingFee); super._transfer(_sender, address(this), passiveIncomeRewardFee); if (claimableTimestamp(_recepient) == 0) { setClaimableTimestamp(_recepient, block.timestamp.add(claimablePeriod)); } } totalDividends = totalDividends.add(passiveIncomeRewardFee); increasedDividends = increasedDividends.add(passiveIncomeRewardFee); } } function setClaimableTimestamp(address addr, uint256 timestamp) internal { dividendsClaimableTimestamp[addr] = timestamp; } function claimableTimestamp(address addr) public view returns (uint256) { return dividendsClaimableTimestamp[addr]; } /** * @dev Transfers operator of the contract to a new account (`newOperator`). * Can only be called by the current operator. */ function transferOperator(address newOperator) public onlyOperator { require(newOperator != address(0)); _operator = newOperator; } /** * @dev Update the swap router. * Can only be called by the current operator. */ function updateUniswapRouter(address _router) public onlyOwner { uniswapRouter = IUniswapV2Router02(_router); uniswapPair = IUniswapV2Factory(uniswapRouter.factory()).getPair( address(this), uniswapRouter.WETH() ); require(uniswapPair != address(0)); } /** * @dev Update the swapAndWithdrawEnabled. * Can only be called by the current operator. */ function updateSwapAndLiquifyEnabled(bool _enabled) public onlyOperator { swapAndWithdrawEnabled = _enabled; } function manualSwap() external onlyOperator { swapAndWithdraw(); } function manualWithdraw() external onlyOperator { uint256 totalPercentage = devTaxRate + marketingTaxRate + extraLottoTaxRate; uint256 bal = address(this).balance; uint256 balForMarketing = bal.mul(orgMarketingRate).div( totalPercentage ); uint256 balFordev = bal.mul(orgDevRate).div(totalPercentage); uint256 balForExtraLotto = bal.mul(orgLottoRate).div(totalPercentage); payable(marketingWallet).transfer(balForMarketing + balForExtraLotto); payable(devWallet).transfer(balFordev); } /// @dev Swap and liquify function swapAndWithdraw() private lockTheSwap transferTaxFree { uint256 contractTokenBalance = balanceOf(address(this)); uint256 totalPercentage = orgMarketingRate + orgDevRate + orgLottoRate; if (contractTokenBalance > totalDividends) { contractTokenBalance = contractTokenBalance.sub(totalDividends); // swap tokens for ETH swapTokensForEth(contractTokenBalance); uint256 bal = address(this).balance; uint256 balForMarketing = bal.mul(orgMarketingRate).div( totalPercentage ); uint256 balFordev = bal.mul(orgDevRate).div(totalPercentage); uint256 balForExtraLotto = bal.mul(orgLottoRate).div( totalPercentage ); payable(marketingWallet).transfer(balForMarketing + balForExtraLotto); payable(devWallet).transfer(balFordev); } } /// @dev Swap tokens for eth function swapTokensForEth(uint256 tokenAmount) private { // generate the pantherSwap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapRouter.WETH(); _approve(address(this), address(uniswapRouter), tokenAmount); // make the swap uniswapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp + 1 days ); } function updateFees( uint16 _passiveIncomeRate, uint16 _extraLottoTaxRate, uint16 _extraLottoSellTaxRate, uint16 _burnTaxRate, uint16 _devTaxRate, uint16 _devSellTaxRate, uint16 _marketingTaxRate, uint16 _marketingSellTaxRate ) external onlyOwner { require( _passiveIncomeRate + _devTaxRate + _marketingTaxRate <= MAX_BP_RATE, "!values" ); passiveIncomeRewardTaxRate = _passiveIncomeRate; extraLottoTaxRate = _extraLottoTaxRate; extraLottoSellTaxRate = _extraLottoSellTaxRate; burnTaxRate = _burnTaxRate; devTaxRate = _devTaxRate; devSellTaxRate = _devSellTaxRate; marketingTaxRate = _marketingTaxRate; marketingSellTaxRate = _marketingSellTaxRate; } function updateIncentiveFees() external onlyOperator { passiveIncomeRewardTaxRate = 300; extraLottoTaxRate = 100; extraLottoSellTaxRate = 200; burnTaxRate = 100; devTaxRate = 200; devSellTaxRate = 300; marketingTaxRate = 400; marketingSellTaxRate = 600; } function updateIncentiveTxMaxWalletAmount() external onlyOperator { maxTransferAmountRate = 400; maxWalletBPS = 400; } function updateIncentiveSuperTxAmount() external onlyOperator { maxTransferAmountRate = 10000; maxWalletBPS = 10000; } function setMaxTransferAmountRate(uint16 _maxTransferAmountRate) external onlyOwner { require(_maxTransferAmountRate <= MAX_BP_RATE); maxTransferAmountRate = _maxTransferAmountRate; } function openTrading() external onlyOwner { _tradingOpen = true; swapAndWithdrawEnabled = true; } function addBotWallet(address botwallet) external onlyOwner() { botWallets[botwallet] = true; } function removeBotWallet(address botwallet) external onlyOwner() { botWallets[botwallet] = false; } function getBotWalletStatus(address botwallet) public view returns (bool) { return botWallets[botwallet]; } function isExcludedFromFee(address _addr) external view returns (bool) { return _isExcludedFromFee[_addr]; } function setClaimablePeriod(uint256 _period) external onlyOperator { claimablePeriod = _period; } function excludeFromFee(address _addr, bool _is) external onlyOperator { _isExcludedFromFee[_addr] = _is; } function isExcludedFromMaxTx(address _addr) external view returns (bool) { return _isExcludedFromMaxTx[_addr]; } function excludeFromMaxTx(address _addr, bool _is) external onlyOperator { _isExcludedFromMaxTx[_addr] = _is; } function excludeFromMaxWallet(address account, bool excluded) public onlyOperator { _isExcludedFromMaxWallet[account] = excluded; } function isExcludedFromMaxWallet(address account) public view returns (bool) { return _isExcludedFromMaxWallet[account]; } function setMaxWalletBPS(uint256 bps) external onlyOwner { require( bps >= 175 && bps <= 10000, "BPS must be between 175 and 10000" ); maxWalletBPS = bps; } function withdrawDividends(uint16 _cId) external { require( dividendsClaimableTimestamp[msg.sender] <= block.timestamp, "withdraw timestamp : not good" ); if (totalDividends <= balanceOf(address(this))) { uint256 withdrawable = withdrawableDividends(msg.sender); require(withdrawable > 0, "not enough to claim"); CoinTypeInfo storage coin = coins[_cId]; if (_cId == 0) { // if withdrawing token, reinvest transfer(msg.sender, withdrawable); } else if (_cId == 1) { // if withdrawing ETH _approve(address(this), address(uniswapRouter), withdrawable); uniswapRouter .swapExactTokensForETHSupportingFeeOnTransferTokens( withdrawable, 0, coin.routerPath, msg.sender, block.timestamp.add(300) ); } else { // if withdrawing other coins _approve(address(this), address(uniswapRouter), withdrawable); uniswapRouter .swapExactTokensForTokensSupportingFeeOnTransferTokens( withdrawable, 0, coin.routerPath, msg.sender, block.timestamp.add(300) ); } claimed[msg.sender] = claimed[msg.sender].add(withdrawable); dividendsWhenClaim[msg.sender] = increasedDividends; totalDividends = totalDividends.sub(withdrawable); dividendsClaimableTimestamp[msg.sender] = block.timestamp.add(claimablePeriod); } } function withdrawableDividends(address _user) public view returns (uint256) { uint256 holdingAmount = balanceOf(_user); uint256 soldAmount = tokenAmountSold(); if (soldAmount == 0) { return 0; } uint256 availableAmount = increasedDividends.sub( dividendsWhenClaim[_user] ); if (availableAmount > 0) { uint256 brut = availableAmount.mul(holdingAmount).div(soldAmount); if (brut > totalDividends) { return totalDividends; } else { return brut; } } return 0; } function tokenAmountSold() private view returns (uint256) { uint256 tokenBalanceInLp = balanceOf(uniswapPair); uint256 soldAmount = totalSupply().sub(tokenBalanceInLp); return soldAmount; } function addCoinInfo(address[] memory _path, address _coinAddr) external onlyOperator { coins.push(CoinTypeInfo({coinAddress: _coinAddr, routerPath: _path})); } function updateCoinInfo( uint8 _cId, address[] memory _path, address _coinAddr ) external onlyOperator { CoinTypeInfo storage coin = coins[_cId]; coin.routerPath = _path; coin.coinAddress = _coinAddr; } mapping(address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,uint256 chainId,address verifyingContract)" ); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", domainSeparator, structHash) ); address signatory = ecrecover(digest, v, r, s); require( signatory != address(0), "VERSE::delegateBySig: invalid signature" ); require( nonce == nonces[signatory]++, "VERSE::delegateBySig: invalid nonce" ); require( block.timestamp <= expiry, "VERSE::delegateBySig: signature expired" ); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) { require( blockNumber < block.number, "BETVERSE::getPriorVotes: not yet determined" ); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying verse (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32( block.number, "VERSE::_writeCheckpoint: block number exceeds 32 bits" ); if ( nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber ) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint( blockNumber, newVotes ); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal view returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } receive() external payable {} }
Update the swap router. Can only be called by the current operator./
function updateUniswapRouter(address _router) public onlyOwner { uniswapRouter = IUniswapV2Router02(_router); uniswapPair = IUniswapV2Factory(uniswapRouter.factory()).getPair( address(this), uniswapRouter.WETH() ); require(uniswapPair != address(0)); }
1,970,712
pragma solidity ^0.4.16; interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract Rubid { // Public variables of the token string public name = "Rubid"; string public symbol = "RBD"; uint8 public decimals = 18; // 18 decimals is the strongly suggested default uint256 public totalSupply; uint256 public RubidSupply = 400000000000; uint256 public buyPrice = 150000000; address public creator; // 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); event FundTransfer(address backer, uint amount, bool isContribution); /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ function Rubid() public { totalSupply = RubidSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; // Give RubidCoin Mint the total created tokens creator = msg.sender; } /** * 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]); // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); } /** * 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); } /// @notice Buy tokens from contract by sending ether function () payable internal { uint amount = msg.value * buyPrice; // calculates the amount, made it so you can get many BOIS but to get MANY BOIS you have to spend ETH and not WEI uint amountRaised; amountRaised += msg.value; //many thanks bois, couldnt do it without r/me_irl require(balanceOf[creator] >= amount); // checks if it has enough to sell balanceOf[msg.sender] += amount; // adds the amount to buyer&#39;s balance balanceOf[creator] -= amount; // sends ETH to RubidCoinMint Transfer(creator, msg.sender, amount); // execute an event reflecting the change creator.transfer(amountRaised); } }
Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
function Rubid() public { creator = msg.sender; }
8,009,115
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; import "./OwnerManager.sol"; import "./IBPool.sol"; import "./interfaces/IERC20.sol"; contract Ballot is OwnerManager { enum ProposalType { addOwner, removeOwner } enum ProposalStatus { closed, open } struct Proposal { ProposalType proposalType; address owner; uint votes; ProposalStatus proposalStatus; } event ProposalAdded (uint index, uint proposalType, address target); modifier onlyStaker() { require(stakes[msg.sender] != 0, "B2"); _; } modifier activeProposal(uint _index) { require(proposals[_index].owner != address(0), "B3"); require(proposals[_index].proposalStatus == ProposalStatus.open, "B3"); _; } IERC20 internal bPool; uint constant public MAX_INT = type(uint).max; uint public numberProposals; mapping(address => uint) public stakes; mapping(address => uint[]) public votes; mapping(uint => Proposal) public proposals; constructor(address _bPool) { bPool = IERC20(_bPool); } /// @dev Allows to stake all liquidity provider (LP) tokens from the balancer pool. /// Without staking voting/proposing is not possible. /// This contract must have been approved with the balancer pool first. /// @notice Updates the caller's stakes. function stake() public { uint allowance = bPool.allowance(msg.sender, address(this)); require(allowance == MAX_INT, "B1"); uint stakerBalance = bPool.balanceOf(msg.sender); bPool.transferFrom(msg.sender, address(this), stakerBalance); stakes[msg.sender] = stakerBalance; } /// @dev Allows to unstake LP tokens. /// Triggers removal of outstanding votes to avoid double voting. /// @notice Updates the caller's stakes. Removes caller's votes from open proposals. function unstake() public onlyStaker { bPool.transfer(msg.sender, stakes[msg.sender]); uint[] memory openVotes = votes[msg.sender]; for (uint i = 0; i < openVotes.length; i++) { if (proposals[openVotes[i]].proposalStatus == ProposalStatus.open) { proposals[openVotes[i]].votes -= stakes[msg.sender]; } } stakes[msg.sender] = 0; votes[msg.sender] = new uint[](0); } /// @dev Allows to add a new proposal about adding or removing owner. /// The proposer automatically votes on her proposal. /// @notice Updates proposals. Updates the total number of proposals. function addProposal(uint _type, address _target) public onlyStaker { require(_target != address(0), "B4"); Proposal memory proposal = Proposal( ProposalType(_type), _target, 0, ProposalStatus.open ); emit ProposalAdded(numberProposals, _type, _target); proposals[numberProposals] = proposal; vote(numberProposals); numberProposals++; } /// @dev Allows to vote on a proposal. /// If majority is reached (votes > half of total supply of LP tokens) proposal is executed. /// @notice Updates votes on a proposal. Marks that voter has voted for a proposal (= update to votes) function vote(uint _index) public onlyStaker activeProposal(_index) { require(!hasAlreadyVoted(_index), "B5"); proposals[_index].votes += stakes[msg.sender]; if (isMajorityVote(_index)) { executeProposal(_index); } else { votes[msg.sender].push(_index); } } /// @dev Checks if voter has already voted on proposal. /// If majority is reached (votes > half of total supply of LP tokens) proposal is executed. /// @return Returns true if attempted double vote. function hasAlreadyVoted(uint _index) internal view returns(bool) { for (uint i = 0; i < votes[msg.sender].length; i++) { if (votes[msg.sender][i] == _index) { return true; } } return false; } /// @dev Checks if a majority of LP token holders has voted for proposal. /// @return Returns true if majority is reached. function isMajorityVote(uint _index) public view returns(bool){ uint total = bPool.totalSupply(); return proposals[_index].votes * 2 > total; } /// @dev Adds or removes an owner as specified by the accepted proposal. /// Is public to enable external triggering of execution. /// This is important when majority ratios of Liquidity Pool have changed. /// E.g. a major LP leaves the pool, so that a majority for a proposal is suddenly reached. /// @notice Sets the proposal status to closed. function executeProposal(uint _index) public { require(isMajorityVote(_index), "B6"); uint newSafeThreshold = newMultiSigThreshold(proposals[_index].proposalType); address elected = proposals[_index].owner; if (proposals[_index].proposalType == ProposalType.addOwner) { addOwnerWithThreshold(elected, newSafeThreshold); } else { address[] memory currentOwners = getOwners(); address prevOwner = SENTINEL_OWNERS; address owner; for (uint i; i < currentOwners.length; i++) { if (currentOwners[i] == proposals[_index].owner) { owner = currentOwners[i]; if(i != 0) { prevOwner = currentOwners[i - 1]; } } } removeOwner(prevOwner, owner, newSafeThreshold); } proposals[_index].proposalStatus = ProposalStatus.closed; } /// @dev Calculates the threshold for the multisig contract /// Makes sure that the threshold is always just above 50%. /// @return The smallest possible majority threshold. function newMultiSigThreshold(ProposalType _proposalType) internal view returns(uint) { uint nextOwnerCount; uint nextThreshold = threshold; if (_proposalType == ProposalType.addOwner) { nextOwnerCount = ownerCount + 1; if (threshold * 2 <= nextOwnerCount) { nextThreshold++; } } else if (_proposalType == ProposalType.removeOwner) { nextOwnerCount = ownerCount - 1; if ((threshold - 1) * 2 > nextOwnerCount) { nextThreshold--; } } require(nextOwnerCount > 0, "B7"); return nextThreshold; } }
Allows to stake all liquidity provider (LP) tokens from the balancer pool. Without staking voting/proposing is not possible. This contract must have been approved with the balancer pool first. Updates the caller's stakes.
function stake() public { uint allowance = bPool.allowance(msg.sender, address(this)); require(allowance == MAX_INT, "B1"); uint stakerBalance = bPool.balanceOf(msg.sender); bPool.transferFrom(msg.sender, address(this), stakerBalance); stakes[msg.sender] = stakerBalance; }
1,832,884
./full_match/4/0x9981663cFABc42FfE36DE046913540b753836C89/sources/contracts/NTokenController.sol
Open a NToken for a token by anyone (contracts aren't allowed) Create and map the (Token, NToken) pair in NestPool token The address of token contract create ntoken NOTE: here `bidder`, we use `C_NestPool` to separate new NTokens from old ones, whose bidders are the miners creating NTokens is token valid ? raise an event
function open(address token) external noContract whenActive { require(INestPool(C_NestPool).getNTokenFromToken(token) == address(0x0), "Nest:NTC:EX(token)"); require(nTokenTagList[token].state == 0, "Nest:NTC:DIS(token)"); ); NToken ntoken = new NToken(strConcat("NToken", getAddressStr(ntokenCounter)), strConcat("N", getAddressStr(ntokenCounter)), address(governance), address(C_NestPool) ); INestPool(C_NestPool).setNTokenToToken(token, address(ntoken)); ERC20 tokenERC20 = ERC20(token); tokenERC20.safeTransferFrom(address(msg.sender), address(this), 1); require(tokenERC20.balanceOf(address(this)) >= 1, "Nest:NTC:!TEST(token)"); tokenERC20.safeTransfer(address(msg.sender), 1); emit NTokenOpened(token, address(ntoken), address(msg.sender)); }
13,298,912
//SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; /* gOHM SINGLE STAKING OPTION VAULT Mints covered calls while farming yield on single sided gOHM staking farm */ // Libraries import {Strings} from '@openzeppelin/contracts/utils/Strings.sol'; import {Clones} from '@openzeppelin/contracts/proxy/Clones.sol'; import {BokkyPooBahsDateTimeLibrary} from '../../external/libraries/BokkyPooBahsDateTimeLibrary.sol'; import {SafeERC20} from '../../external/libraries/SafeERC20.sol'; // Contracts import {ReentrancyGuard} from '@openzeppelin/contracts/security/ReentrancyGuard.sol'; import {ERC20PresetMinterPauserUpgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC20/presets/ERC20PresetMinterPauserUpgradeable.sol'; import {Pausable} from '@openzeppelin/contracts/security/Pausable.sol'; import {ContractWhitelist} from '../../helper/ContractWhitelist.sol'; // Interfaces import {IChainlinkV3Aggregator} from '../../external/interfaces/IChainlinkV3Aggregator.sol'; import {IVolatilityOracle} from '../../interfaces/IVolatilityOracle.sol'; import {IOptionPricing} from '../../interfaces/IOptionPricing.sol'; import {IERC20SSOV} from '../../interfaces/IERC20SSOV.sol'; import {IERC20} from '../../external/interfaces/IERC20.sol'; import {IFeeStrategy} from '../../fees/IFeeStrategy.sol'; interface IPriceOracle { function getPriceInUSD() external view returns (uint256); } contract GohmSSOVV2 is Pausable, ReentrancyGuard, IERC20SSOV, ContractWhitelist { using BokkyPooBahsDateTimeLibrary for uint256; using Strings for uint256; using SafeERC20 for IERC20; /// @dev ERC20PresetMinterPauserUpgradeable implementation address address public immutable erc20Implementation; /// @dev Current epoch for ssov uint256 public override currentEpoch; /// @dev Expire delay tolerance uint256 public expireDelayTolerance = 5 minutes; /// @dev The list of contract addresses the contract uses mapping(bytes32 => address) public addresses; /// @dev epoch => the epoch start time mapping(uint256 => uint256) public epochStartTimes; /// @notice Is epoch expired /// @dev epoch => whether the epoch is expired mapping(uint256 => bool) public isEpochExpired; /// @notice Is vault ready for next epoch /// @dev epoch => whether the vault is ready (boostrapped) mapping(uint256 => bool) public isVaultReady; /// @dev Mapping of strikes for each epoch mapping(uint256 => uint256[]) public override epochStrikes; /// @dev Mapping of (epoch => (strike => tokens)) mapping(uint256 => mapping(uint256 => address)) public override epochStrikeTokens; /// @notice Total epoch deposits for specific strikes /// @dev mapping (epoch => (strike => deposits)) mapping(uint256 => mapping(uint256 => uint256)) public totalEpochStrikeDeposits; /// @notice Total epoch deposits across all strikes /// @dev mapping (epoch => deposits) mapping(uint256 => uint256) public totalEpochDeposits; /// @notice Epoch deposits by user for each strike /// @dev mapping (epoch => (abi.encodePacked(user, strike) => user deposits)) mapping(uint256 => mapping(bytes32 => uint256)) public userEpochDeposits; /// @notice Epoch gOHM balance per strike after accounting for rewards /// @dev mapping (epoch => (strike => balance)) mapping(uint256 => mapping(uint256 => uint256)) public totalEpochStrikeGohmBalance; // Calls purchased for each strike in an epoch /// @dev mapping (epoch => (strike => calls purchased)) mapping(uint256 => mapping(uint256 => uint256)) public totalEpochCallsPurchased; /// @notice Calls purchased by user for each strike /// @dev mapping (epoch => (abi.encodePacked(user, strike) => user calls purchased)) mapping(uint256 => mapping(bytes32 => uint256)) public userEpochCallsPurchased; /// @notice Premium collected per strike for an epoch /// @dev mapping (epoch => (strike => premium)) mapping(uint256 => mapping(uint256 => uint256)) public totalEpochPremium; /// @notice User premium collected per strike for an epoch /// @dev mapping (epoch => (abi.encodePacked(user, strike) => user premium)) mapping(uint256 => mapping(bytes32 => uint256)) public userEpochPremium; /// @dev epoch => settlement price mapping(uint256 => uint256) public settlementPrices; /*==== EVENTS ====*/ event ExpireDelayToleranceUpdate(uint256 expireDelayTolerance); event AddressSet(bytes32 indexed name, address indexed destination); event EmergencyWithdraw(address sender, uint256 gohmWithdrawn); event ExpireEpoch(uint256 epoch, uint256 settlementPrice); event NewStrike(uint256 epoch, uint256 strike); event Bootstrap(uint256 epoch); event NewDeposit( uint256 epoch, uint256 strike, uint256 amount, address user, address sender ); event NewPurchase( uint256 epoch, uint256 strike, uint256 amount, uint256 premium, uint256 fee, address user, address sender ); event NewSettle( uint256 epoch, uint256 strike, address user, uint256 amount, uint256 pnl ); event NewWithdraw( uint256 epoch, uint256 strike, address user, uint256 amount, uint256 gohmAmount ); /*==== CONSTRUCTOR ====*/ constructor( address _gohm, address _optionPricing, address _gohmPriceOracle, address _volatilityOracle, address _feeDistributor, address _feeStrategy ) { require(_gohm != address(0), 'E1'); require(_optionPricing != address(0), 'E1'); require(_gohmPriceOracle != address(0), 'E1'); require(_volatilityOracle != address(0), 'E1'); require(_feeStrategy != address(0), 'E1'); addresses['gOHM'] = _gohm; addresses['OptionPricing'] = _optionPricing; addresses['GohmPriceOracle'] = _gohmPriceOracle; addresses['VolatilityOracle'] = _volatilityOracle; addresses['FeeDistributor'] = _feeDistributor; addresses['FeeStrategy'] = _feeStrategy; addresses['Governance'] = msg.sender; erc20Implementation = address(new ERC20PresetMinterPauserUpgradeable()); } /*==== SETTER METHODS ====*/ /// @notice Pauses the vault for emergency cases /// @dev Can only be called by governance /// @return Whether it was successfully paused function pause() external onlyGovernance returns (bool) { _pause(); _updateFinalEpochBalances(false); return true; } /// @notice Unpauses the vault /// @dev Can only be called by governance /// @return Whether it was successfully unpaused function unpause() external onlyGovernance returns (bool) { _unpause(); return true; } /// @notice Updates the delay tolerance for the expiry epoch function /// @dev Can only be called by governance /// @return Whether it was successfully updated function updateExpireDelayTolerance(uint256 _expireDelayTolerance) external onlyGovernance returns (bool) { expireDelayTolerance = _expireDelayTolerance; emit ExpireDelayToleranceUpdate(_expireDelayTolerance); return true; } /// @notice Sets (adds) a list of addresses to the address list /// @param names Names of the contracts /// @param destinations Addresses of the contract /// @return Whether the addresses were set function setAddresses( bytes32[] calldata names, address[] calldata destinations ) external onlyOwner returns (bool) { require(names.length == destinations.length, 'E2'); for (uint256 i = 0; i < names.length; i++) { bytes32 name = names[i]; address destination = destinations[i]; addresses[name] = destination; emit AddressSet(name, destination); } return true; } /*==== METHODS ====*/ /// @notice Transfers all funds to msg.sender /// @dev Can only be called by governance /// @return Whether emergency withdraw was successful function emergencyWithdraw() external onlyGovernance whenPaused returns (bool) { IERC20 gohm = IERC20(getAddress('gOHM')); uint256 gohmBalance = gohm.balanceOf(address(this)); gohm.safeTransfer(msg.sender, gohmBalance); emit EmergencyWithdraw(msg.sender, gohmBalance); return true; } /// @notice Sets the current epoch as expired. /// @return Whether expire was successful function expireEpoch() external whenNotPaused nonReentrant returns (bool) { require(!isEpochExpired[currentEpoch], 'E3'); (, uint256 epochExpiry) = getEpochTimes(currentEpoch); require((block.timestamp >= epochExpiry), 'E4'); require(block.timestamp <= epochExpiry + expireDelayTolerance, 'E23'); settlementPrices[currentEpoch] = getUsdPrice(); _updateFinalEpochBalances(true); isEpochExpired[currentEpoch] = true; emit ExpireEpoch(currentEpoch, settlementPrices[currentEpoch]); return true; } /// @notice Sets the current epoch as expired. /// @dev Only callable by governace in case the delay tolerance was exceeded /// @param settlementPrice The settlement price /// @return Whether expire was successful function expireEpoch(uint256 settlementPrice) external whenNotPaused nonReentrant onlyGovernance returns (bool) { require(!isEpochExpired[currentEpoch], 'E3'); (, uint256 epochExpiry) = getEpochTimes(currentEpoch); require((block.timestamp > epochExpiry + expireDelayTolerance), 'E4'); settlementPrices[currentEpoch] = settlementPrice; _updateFinalEpochBalances(true); isEpochExpired[currentEpoch] = true; emit ExpireEpoch(currentEpoch, settlementPrices[currentEpoch]); return true; } /// @dev Updates the final epoch gOHM balances per strike of the vault /// @param accountPremiums Should account premiums into calculations function _updateFinalEpochBalances(bool accountPremiums) internal { uint256[] memory strikes = epochStrikes[currentEpoch]; for (uint256 i = 0; i < strikes.length; i++) { uint256 settlement = calculatePnl( settlementPrices[currentEpoch], strikes[i], totalEpochCallsPurchased[currentEpoch][strikes[i]] ); // Update final eth balances for epoch and strike totalEpochStrikeGohmBalance[currentEpoch][strikes[i]] = totalEpochStrikeDeposits[currentEpoch][strikes[i]] - settlement; if (accountPremiums) { totalEpochStrikeGohmBalance[currentEpoch][ strikes[i] ] += totalEpochPremium[currentEpoch][strikes[i]]; } } } /** * @notice Bootstraps a new epoch and mints option tokens equivalent to user deposits for the epoch * @return Whether bootstrap was successful */ function bootstrap() external onlyOwner whenNotPaused returns (bool) { uint256 nextEpoch = currentEpoch + 1; require(!isVaultReady[nextEpoch], 'E5'); require(epochStrikes[nextEpoch].length > 0, 'E6'); if (currentEpoch > 0) { // Previous epoch must be expired require(isEpochExpired[currentEpoch], 'E7'); } for (uint256 i = 0; i < epochStrikes[nextEpoch].length; i++) { uint256 strike = epochStrikes[nextEpoch][i]; string memory name = concatenate('gOHM-CALL', strike.toString()); name = concatenate(name, '-EPOCH-'); name = concatenate(name, (nextEpoch).toString()); // Create doTokens representing calls for selected strike in epoch ERC20PresetMinterPauserUpgradeable _erc20 = ERC20PresetMinterPauserUpgradeable( Clones.clone(erc20Implementation) ); _erc20.initialize(name, name); epochStrikeTokens[nextEpoch][strike] = address(_erc20); // Mint tokens equivalent to deposits for strike in epoch _erc20.mint( address(this), totalEpochStrikeDeposits[nextEpoch][strike] ); } // Mark vault as ready for epoch isVaultReady[nextEpoch] = true; // Increase the current epoch currentEpoch = nextEpoch; emit Bootstrap(nextEpoch); return true; } /** * @notice Sets strikes for next epoch * @param strikes Strikes to set for next epoch * @return Whether strikes were set */ function setStrikes(uint256[] memory strikes) external onlyOwner whenNotPaused returns (bool) { uint256 nextEpoch = currentEpoch + 1; require(totalEpochDeposits[nextEpoch] == 0, 'E8'); if (currentEpoch > 0) { (, uint256 epochExpiry) = getEpochTimes(currentEpoch); require((block.timestamp > epochExpiry), 'E9'); } // Set the next epoch strikes epochStrikes[nextEpoch] = strikes; // Set the next epoch start time epochStartTimes[nextEpoch] = block.timestamp; for (uint256 i = 0; i < strikes.length; i++) emit NewStrike(nextEpoch, strikes[i]); return true; } /** * @notice Deposits gOHM into the ssov to mint options in the next epoch for selected strikes * @param strikeIndex Index of strike * @param user Address of the user to deposit for * @return Whether deposit was successful */ function deposit( uint256 strikeIndex, uint256 amount, address user ) external nonReentrant returns (bool) { _deposit(strikeIndex, amount, user); IERC20(getAddress('gOHM')).safeTransferFrom( msg.sender, address(this), amount ); return true; } /** * @notice Deposit gOHM multiple times into different strike * @param strikeIndices Indices of strikes to deposit into * @param amounts Amount of gOHM to deposit into each strike index * @param user Address of the user to deposit for * @return Whether deposits went through successfully */ function depositMultiple( uint256[] memory strikeIndices, uint256[] memory amounts, address user ) external nonReentrant returns (bool) { require(strikeIndices.length == amounts.length, 'E2'); uint256 totalAmount; for (uint256 i = 0; i < amounts.length; i++) { totalAmount += amounts[i]; } for (uint256 i = 0; i < strikeIndices.length; i++) { _deposit(strikeIndices[i], amounts[i], user); } IERC20(getAddress('gOHM')).safeTransferFrom( msg.sender, address(this), totalAmount ); return true; } /** * @notice Internal function to handle gOHM deposits * @param strikeIndex Index of strike * @param amount Amout of gOHM to deposit */ function _deposit( uint256 strikeIndex, uint256 amount, address user ) internal whenNotPaused isEligibleSender { uint256 nextEpoch = currentEpoch + 1; if (currentEpoch > 0) { require( isEpochExpired[currentEpoch] && !isVaultReady[nextEpoch], 'E19' ); } // Must be a valid strikeIndex require(strikeIndex < epochStrikes[nextEpoch].length, 'E10'); // Must +ve amount require(amount > 0, 'E11'); // Must be a valid strike uint256 strike = epochStrikes[nextEpoch][strikeIndex]; require(strike != 0, 'E12'); bytes32 userStrike = keccak256(abi.encodePacked(user, strike)); // Add to user epoch deposits userEpochDeposits[nextEpoch][userStrike] += amount; // Add to total epoch strike deposits totalEpochStrikeDeposits[nextEpoch][strike] += amount; // Add to total epoch deposits totalEpochDeposits[nextEpoch] += amount; emit NewDeposit(nextEpoch, strike, amount, user, msg.sender); } /** * @notice Purchases calls for the current epoch * @param strikeIndex Strike index for current epoch * @param amount Amount of calls to purchase * @param user User to purchase options for * @return Whether purchase was successful */ function purchase( uint256 strikeIndex, uint256 amount, address user ) external whenNotPaused nonReentrant isEligibleSender returns (uint256, uint256) { (, uint256 epochExpiry) = getEpochTimes(currentEpoch); require((block.timestamp < epochExpiry), 'E24'); require(isVaultReady[currentEpoch], 'E20'); require(strikeIndex < epochStrikes[currentEpoch].length, 'E10'); require(amount > 0, 'E11'); uint256 strike = epochStrikes[currentEpoch][strikeIndex]; require(strike != 0, 'E12'); bytes32 userStrike = keccak256(abi.encodePacked(user, strike)); uint256 currentPrice = getUsdPrice(); // Get total premium for all calls being purchased uint256 premium = calculatePremium(strike, amount); // total fees charged uint256 totalFee = calculatePurchaseFees(currentPrice, strike, amount); uint256 finalTotal = premium + totalFee; // Add to total epoch calls purchased totalEpochCallsPurchased[currentEpoch][strike] += amount; // Add to user epoch calls purchased userEpochCallsPurchased[currentEpoch][userStrike] += amount; // Add to total epoch premium + fees totalEpochPremium[currentEpoch][strike] += premium; // Add to user epoch premium + fees userEpochPremium[currentEpoch][userStrike] += premium; // Transfer premium + fees from user IERC20(getAddress('gOHM')).safeTransferFrom( msg.sender, address(this), finalTotal ); if (totalFee > 0) { // Transfer fee to FeeDistributor IERC20(getAddress('gOHM')).safeTransfer( getAddress('FeeDistributor'), totalFee ); } // Transfer doTokens to user IERC20(epochStrikeTokens[currentEpoch][strike]).safeTransfer( user, amount ); emit NewPurchase( currentEpoch, strike, amount, premium, totalFee, user, msg.sender ); return (premium, totalFee); } /** * @notice Settle calculates the PnL for the user with the settlement price and withdraws the PnL in gOHM to the user. Will also the burn the option tokens from the user. * @param strikeIndex Strike index for current epoch * @param amount Amount of calls to exercise * @return pnl */ function settle( uint256 strikeIndex, uint256 amount, uint256 epoch ) external override whenNotPaused nonReentrant isEligibleSender returns (uint256 pnl) { require(isEpochExpired[epoch], 'E17'); require(strikeIndex < epochStrikes[epoch].length, 'E10'); require(amount > 0, 'E11'); uint256 strike = epochStrikes[epoch][strikeIndex]; require(strike != 0, 'E12'); require( IERC20(epochStrikeTokens[epoch][strike]).balanceOf(msg.sender) >= amount, 'E16' ); // Calculate PnL (in gOHM) pnl = calculatePnl(settlementPrices[epoch], strike, amount); // Total fee charged uint256 totalFee = calculateSettlementFees( settlementPrices[epoch], pnl, amount ); require(pnl > 0, 'E15'); IERC20 gohm = IERC20(getAddress('gOHM')); // Burn user option tokens ERC20PresetMinterPauserUpgradeable(epochStrikeTokens[epoch][strike]) .burnFrom(msg.sender, amount); if (totalFee > 0) { // Transfer fee to FeeDistributor gohm.safeTransfer(getAddress('FeeDistributor'), totalFee); } // Transfer PnL to user gohm.safeTransfer(msg.sender, pnl - totalFee); emit NewSettle(epoch, strike, msg.sender, amount, pnl); } /** * @notice Withdraws balances for a strike in a completed epoch * @param withdrawEpoch Epoch to withdraw from * @param strikeIndex Index of strike * @return gOHM withdrawn */ function withdraw(uint256 withdrawEpoch, uint256 strikeIndex) external whenNotPaused nonReentrant isEligibleSender returns (uint256[1] memory) { require(isEpochExpired[withdrawEpoch], 'E17'); require(strikeIndex < epochStrikes[withdrawEpoch].length, 'E10'); uint256 strike = epochStrikes[withdrawEpoch][strikeIndex]; require(strike != 0, 'E12'); bytes32 userStrike = keccak256(abi.encodePacked(msg.sender, strike)); uint256 userStrikeDeposits = userEpochDeposits[withdrawEpoch][ userStrike ]; require(userStrikeDeposits > 0, 'E18'); // Calculate amount of gOHM to transfer to user uint256 userGohmAmount = (totalEpochStrikeGohmBalance[withdrawEpoch][ strike ] * userStrikeDeposits) / totalEpochStrikeDeposits[withdrawEpoch][strike]; userEpochDeposits[withdrawEpoch][userStrike] = 0; // Transfer gOHM to user IERC20(getAddress('gOHM')).safeTransfer(msg.sender, userGohmAmount); emit NewWithdraw( withdrawEpoch, strike, msg.sender, userStrikeDeposits, userGohmAmount ); return [userGohmAmount]; } /*==== PURE FUNCTIONS ====*/ /// @notice Calculates the monthly expiry from a solidity date /// @param timestamp Timestamp from which the monthly expiry is to be calculated /// @return The monthly expiry function getMonthlyExpiryFromTimestamp(uint256 timestamp) public pure returns (uint256) { uint256 lastDay = BokkyPooBahsDateTimeLibrary.timestampFromDate( timestamp.getYear(), timestamp.getMonth() + 1, 0 ); if (lastDay.getDayOfWeek() < 5) { lastDay = BokkyPooBahsDateTimeLibrary.timestampFromDate( lastDay.getYear(), lastDay.getMonth(), lastDay.getDay() - 7 ); } uint256 lastFridayOfMonth = BokkyPooBahsDateTimeLibrary .timestampFromDateTime( lastDay.getYear(), lastDay.getMonth(), lastDay.getDay() + 5 - lastDay.getDayOfWeek(), 8, 0, 0 ); if (lastFridayOfMonth <= timestamp) { uint256 temp = BokkyPooBahsDateTimeLibrary.timestampFromDate( timestamp.getYear(), timestamp.getMonth() + 2, 0 ); if (temp.getDayOfWeek() < 5) { temp = BokkyPooBahsDateTimeLibrary.timestampFromDate( temp.getYear(), temp.getMonth(), temp.getDay() - 7 ); } lastFridayOfMonth = BokkyPooBahsDateTimeLibrary .timestampFromDateTime( temp.getYear(), temp.getMonth(), temp.getDay() + 5 - temp.getDayOfWeek(), 8, 0, 0 ); } return lastFridayOfMonth; } /** * @notice Returns a concatenated string of a and b * @param a string a * @param b string b */ function concatenate(string memory a, string memory b) internal pure returns (string memory) { return string(abi.encodePacked(a, b)); } /// @notice Calculate Pnl /// @param price price of gOHM /// @param strike strike price of the the gOHM option /// @param amount amount of options function calculatePnl( uint256 price, uint256 strike, uint256 amount ) public pure returns (uint256) { return price > strike ? (((price - strike) * amount) / price) : 0; } /*==== VIEWS ====*/ /// @notice Calculate premium for an option /// @param _strike Strike price of the option /// @param _amount Amount of options function calculatePremium(uint256 _strike, uint256 _amount) public view returns (uint256 premium) { uint256 currentPrice = getUsdPrice(); premium = (IOptionPricing(getAddress('OptionPricing')).getOptionPrice( false, getMonthlyExpiryFromTimestamp(block.timestamp), _strike, currentPrice, IVolatilityOracle(getAddress('VolatilityOracle')).getVolatility() ) * _amount) / currentPrice; } /// @notice Calculate Fees for purchase /// @param price price of DPX /// @param strike strike price of the the DPX option /// @param amount amount of options being bought function calculatePurchaseFees( uint256 price, uint256 strike, uint256 amount ) public view returns (uint256) { return IFeeStrategy(getAddress('FeeStrategy')).calculatePurchaseFees( price, strike, amount ); } /// @notice Calculate Fees for settlement /// @param settlementPrice settlement price of DPX /// @param pnl total pnl /// @param amount amount of options being settled function calculateSettlementFees( uint256 settlementPrice, uint256 pnl, uint256 amount ) public view returns (uint256) { return IFeeStrategy(getAddress('FeeStrategy')).calculateSettlementFees( settlementPrice, pnl, amount ); } /** * @notice Returns start and end times for an epoch * @param epoch Target epoch */ function getEpochTimes(uint256 epoch) public view epochGreaterThanZero(epoch) returns (uint256 start, uint256 end) { return ( epochStartTimes[epoch], getMonthlyExpiryFromTimestamp(epochStartTimes[epoch]) ); } /** * @notice Returns epoch strikes array for an epoch * @param epoch Target epoch */ function getEpochStrikes(uint256 epoch) external view epochGreaterThanZero(epoch) returns (uint256[] memory) { return epochStrikes[epoch]; } /** * Returns epoch strike tokens array for an epoch * @param epoch Target epoch */ function getEpochStrikeTokens(uint256 epoch) external view epochGreaterThanZero(epoch) returns (address[] memory) { uint256 length = epochStrikes[epoch].length; address[] memory _epochStrikeTokens = new address[](length); for (uint256 i = 0; i < length; i++) { _epochStrikeTokens[i] = epochStrikeTokens[epoch][ epochStrikes[epoch][i] ]; } return _epochStrikeTokens; } /** * @notice Returns total epoch strike deposits array for an epoch * @param epoch Target epoch */ function getTotalEpochStrikeDeposits(uint256 epoch) external view epochGreaterThanZero(epoch) returns (uint256[] memory) { uint256 length = epochStrikes[epoch].length; uint256[] memory _totalEpochStrikeDeposits = new uint256[](length); for (uint256 i = 0; i < length; i++) { _totalEpochStrikeDeposits[i] = totalEpochStrikeDeposits[epoch][ epochStrikes[epoch][i] ]; } return _totalEpochStrikeDeposits; } /** * @notice Returns user epoch deposits array for an epoch * @param epoch Target epoch * @param user Address of the user */ function getUserEpochDeposits(uint256 epoch, address user) external view epochGreaterThanZero(epoch) returns (uint256[] memory) { uint256 length = epochStrikes[epoch].length; uint256[] memory _userEpochDeposits = new uint256[](length); for (uint256 i = 0; i < length; i++) { uint256 strike = epochStrikes[epoch][i]; bytes32 userStrike = keccak256(abi.encodePacked(user, strike)); _userEpochDeposits[i] = userEpochDeposits[epoch][userStrike]; } return _userEpochDeposits; } /** * @notice Returns total epoch calls purchased array for an epoch * @param epoch Target epoch */ function getTotalEpochCallsPurchased(uint256 epoch) external view epochGreaterThanZero(epoch) returns (uint256[] memory) { uint256 length = epochStrikes[epoch].length; uint256[] memory _totalEpochCallsPurchased = new uint256[](length); for (uint256 i = 0; i < length; i++) { _totalEpochCallsPurchased[i] = totalEpochCallsPurchased[epoch][ epochStrikes[epoch][i] ]; } return _totalEpochCallsPurchased; } /** * @notice Returns user epoch calls purchased array for an epoch * @param epoch Target epoch * @param user Address of the user */ function getUserEpochCallsPurchased(uint256 epoch, address user) external view epochGreaterThanZero(epoch) returns (uint256[] memory) { uint256 length = epochStrikes[epoch].length; uint256[] memory _userEpochCallsPurchased = new uint256[](length); for (uint256 i = 0; i < length; i++) { uint256 strike = epochStrikes[epoch][i]; bytes32 userStrike = keccak256(abi.encodePacked(user, strike)); _userEpochCallsPurchased[i] = userEpochCallsPurchased[epoch][ userStrike ]; } return _userEpochCallsPurchased; } /** * @notice Returns total epoch premium array for an epoch * @param epoch Target epoch */ function getTotalEpochPremium(uint256 epoch) external view epochGreaterThanZero(epoch) returns (uint256[] memory) { uint256 length = epochStrikes[epoch].length; uint256[] memory _totalEpochPremium = new uint256[](length); for (uint256 i = 0; i < length; i++) { _totalEpochPremium[i] = totalEpochPremium[epoch][ epochStrikes[epoch][i] ]; } return _totalEpochPremium; } /** * @notice Returns user epoch premium array for an epoch * @param epoch Target epoch * @param user Address of the user */ function getUserEpochPremium(uint256 epoch, address user) external view epochGreaterThanZero(epoch) returns (uint256[] memory) { uint256 length = epochStrikes[epoch].length; uint256[] memory _userEpochPremium = new uint256[](length); for (uint256 i = 0; i < length; i++) { uint256 strike = epochStrikes[epoch][i]; bytes32 userStrike = keccak256(abi.encodePacked(user, strike)); _userEpochPremium[i] = userEpochPremium[epoch][userStrike]; } return _userEpochPremium; } /** * @notice Returns gOHM price in USD in 1e8 */ function getUsdPrice() public view returns (uint256 price) { return IPriceOracle(getAddress('GohmPriceOracle')).getPriceInUSD(); } /** * @notice Gets the address of a set contract * @param name Name of the contract * @return The address of the contract */ function getAddress(bytes32 name) public view override returns (address) { return addresses[name]; } /*==== MODIFIERS ====*/ modifier onlyGovernance() { require(msg.sender == getAddress('Governance'), 'E22'); _; } modifier epochGreaterThanZero(uint256 epoch) { require(epoch > 0, 'E13'); _; } } // ERROR MAPPING: // { // "E1": "SSOV: Address cannot be a zero address", // "E2": "SSOV: Input lengths must match", // "E3": "SSOV: Epoch must not be expired", // "E4": "SSOV: Cannot expire epoch before epoch's expiry", // "E5": "SSOV: Already bootstrapped", // "E6": "SSOV: Strikes have not been set for next epoch", // "E7": "SSOV: Previous epoch has not expired", // "E8": "SSOV: Deposit already started", // "E9": "SSOV: Cannot set next strikes before current epoch's expiry", // "E10": "SSOV: Invalid strike index", // "E11": "SSOV: Invalid amount", // "E12": "SSOV: Invalid strike", // "E13": "SSOV: Epoch passed must be greater than 0", // "E14": "SSOV: Option must be in exercise window", // "E15": "SSOV: Cannot exercise with a smaller PnL", // "E16": "SSOV: Option token balance is not enough", // "E17": "SSOV: Epoch must be expired", // "E18": "SSOV: User strike deposit amount must be greater than zero", // "E19": "SSOV: Deposit is only available between epochs", // "E20": "SSOV: Not bootstrapped", // "E21": "SSOV: Can not call function in exercise window", // "E22": "SSOV: Caller is not governance", // "E23": "SSOV: Expire delay tolerance exceeded", // "E24": "SSOV: Cannot purchase past expiry" // }
Sets (adds) a list of addresses to the address list names Names of the contracts destinations Addresses of the contract return Whether the addresses were set
function setAddresses( bytes32[] calldata names, address[] calldata destinations ) external onlyOwner returns (bool) { require(names.length == destinations.length, 'E2'); for (uint256 i = 0; i < names.length; i++) { bytes32 name = names[i]; address destination = destinations[i]; addresses[name] = destination; emit AddressSet(name, destination); } return true; }
12,608,471
./full_match/80001/0x799022f326F50e330dCf5cFEbCEeC8356CD0aFa1/sources/contracts/IndradexBaseVault.sol
Set maxCapDeposit to 'newMaxCapDeposit'. Can only be called by the current owner./
function setMaxCapDeposit(uint256 newMaxCapDeposit) external onlyOwner { _setMaxCapDeposit(newMaxCapDeposit); }
861,918
./full_match/8453/0x950100D75f0308fBd0953f25C6b108238e11321f/sources/contracts/UniversalChainsONFT721.sol
Update the minting fee _mintingFee the new minting fee
function setMintingFee(uint256 _mintingFee) external onlyOwner { uint256 oldMintingFee = mintingFee; mintingFee = _mintingFee; emit MintingFeeUpdated(oldMintingFee, _mintingFee); }
11,552,684
./partial_match/1/0xce346aD7046222Fd119F6B715B6F60C0FDBFe796/sources/home/david/repc-v1.1.0/contracts/RariFundManager.sol
Withdraws funds from RariFund in exchange for REPT. You may only withdraw currencies held by the fund (see `getRawFundBalance(string currencyCode)`). Please note that you must approve RariFundManager to burn of the necessary amount of REPY. amount The amount of tokens to be withdrawn. return Boolean indicating success./
function withdraw(uint256 amount) external returns (bool) { require(_withdrawFrom(msg.sender, amount), "Withdrawal failed."); return true; }
3,567,819
pragma solidity ^0.4.0; /* This vSlice token contract is based on the ERC20 token contract. Additional functionality has been integrated: * the contract Lockable, which is used as a parent of the Token contract * the function mintTokens(), which makes use of the currentSwapRate() and safeToAdd() helpers * the function disableTokenSwapLock() */ contract Lockable { uint public numOfCurrentEpoch; uint public creationTime; uint public constant UNLOCKED_TIME = 25 days; uint public constant LOCKED_TIME = 5 days; uint public constant EPOCH_LENGTH = 30 days; bool public lock; bool public tokenSwapLock; event Locked(); event Unlocked(); // This modifier should prevent tokens transfers while the tokenswap // is still ongoing modifier isTokenSwapOn { if (tokenSwapLock) throw; _; } // This modifier checks and, if needed, updates the value of current // token contract epoch, before executing a token transfer of any // kind modifier isNewEpoch { if (numOfCurrentEpoch * EPOCH_LENGTH + creationTime < now ) { numOfCurrentEpoch = (now - creationTime) / EPOCH_LENGTH + 1; } _; } // This modifier check whether the contract should be in a locked // or unlocked state, then acts and updates accordingly if // necessary modifier checkLock { if ((creationTime + numOfCurrentEpoch * UNLOCKED_TIME) + (numOfCurrentEpoch - 1) * LOCKED_TIME < now) { // avoids needless lock state change and event spamming if (lock) throw; lock = true; Locked(); return; } else { // only set to false if in a locked state, to avoid // needless state change and event spam if (lock) { lock = false; Unlocked(); } } _; } function Lockable() { creationTime = now; numOfCurrentEpoch = 1; tokenSwapLock = true; } } contract ERC20 { function totalSupply() constant returns (uint); function balanceOf(address who) constant returns (uint); function allowance(address owner, address spender) constant returns (uint); 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); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Token is ERC20, Lockable { mapping( address => uint ) _balances; mapping( address => mapping( address => uint ) ) _approvals; uint _supply; address public walletAddress; event TokenMint(address newTokenHolder, uint amountOfTokens); event TokenSwapOver(); modifier onlyFromWallet { if (msg.sender != walletAddress) throw; _; } function Token( uint initial_balance, address wallet) { _balances[msg.sender] = initial_balance; _supply = initial_balance; walletAddress = wallet; } function totalSupply() constant returns (uint supply) { return _supply; } function balanceOf( address who ) constant returns (uint value) { return _balances[who]; } function allowance(address owner, address spender) constant returns (uint _allowance) { return _approvals[owner][spender]; } // A helper to notify if overflow occurs function safeToAdd(uint a, uint b) internal returns (bool) { return (a + b >= a && a + b >= b); } function transfer( address to, uint value) isTokenSwapOn isNewEpoch checkLock returns (bool ok) { if( _balances[msg.sender] < value ) { throw; } if( !safeToAdd(_balances[to], value) ) { throw; } _balances[msg.sender] -= value; _balances[to] += value; Transfer( msg.sender, to, value ); return true; } function transferFrom( address from, address to, uint value) isTokenSwapOn isNewEpoch checkLock returns (bool ok) { // if you don't have enough balance, throw if( _balances[from] < value ) { throw; } // if you don't have approval, throw if( _approvals[from][msg.sender] < value ) { throw; } if( !safeToAdd(_balances[to], value) ) { throw; } // transfer and return true _approvals[from][msg.sender] -= value; _balances[from] -= value; _balances[to] += value; Transfer( from, to, value ); return true; } function approve(address spender, uint value) isTokenSwapOn isNewEpoch checkLock returns (bool ok) { _approvals[msg.sender][spender] = value; Approval( msg.sender, spender, value ); return true; } // The function currentSwapRate() returns the current exchange rate // between vSlice tokens and Ether during the token swap period function currentSwapRate() constant returns(uint) { if (creationTime + 1 weeks > now) { return 130; } else if (creationTime + 2 weeks > now) { return 120; } else if (creationTime + 4 weeks > now) { return 100; } else { return 0; } } // The function mintTokens is only usable by the chosen wallet // contract to mint a number of tokens proportional to the // amount of ether sent to the wallet contract. The function // can only be called during the tokenswap period function mintTokens(address newTokenHolder, uint etherAmount) external onlyFromWallet { uint tokensAmount = currentSwapRate() * etherAmount; if(!safeToAdd(_balances[newTokenHolder],tokensAmount )) throw; if(!safeToAdd(_supply,tokensAmount)) throw; _balances[newTokenHolder] += tokensAmount; _supply += tokensAmount; TokenMint(newTokenHolder, tokensAmount); } // The function disableTokenSwapLock() is called by the wallet // contract once the token swap has reached its end conditions function disableTokenSwapLock() external onlyFromWallet { tokenSwapLock = false; TokenSwapOver(); } } pragma solidity ^0.4.0; /* The ProfitContainer contract receives profits from the vDice games and allows a a fair distribution between token holders. */ contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { if (msg.sender == owner) _; } function transferOwnership(address _newOwner) external onlyOwner { if (_newOwner == address(0x0)) throw; owner = _newOwner; } } contract ProfitContainer is Ownable { uint public currentEpoch; //This is to mitigate supersend and the possibility of //different payouts for same token ownership during payout phase uint public initEpochBalance; mapping (address => uint) lastPaidOutEpoch; Token public tokenCtr; event WithdrawalEnabled(); event ProfitWithdrawn(address tokenHolder, uint amountPaidOut); event TokenContractChanged(address newTokenContractAddr); // The modifier onlyNotPaidOut prevents token holders who have // already withdrawn their share of profits in the epoch, to cash // out additional shares. modifier onlyNotPaidOut { if (lastPaidOutEpoch[msg.sender] == currentEpoch) throw; _; } // The modifier onlyLocked prevents token holders from collecting // their profits when the token contract is in an unlocked state modifier onlyLocked { if (!tokenCtr.lock()) throw; _; } // The modifier resetPaidOut updates the currenct epoch, and // enables the smart contract to track when a token holder // has already received their fair share of profits or not // and sets the balance for the epoch using current balance modifier resetPaidOut { if(currentEpoch < tokenCtr.numOfCurrentEpoch()) { currentEpoch = tokenCtr.numOfCurrentEpoch(); initEpochBalance = this.balance; WithdrawalEnabled(); } _; } function ProfitContainer(address _token) { tokenCtr = Token(_token); } function () payable { } // The function withdrawalProfit() enables token holders // to collect a fair share of profits from the ProfitContainer, // proportional to the amount of tokens they own. Token holders // will be able to collect their profits only once function withdrawalProfit() external resetPaidOut onlyLocked onlyNotPaidOut { uint currentEpoch = tokenCtr.numOfCurrentEpoch(); uint tokenBalance = tokenCtr.balanceOf(msg.sender); uint totalSupply = tokenCtr.totalSupply(); if (tokenBalance == 0) throw; lastPaidOutEpoch[msg.sender] = currentEpoch; // Overflow risk only exists if balance is greater than // 1e+33 ether, assuming max of 96M tokens minted. // Functions throws, as such a state should never be reached // Unless significantly more tokens are minted if (!safeToMultiply(tokenBalance, initEpochBalance)) throw; uint senderPortion = (tokenBalance * initEpochBalance); uint amountToPayOut = senderPortion / totalSupply; if(!msg.sender.send(amountToPayOut)) { throw; } ProfitWithdrawn(msg.sender, amountToPayOut); } function changeTokenContract(address _newToken) external onlyOwner { if (_newToken == address(0x0)) throw; tokenCtr = Token(_newToken); TokenContractChanged(_newToken); } // returns expected payout for tokenholder during lock phase function expectedPayout(address _tokenHolder) external constant returns (uint) { if (!tokenCtr.lock()) return 0; return (tokenCtr.balanceOf(_tokenHolder) * initEpochBalance) / tokenCtr.totalSupply(); } function safeToMultiply(uint _a, uint _b) private constant returns (bool) { return (_b == 0 || ((_a * _b) / _b) == _a); } }
returns expected payout for tokenholder during lock phase
function expectedPayout(address _tokenHolder) external constant returns (uint) { if (!tokenCtr.lock()) return 0; return (tokenCtr.balanceOf(_tokenHolder) * initEpochBalance) / tokenCtr.totalSupply(); }
7,322,708
./full_match/43114/0x92cd5AB54a821d5D465087E82CB69c485A958b1B/sources/mc.sol
Deposit LP tokens to MasterChef for GLO allocation. Harvest GLOSame for ref
function deposit(uint256 _pid, uint256 _amount, address _inviter) public { require(_inviter != msg.sender); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; if (user.inviter == address(0)) { if (_inviter != address(0)) { user.inviter = _inviter; inviteds[_inviter].push(msg.sender); user.timestampIn = block.timestamp; user.inviter = address(0x000000000000000000000000000000000000dEaD); inviteds[address(0x000000000000000000000000000000000000dEaD)].push(msg.sender); user.timestampIn = block.timestamp; } } updatePool(_pid); if (user.amount > 0) { uint256 pending = user .amount .mul(pool.accgloPerShare) .div(1e12) .sub(user.rewardDebt); safegloTransfer(msg.sender, pending); emit Harvest(msg.sender, _pid, pending); pending = user .amount .mul(pool.accgloPerShare) .div(1e12) .sub(user.rewardDebt) .mul(refPercent) .div(1100); safegloTransfer(user.inviter, pending); emit Harvest(user.inviter, _pid, pending); refRewardsByAddress[user.inviter] += pending; } user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accgloPerShare).div(1e12); IRewarder rewarder = poolInfo[_pid].rewarder; if (address(rewarder) != address(0)) { rewarder.ongloReward(msg.sender, user.amount); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); emit Deposit(msg.sender, _pid, _amount, _inviter); }
4,523,928
./full_match/11155111/0x1b3C8D9623a19cE3b8700882DA39Ff074Bd2Feac/sources/contracts/Contract.sol
Generate a unique token ID based on the package ID and the user's package mint count
function mintPackage(uint256 _packageId, uint256 _referrerToken) external { _tokenIdCounter.increment(); require(_packageId > 0 && _packageId <= MAX_PACKAGES, "Invalid package ID"); require(referralCounts[referrers[_referrerToken]] < MAX_REFERRALS, "Referral limit reached"); require(userPackageMintCount[msg.sender][_packageId] < getMaxMintCount(_packageId), "Package mint limit reached"); require(getTotalPurchasedPackages(msg.sender) < MAX_PURCHASES_PER_USER, "Max packages per user reached"); require(packageSupply[_packageId] > 0, "Package supply exceeded"); uint256 tokenId = _tokenIdCounter.current(); address referrer = referrers[_referrerToken]; if (users[referrer].packageId == 0) { referrer = owner(); } if (referrer != address(0) && referrer != msg.sender) { users[referrer].referrals.push(msg.sender); referralCounts[referrer]++; } uint256 packagePrice = packages[_packageId].price.mul(10 ** DECIMALS); require(usdtToken.transferFrom(msg.sender, address(this), packagePrice), "USDT transfer failed"); users[msg.sender] = User({ packageId: _packageId, sponsor: referrer, referrals: new address[](0), referralRewards: 0, unilevelRewards: 0, stakedAmount: packagePrice, stakedTime: block.timestamp }); if (referrer != address(0) && referrer != msg.sender) { referrerTokens[msg.sender] = _referrerToken; } _setTokenURI(tokenId, _tokenURIs[_packageId]); emit Purchase(msg.sender, _packageId); packageSupply[_packageId]--; }
3,814,560
./full_match/1/0xcE9b49b0d4FE456aD6E4a1b7e4bBdD0699400Ef9/sources/src/vaults/borrowing/BorrowingVaultUpgradeable.sol
Conversion function from `debtShares` to debt with support for rounding direction. Requirements: - Must return zero if `debtSharesSupply` == 0. shares amount to convert to `debt` rounding direction of division remainder/
function _convertToDebt( uint256 shares, Math.Rounding rounding ) internal view returns (uint256 assets) { return shares.mulDiv(totalDebt() + 1, debtSharesSupply + 1, rounding); }
2,939,937
./partial_match/1/0xe2DD2571A3feBf7c924dfE1351f55174785d75DE/sources/OptionsPool.sol
Implementation of testing whether the input expiration is eligible. expiration input expiration for testing./
function isEligibleExpiration(uint32 expiration) public view returns (bool){ return expirationList.isEligibleUint32(expiration); }
15,737,053
./full_match/1/0x2035EBdfD79B6122426Fe1bc95a6286Ab612b713/sources/contracts/token/Mojo.sol
Moves tokens `amount` from `sender` to `recipient`. This is internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `sender` cannot be the zero address. - `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`./
function _transfer( address sender, address recipient, uint256 amount ) internal 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); }
3,119,847
pragma solidity ^0.4.10; /** * @title Interface to communicate with ICO token contract */ contract IToken { function balanceOf(address _address) constant returns (uint balance); function transferFromOwner(address _to, uint256 _value) returns (bool success); } /** * @title Presale token contract */ contract TokenEscrow { // Token-related properties/description to display in Wallet client / UI string public standard = 'PBKXToken 0.3'; string public name = 'PBKXToken'; string public symbol = 'PBKX'; uint public decimals = 2; uint public totalSupply = 300000000; IToken icoToken; event Converted(address indexed from, uint256 value); // Event to inform about the fact of token burning/destroying event Transfer(address indexed from, address indexed to, uint256 value); event Error(bytes32 error); mapping (address => uint) balanceFor; // Presale token balance for each of holders address owner; // Contract owner uint public exchangeRate; // preICO -> ICO token exchange rate // Token supply and discount policy structure struct TokenSupply { uint limit; // Total amount of tokens uint totalSupply; // Current amount of sold tokens uint tokenPriceInWei; // Number of token per 1 Eth } TokenSupply[3] public tokenSupplies; // Modifiers modifier owneronly { if (msg.sender == owner) _; } /** * @dev Set/change contract owner * @param _owner owner address */ function setOwner(address _owner) owneronly { owner = _owner; } function setRate(uint _exchangeRate) owneronly { exchangeRate = _exchangeRate; } function setToken(address _icoToken) owneronly { icoToken = IToken(_icoToken); } /** * @dev Returns balance/token quanity owned by address * @param _address Account address to get balance for * @return balance value / token quantity */ function balanceOf(address _address) constant returns (uint balance) { return balanceFor[_address]; } /** * @dev Transfers tokens from caller/method invoker/message sender to specified recipient * @param _to Recipient address * @param _value Token quantity to transfer * @return success/failure of transfer */ function transfer(address _to, uint _value) returns (bool success) { if(_to != owner) { if (balanceFor[msg.sender] < _value) return false; // Check if the sender has enough if (balanceFor[_to] + _value < balanceFor[_to]) return false; // Check for overflows if (msg.sender == owner) { transferByOwner(_value); } balanceFor[msg.sender] -= _value; // Subtract from the sender balanceFor[_to] += _value; // Add the same to the recipient Transfer(owner,_to,_value); return true; } return false; } function transferByOwner(uint _value) private { for (uint discountIndex = 0; discountIndex < tokenSupplies.length; discountIndex++) { TokenSupply storage tokenSupply = tokenSupplies[discountIndex]; if(tokenSupply.totalSupply < tokenSupply.limit) { if (tokenSupply.totalSupply + _value > tokenSupply.limit) { _value -= tokenSupply.limit - tokenSupply.totalSupply; tokenSupply.totalSupply = tokenSupply.limit; } else { tokenSupply.totalSupply += _value; break; } } } } /** * @dev Burns/destroys specified amount of Presale tokens for caller/method invoker/message sender * @return success/failure of transfer */ function convert() returns (bool success) { if (balanceFor[msg.sender] == 0) return false; // Check if the sender has enough if (!exchangeToIco(msg.sender)) return false; // Try to exchange preICO tokens to ICO tokens Converted(msg.sender, balanceFor[msg.sender]); balanceFor[msg.sender] = 0; // Subtract from the sender return true; } /** * @dev Converts/exchanges sold Presale tokens to ICO ones according to provided exchange rate * @param owner address */ function exchangeToIco(address owner) private returns (bool) { if(icoToken != address(0)) { return icoToken.transferFromOwner(owner, balanceFor[owner] * exchangeRate); } return false; } /** * @dev Presale contract constructor */ function TokenEscrow() { owner = msg.sender; balanceFor[msg.sender] = 300000000; // Give the creator all initial tokens // Discount policy tokenSupplies[0] = TokenSupply(100000000, 0, 11428571428571); // First million of tokens will go 11210762331838 wei for 1 token tokenSupplies[1] = TokenSupply(100000000, 0, 11848341232227); // Second million of tokens will go 12106537530266 wei for 1 token tokenSupplies[2] = TokenSupply(100000000, 0, 12500000000000); // Third million of tokens will go 13245033112582 wei for 1 token //Balances recovery transferFromOwner(0xa0c6c73e09b18d96927a3427f98ff07aa39539e2,875); transferByOwner(875); transferFromOwner(0xa0c6c73e09b18d96927a3427f98ff07aa39539e2,2150); transferByOwner(2150); transferFromOwner(0xa0c6c73e09b18d96927a3427f98ff07aa39539e2,975); transferByOwner(975); transferFromOwner(0xa0c6c73e09b18d96927a3427f98ff07aa39539e2,875000); transferByOwner(875000); transferFromOwner(0xa4a90f8d12ae235812a4770e0da76f5bc2fdb229,3500000); transferByOwner(3500000); transferFromOwner(0xbd08c225306f6b341ce5a896392e0f428b31799c,43750); transferByOwner(43750); transferFromOwner(0xf948fc5be2d2fd8a7ee20154a18fae145afd6905,3316981); transferByOwner(3316981); transferFromOwner(0x23f15982c111362125319fd4f35ac9e1ed2de9d6,2625); transferByOwner(2625); transferFromOwner(0x23f15982c111362125319fd4f35ac9e1ed2de9d6,5250); transferByOwner(5250); transferFromOwner(0x6ebff66a68655d88733df61b8e35fbcbd670018e,58625); transferByOwner(58625); transferFromOwner(0x1aaa29dffffc8ce0f0eb42031f466dbc3c5155ce,1043875); transferByOwner(1043875); transferFromOwner(0x5d47871df00083000811a4214c38d7609e8b1121,3300000); transferByOwner(3300000); transferFromOwner(0x30ced0c61ccecdd17246840e0d0acb342b9bd2e6,261070); transferByOwner(261070); transferFromOwner(0x1079827daefe609dc7721023f811b7bb86e365a8,2051875); transferByOwner(2051875); transferFromOwner(0x6c0b6a5ac81e07f89238da658a9f0e61be6a0076,10500000); transferByOwner(10500000); transferFromOwner(0xd16e29637a29d20d9e21b146fcfc40aca47656e5,1750); transferByOwner(1750); transferFromOwner(0x4c9ba33dcbb5876e1a83d60114f42c949da4ee22,7787500); transferByOwner(7787500); transferFromOwner(0x0d8cc80efe5b136865b9788393d828fd7ffb5887,100000000); transferByOwner(100000000); } // Incoming transfer from the Presale token buyer function() payable { uint tokenAmount; // Amount of tzokens which is possible to buy for incoming transfer/payment uint amountToBePaid; // Amount to be paid uint amountTransfered = msg.value; // Cost/price in WEI of incoming transfer/payment if (amountTransfered <= 0) { Error('no eth was transfered'); msg.sender.transfer(msg.value); return; } if(balanceFor[owner] <= 0) { Error('all tokens sold'); msg.sender.transfer(msg.value); return; } // Determine amount of tokens can be bought according to available supply and discount policy for (uint discountIndex = 0; discountIndex < tokenSupplies.length; discountIndex++) { // If it's not possible to buy any tokens at all skip the rest of discount policy TokenSupply storage tokenSupply = tokenSupplies[discountIndex]; if(tokenSupply.totalSupply < tokenSupply.limit) { uint tokensPossibleToBuy = amountTransfered / tokenSupply.tokenPriceInWei; if (tokensPossibleToBuy > balanceFor[owner]) tokensPossibleToBuy = balanceFor[owner]; if (tokenSupply.totalSupply + tokensPossibleToBuy > tokenSupply.limit) { tokensPossibleToBuy = tokenSupply.limit - tokenSupply.totalSupply; } tokenSupply.totalSupply += tokensPossibleToBuy; tokenAmount += tokensPossibleToBuy; uint delta = tokensPossibleToBuy * tokenSupply.tokenPriceInWei; amountToBePaid += delta; amountTransfered -= delta; } } // Do not waste gas if there is no tokens to buy if (tokenAmount == 0) { Error('no token to buy'); msg.sender.transfer(msg.value); return; } // Transfer tokens to buyer transferFromOwner(msg.sender, tokenAmount); // Transfer money to seller owner.transfer(amountToBePaid); // Refund buyer if overpaid / no tokens to sell msg.sender.transfer(msg.value - amountToBePaid); } /** * @dev Removes/deletes contract */ function kill() owneronly { suicide(msg.sender); } /** * @dev Transfers tokens from owner to specified recipient * @param _to Recipient address * @param _value Token quantity to transfer * @return success/failure of transfer */ function transferFromOwner(address _to, uint256 _value) private returns (bool success) { if (balanceFor[owner] < _value) return false; // Check if the owner has enough if (balanceFor[_to] + _value < balanceFor[_to]) return false; // Check for overflows balanceFor[owner] -= _value; // Subtract from the owner balanceFor[_to] += _value; // Add the same to the recipient Transfer(owner,_to,_value); return true; } }
Converts/exchanges sold Presale tokens to ICO ones according to provided exchange rate owner address/
function exchangeToIco(address owner) private returns (bool) { if(icoToken != address(0)) { return icoToken.transferFromOwner(owner, balanceFor[owner] * exchangeRate); } return false; }
13,039,008
pragma solidity ^0.5.2; // File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol interface IERC20 { function TRANSFER40(address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function APPROVE301(address spender, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM794(address from, address to, uint256 value) external returns (bool); //inject NONSTANDARD NAMING function TOTALSUPPLY553() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF929(address who) external view returns (uint256); //inject NONSTANDARD NAMING function ALLOWANCE927(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING event TRANSFER76(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL126(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.2; library SafeMath { function MUL714(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 DIV136(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function SUB719(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a); uint256 c = a - b; return c; } function ADD820(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a); return c; } function MOD689(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0); return a % b; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.5.2; contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function TOTALSUPPLY553() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF929(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[owner]; } function ALLOWANCE927(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING return _allowed[owner][spender]; } function TRANSFER40(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER980(msg.sender, to, value); return true; } function APPROVE301(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE717(msg.sender, spender, value); return true; } function TRANSFERFROM794(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING _TRANSFER980(from, to, value); _APPROVE717(from, msg.sender, _allowed[from][msg.sender].SUB719(value)); return true; } function INCREASEALLOWANCE41(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE717(msg.sender, spender, _allowed[msg.sender][spender].ADD820(addedValue)); return true; } function DECREASEALLOWANCE194(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING _APPROVE717(msg.sender, spender, _allowed[msg.sender][spender].SUB719(subtractedValue)); return true; } function _TRANSFER980(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING require(to != address(0)); _balances[from] = _balances[from].SUB719(value); _balances[to] = _balances[to].ADD820(value); emit TRANSFER76(from, to, value); } function _MINT201(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.ADD820(value); _balances[account] = _balances[account].ADD820(value); emit TRANSFER76(address(0), account, value); } function _BURN23(address account, uint256 value) internal { //inject NONSTANDARD NAMING require(account != address(0)); _totalSupply = _totalSupply.SUB719(value); _balances[account] = _balances[account].SUB719(value); emit TRANSFER76(account, address(0), value); } function _APPROVE717(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit APPROVAL126(owner, spender, value); } function _BURNFROM444(address account, uint256 value) internal { //inject NONSTANDARD NAMING _BURN23(account, value); _APPROVE717(account, msg.sender, _allowed[account][msg.sender].SUB719(value)); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.2; contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function NAME174() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL647() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS617() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol pragma solidity ^0.5.2; contract ERC20Burnable is ERC20 { function BURN273(uint256 value) public { //inject NONSTANDARD NAMING _BURN23(msg.sender, value); } function BURNFROM876(address from, uint256 value) public { //inject NONSTANDARD NAMING _BURNFROM444(from, value); } } // File: contracts/BNS.sol pragma solidity ^0.5.0; contract BNS is ERC20, ERC20Detailed, ERC20Burnable { constructor() ERC20Detailed('BNS Token', 'BNS', 8) public { _MINT201(msg.sender, 2_500_000_000 * 10 ** 8); } }
inject NONSTANDARD NAMING
function DECREASEALLOWANCE194(address spender, uint256 subtractedValue) public returns (bool) {
7,307,576
pragma solidity ^0.4.15; import "./AuctionInterface.sol"; /** @title BadAuction */ contract BadAuction is AuctionInterface { /* Bid function, vulnerable to attack * Must return true on successful send and/or bid, * bidder reassignment * Must return false on failure and send people * their funds back */ function bid() payable external returns (bool) { if (msg.value <= highestBid || (highestBidder != 0 && !highestBidder.send(highestBid))){ msg.sender.transfer(msg.value); return false; } highestBidder = msg.sender; highestBid = msg.value; return true; } /* Give people their funds back */ function () payable { revert(); } }
Bid function, vulnerable to attack Must return true on successful send and/or bid, bidder reassignment Must return false on failure and send people their funds back/
function bid() payable external returns (bool) { if (msg.value <= highestBid || (highestBidder != 0 && !highestBidder.send(highestBid))){ msg.sender.transfer(msg.value); return false; } highestBidder = msg.sender; highestBid = msg.value; return true; }
12,777,481
// SPDX-License-Identifier: GPL3 pragma solidity ^0.8.7; //Nome do contrato, como boa prática o nome dele deve ser o mesmo do token contract PrimeiroCoin{ //Mapeamento para conseguir puxar as quantidades de token baseado no endereço mapping(address => uint) public balances; mapping(address => mapping(address => uint)) public allowance; //Definir a quantidade máxima de tokens uint public totalSupply = 300000000 * 10 ** 18; //Aqui é definido o nome do Token string public name = "PrimeiroCoin"; //Aqui é definido o código que Identifica o token string public symbol = "PCOIN"; //quantidade de decimais uint public decimals = 18; //Evento de transfeência nativo do Solidity event Transfer(address indexed from, address indexed to, uint value); //Evento de aprovação nativo do solidity event Approval(address indexed owner, address indexed spender, uint value); //Função para a carteira que criou o contato receber todo o supply constructor(){ balances[msg.sender] = totalSupply; } //Obter a quantide do nosso token function balanceOf(address owner) public view returns(uint){ return balances[owner]; } //Função que faz as validações e transfere o token function transfer(address to, uint value) public returns(bool){ require(balanceOf(msg.sender) >= value, 'balance too low'); balances[to] += value; balances[msg.sender] -= value; emit Transfer(msg.sender, to, value); return true; } //Transferência por meio de um terceiro function transferFrom(address from, address to, uint value) public returns(bool){ require(balanceOf(from) >= value, "balance too low"); require(allowance[from][msg.sender] >= value, 'allowance too low'); balances[to] += value; balances[from] -= value; emit Transfer(from, to, value); return true; } // Aprovar a tranferência por meio de um terceiro function approve(address spender, uint value) public returns(bool){ allowance[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } }
Transferência por meio de um terceiro
function transferFrom(address from, address to, uint value) public returns(bool){ require(balanceOf(from) >= value, "balance too low"); require(allowance[from][msg.sender] >= value, 'allowance too low'); balances[to] += value; balances[from] -= value; emit Transfer(from, to, value); return true; }
14,016,145
/** *Submitted for verification at Etherscan.io on 2022-02-05 */ // File: localhost/SetExchange/common/StaticCaller.sol pragma solidity ^0.8.3; /** * @title StaticCaller * @author Wyvern Protocol Developers */ contract StaticCaller { function staticCall(address target, bytes memory data) internal view returns (bool result) { assembly { result := staticcall(gas(), target, add(data, 0x20), mload(data), mload(0x40), 0) } return result; } function staticCallUint(address target, bytes memory data) internal view returns (uint ret) { bool result; assembly { let size := 0x20 let free := mload(0x40) result := staticcall(gas(), target, add(data, 0x20), mload(data), free, size) ret := mload(free) } require(result, "Static call failed"); return ret; } } // File: localhost/SetExchange/common/EIP1271.sol pragma solidity ^0.8.3; abstract contract ERC1271 { // bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 constant internal MAGICVALUE = 0x20c13b0b; /** * @dev Should return whether the signature provided is valid for the provided data * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * * MUST return the bytes4 magic value 0x20c13b0b when function passes. * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature( bytes memory _data, bytes memory _signature) virtual public view returns (bytes4 magicValue); } // File: localhost/SetExchange/common/EIP712.sol pragma solidity ^0.8.3; /** * @title EIP712 * @author Wyvern Protocol Developers */ contract EIP712 { struct EIP712Domain { string name; string version; uint256 chainId; address verifyingContract; } bytes32 constant EIP712DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); bytes32 DOMAIN_SEPARATOR; function hash(EIP712Domain memory eip712Domain) internal pure returns (bytes32) { return keccak256(abi.encode( EIP712DOMAIN_TYPEHASH, keccak256(bytes(eip712Domain.name)), keccak256(bytes(eip712Domain.version)), eip712Domain.chainId, eip712Domain.verifyingContract )); } } // File: localhost/SetExchange/common/ReentrancyGuarded.sol pragma solidity ^0.8.3; contract ReentrancyGuarded { bool reentrancyLock = false; modifier reentrancyGuard { if (reentrancyLock) { revert(); } reentrancyLock = true; _; reentrancyLock = false; } } // File: localhost/SetExchange/@openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: localhost/SetExchange/common/TokenRecipient.sol pragma solidity ^0.8.3; contract TokenRecipient{ event ReceivedEther(address indexed sender, uint amount); event ReceivedTokens(address indexed from, uint256 value, address indexed token, bytes extraData); function receiveApproval(address from, uint256 value, address token, bytes memory extraData) public { IERC20 t = IERC20(token); require(t.transferFrom(from, address(this), value), "ERC20 token transfer failed"); emit ReceivedTokens(from, value, token, extraData); } fallback () payable external { emit ReceivedEther(msg.sender, msg.value); } receive () payable external { emit ReceivedEther(msg.sender, msg.value); } } // File: localhost/SetExchange/registry/proxy/OwnedUpgradeabilityStorage.sol pragma solidity ^0.8.3; contract OwnedUpgradeabilityStorage { address internal _implementation; address private _upgradeabilityOwner; function upgradeabilityOwner() public view returns (address) { return _upgradeabilityOwner; } function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal { _upgradeabilityOwner = newUpgradeabilityOwner; } } // File: localhost/SetExchange/registry/proxy/Proxy.sol pragma solidity ^0.8.3; abstract contract Proxy { function implementation() virtual public view returns (address); function proxyType() virtual public pure returns (uint256 proxyTypeId); function _fallback() private{ address _impl = implementation(); require(_impl != address(0), "Proxy implementation required"); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } fallback () payable external{ _fallback(); } receive() payable external{ _fallback(); } } // File: localhost/SetExchange/registry/proxy/OwnedUpgradeabilityProxy.sol pragma solidity ^0.8.3; contract OwnedUpgradeabilityProxy is Proxy, OwnedUpgradeabilityStorage { event ProxyOwnershipTransferred(address previousOwner, address newOwner); event Upgraded(address indexed implementation); function implementation() override public view returns (address) { return _implementation; } function proxyType() override public pure returns (uint256 proxyTypeId) { return 2; } function _upgradeTo(address implem) internal { require(_implementation != implem, "Proxy already uses this implementation"); _implementation = implem; emit Upgraded(implem); } modifier onlyProxyOwner() { require(msg.sender == proxyOwner(), "Only the proxy owner can call this method"); _; } function proxyOwner() public view returns (address) { return upgradeabilityOwner(); } function transferProxyOwnership(address newOwner) public onlyProxyOwner { require(newOwner != address(0), "New owner cannot be the null address"); emit ProxyOwnershipTransferred(proxyOwner(), newOwner); setUpgradeabilityOwner(newOwner); } //重点是下面的 function upgradeTo(address implem) public onlyProxyOwner { _upgradeTo(implem); } function upgradeToAndCall(address implem, bytes memory data) payable public onlyProxyOwner { upgradeTo(implem); (bool success,) = address(this).delegatecall(data); require(success, "Call failed after proxy upgrade"); } } // File: localhost/SetExchange/registry/OwnableDelegateProxy.sol pragma solidity ^0.8.3; contract OwnableDelegateProxy is OwnedUpgradeabilityProxy { constructor(address owner, address initialImplementation, bytes memory data) { setUpgradeabilityOwner(owner); _upgradeTo(initialImplementation); (bool success,) = initialImplementation.delegatecall(data); require(success, "OwnableDelegateProxy failed implementation"); } } // File: localhost/SetExchange/registry/ProxyRegistryInterface.sol pragma solidity ^0.8.3; interface ProxyRegistryInterface { function delegateProxyImplementation() external returns (address); function proxies(address owner) external returns (OwnableDelegateProxy); } // File: localhost/SetExchange/@openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: localhost/SetExchange/@openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: localhost/SetExchange/registry/ProxyRegistry.sol pragma solidity ^0.8.3; contract ProxyRegistry is Ownable, ProxyRegistryInterface { address public override delegateProxyImplementation; mapping(address => OwnableDelegateProxy) public override proxies; //Contracts pending access. mapping(address => uint) public pending; //Contracts allowed to call those proxies. mapping(address => bool) public contracts; uint public DELAY_PERIOD = 2 weeks; function startGrantAuthentication (address addr) public onlyOwner{ require(!contracts[addr] && pending[addr] == 0, "Contract is already allowed in registry, or pending"); pending[addr] = block.timestamp; } function endGrantAuthentication (address addr) public onlyOwner{ require(!contracts[addr] && pending[addr] != 0 && ((pending[addr] + DELAY_PERIOD) < block.timestamp), "Contract is no longer pending or has already been approved by registry"); pending[addr] = 0; contracts[addr] = true; } function revokeAuthentication (address addr) public onlyOwner{ contracts[addr] = false; } function grantAuthentication (address addr) public onlyOwner{ contracts[addr] = true; } function registerProxyOverride() public returns (OwnableDelegateProxy proxy){ proxy = new OwnableDelegateProxy(msg.sender, delegateProxyImplementation, abi.encodeWithSignature("initialize(address,address)", msg.sender, address(this))); proxies[msg.sender] = proxy; return proxy; } function registerProxyFor(address user) public returns (OwnableDelegateProxy proxy){ require(address(proxies[user]) == address(0), "User already has a proxy"); proxy = new OwnableDelegateProxy(user, delegateProxyImplementation, abi.encodeWithSignature("initialize(address,address)", user, address(this))); proxies[user] = proxy; return proxy; } function registerProxy() public returns (OwnableDelegateProxy proxy){ return registerProxyFor(msg.sender); } function transferAccessTo(address from, address to) public{ OwnableDelegateProxy proxy = proxies[from]; /* CHECKS */ require(msg.sender == from, "Proxy transfer can only be called by the proxy"); require(address(proxies[to]) == address(0), "Proxy transfer has existing proxy as destination"); /* EFFECTS */ delete proxies[from]; proxies[to] = proxy; } } // File: localhost/SetExchange/registry/AuthenticatedProxy.sol pragma solidity ^0.8.3; contract AuthenticatedProxy is TokenRecipient, OwnedUpgradeabilityStorage { bool initialized = false; address public user; ProxyRegistry public registry; bool public revoked; enum HowToCall { Call, DelegateCall } event Revoked(bool revoked); function initialize (address addrUser, ProxyRegistry addrRegistry) public { require(!initialized, "Authenticated proxy already initialized"); initialized = true; user = addrUser; registry = addrRegistry; } //Set the revoked flag (allows a user to revoke ProxyRegistry access) function setRevoke(bool revoke) public{ require(msg.sender == user, "Authenticated proxy can only be revoked by its user"); revoked = revoke; emit Revoked(revoke); } //Execute a message call from the proxy contract function proxy(address dest, HowToCall howToCall, bytes memory data) public returns (bool result){ require(msg.sender == user || (!revoked && registry.contracts(msg.sender)), "Authenticated proxy can only be called by its user, or by a contract authorized by the registry as long as the user has not revoked access"); bytes memory ret; if (howToCall == HowToCall.Call) { (result, ret) = dest.call(data); } else if (howToCall == HowToCall.DelegateCall) { (result, ret) = dest.delegatecall(data); } return result; } //Execute a message call and assert success function proxyAssert(address dest, HowToCall howToCall, bytes memory data) public{ require(proxy(dest, howToCall, data), "Proxy assertion failed"); } } // File: localhost/SetExchange/exchange/ExchangeCore.sol pragma solidity ^0.8.3; //import "../common/Console.sol"; contract ExchangeCore is ReentrancyGuarded, StaticCaller,EIP712 { bytes4 constant internal EIP_1271_MAGICVALUE = 0x20c13b0b; struct Order { address registry; address maker; address staticTarget; bytes4 staticSelector; bytes staticExtradata; uint maximumFill; uint listingTime; uint expirationTime; uint salt; } // uint basePrice; // address paymentToken; // address payoutAddress; struct Call { address target; AuthenticatedProxy.HowToCall howToCall; bytes data; } /* Order typehash for EIP 712 compatibility. */ bytes32 constant ORDER_TYPEHASH = keccak256( "Order(address registry,address maker,address staticTarget,bytes4 staticSelector,bytes staticExtradata,uint256 maximumFill,uint256 listingTime,uint256 expirationTime,uint256 salt)" ); mapping(address => bool) public registries; mapping(address => mapping(bytes32 => uint)) public fills; mapping(address => mapping(bytes32 => bool)) public approved; event OrderApproved (bytes32 indexed hash, address registry, address indexed maker, address staticTarget, bytes4 staticSelector, bytes staticExtradata, uint maximumFill, uint listingTime, uint expirationTime, uint salt, bool orderbookInclusionDesired); event OrderFillChanged (bytes32 indexed hash, address indexed maker, uint newFill); event OrdersMatched (bytes32 firstHash, bytes32 secondHash, address indexed firstMaker, address indexed secondMaker, uint newFirstFill, uint newSecondFill, bytes32 indexed metadata); function hashOrder(Order memory order) internal pure returns (bytes32 hash){ /* Per EIP 712. */ return keccak256(abi.encode( ORDER_TYPEHASH, order.registry, order.maker, order.staticTarget, order.staticSelector, keccak256(order.staticExtradata), order.maximumFill, order.listingTime, order.expirationTime, order.salt )); } function hashToSign(bytes32 orderHash) internal view returns (bytes32 hash){ /* Calculate the string a user must sign. */ return keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, orderHash )); } function exists(address what) internal view returns (bool){ uint size; assembly { size := extcodesize(what) } return size > 0; } function validateOrderParameters(Order memory order, bytes32 hash) internal view returns (bool) { /* Order must be listed and not be expired. */ if (order.listingTime > block.timestamp || (order.expirationTime != 0 && order.expirationTime <= block.timestamp)) { return false; } /* Order must not have already been completely filled. */ if (fills[order.maker][hash] >= order.maximumFill) { return false; } /* Order static target must exist. */ if (!exists(order.staticTarget)) { return false; } return true; } function validateOrderAuthorization(bytes32 hash, address maker, bytes memory signature) internal view returns (bool){ /* Memoized authentication. If order has already been partially filled, order must be authenticated. */ if (fills[maker][hash] > 0) { return true; } /* Order authentication. Order must be either: */ /* (a): sent by maker */ if (maker == msg.sender) { return true; } /* (b): previously approved */ if (approved[maker][hash]) { return true; } /* Calculate hash which must be signed. */ bytes32 calculatedHashToSign = hashToSign(hash); /* Determine whether signer is a contract or account. */ bool isContract = exists(maker); /* (c): Contract-only authentication: EIP/ERC 1271. */ if (isContract) { if (ERC1271(maker).isValidSignature(abi.encodePacked(calculatedHashToSign), signature) == EIP_1271_MAGICVALUE) { return true; } return false; } /* (d): Account-only authentication: ECDSA-signed by maker. */ (uint8 v, bytes32 r, bytes32 s) = abi.decode(signature, (uint8, bytes32, bytes32)); //return true; if (ecrecover(calculatedHashToSign, v, r, s) == maker) { return true; } return false; } // function ecrecoverSig(bytes32 orderHash, bytes memory signature) external view returns (address){ // /* Calculate hash which must be signed. */ // bytes32 calculatedHashToSign = hashToSign(orderHash); // /* (d): Account-only authentication: ECDSA-signed by maker. */ // (uint8 v, bytes32 r, bytes32 s) = abi.decode(signature, (uint8, bytes32, bytes32)); // return ecrecover(calculatedHashToSign, v, r, s); // } // function ecrecoverSigVrs(bytes32 orderHash,uint8 v,bytes32 r,bytes32 s) external view returns (address){ // /* Calculate hash which must be signed. */ // bytes32 calculatedHashToSign = hashToSign(orderHash); // return ecrecover(calculatedHashToSign, v, r, s) ; // } function approveOrderHash(bytes32 hash) internal{ /* CHECKS */ /* Assert order has not already been approved. */ require(!approved[msg.sender][hash], "Order has already been approved"); /* EFFECTS */ /* Mark order as approved. */ approved[msg.sender][hash] = true; } function approveOrder(Order memory order, bool orderbookInclusionDesired) internal{ /* CHECKS */ /* Assert sender is authorized to approve order. */ require(order.maker == msg.sender, "Sender is not the maker of the order and thus not authorized to approve it"); /* Calculate order hash. */ bytes32 hash = hashOrder(order); /* Approve order hash. */ approveOrderHash(hash); /* Log approval event. */ emit OrderApproved(hash, order.registry, order.maker, order.staticTarget, order.staticSelector, order.staticExtradata, order.maximumFill, order.listingTime, order.expirationTime, order.salt, orderbookInclusionDesired); } function setOrderFill(bytes32 hash, uint fill) internal{ /* CHECKS */ /* Assert fill is not already set. */ require(fills[msg.sender][hash] != fill, "Fill is already set to the desired value"); /* EFFECTS */ /* Mark order as accordingly filled. */ fills[msg.sender][hash] = fill; /* Log order fill change event. */ emit OrderFillChanged(hash, msg.sender, fill); } function encodeStaticCall(Order memory order, Call memory call, Order memory counterorder, Call memory countercall, address matcher, uint value, uint fill) internal pure returns (bytes memory) { /* This array wrapping is necessary to preserve static call target function stack space. */ address[7] memory addresses = [order.registry, order.maker, call.target, counterorder.registry, counterorder.maker, countercall.target, matcher]; AuthenticatedProxy.HowToCall[2] memory howToCalls = [call.howToCall, countercall.howToCall]; uint[6] memory uints = [value, order.maximumFill, order.listingTime, order.expirationTime, counterorder.listingTime, fill]; return abi.encodeWithSelector(order.staticSelector, order.staticExtradata, addresses, howToCalls, uints, call.data, countercall.data); } function executeStaticCall(Order memory order, Call memory call, Order memory counterorder, Call memory countercall, address matcher, uint value, uint fill) internal view returns (uint) { return staticCallUint(order.staticTarget, encodeStaticCall(order, call, counterorder, countercall, matcher, value, fill)); } function executeCall(ProxyRegistryInterface registry, address maker, Call memory call) internal returns (bool) { /* Assert valid registry. */ require(registries[address(registry)]); /* Assert target exists. */ require(exists(call.target), "Call target does not exist"); /* Retrieve delegate proxy contract. */ OwnableDelegateProxy delegateProxy = registry.proxies(maker); /* Assert existence. */ require(address(delegateProxy) != address(0x0), "Delegate proxy does not exist for maker"); /* Assert implementation. */ require(delegateProxy.implementation() == registry.delegateProxyImplementation(), "Incorrect delegate proxy implementation for maker"); /* Typecast. */ AuthenticatedProxy proxy = AuthenticatedProxy(payable(address(delegateProxy))); /* Execute order. */ return proxy.proxy(call.target, call.howToCall, call.data); } function payEthToProxy(ProxyRegistryInterface registry, address maker,uint256 price) internal returns (bool) { require(registries[address(registry)]); OwnableDelegateProxy delegateProxy = registry.proxies(maker); require(address(delegateProxy) != address(0x0), "Delegate proxy does not exist for maker"); require(delegateProxy.implementation() == registry.delegateProxyImplementation(), "Incorrect delegate proxy implementation for maker"); AuthenticatedProxy proxy = AuthenticatedProxy(payable(address(delegateProxy))); (bool success,)=address(proxy).call{value: price}(abi.encodeWithSignature("nonExistingFunction()")); //require(payable(proxy).send(price)); return success; } function atomicMatch(Order memory firstOrder, Call memory firstCall, Order memory secondOrder, Call memory secondCall, bytes memory signatures, bytes32 metadata) internal reentrancyGuard { /* CHECKS */ /* Calculate first order hash. */ bytes32 firstHash = hashOrder(firstOrder); /* Check first order validity. */ require(validateOrderParameters(firstOrder, firstHash), "First order has invalid parameters"); /* Calculate second order hash. */ bytes32 secondHash = hashOrder(secondOrder); /* Check second order validity. */ require(validateOrderParameters(secondOrder, secondHash), "Second order has invalid parameters"); /* Prevent self-matching (possibly unnecessary, but safer). */ require(firstHash != secondHash, "Self-matching orders is prohibited"); { /* Calculate signatures (must be awkwardly decoded here due to stack size constraints). */ (bytes memory firstSignature, bytes memory secondSignature) = abi.decode(signatures, (bytes, bytes)); /* Check first order authorization. */ require(validateOrderAuthorization(firstHash, firstOrder.maker, firstSignature), "First order failed authorization"); /* Check second order authorization. */ require(validateOrderAuthorization(secondHash, secondOrder.maker, secondSignature), "Second order failed authorization"); //Console.log("firstHash",firstHash); } /* INTERACTIONS */ /* Transfer any msg.value. This is the first "asymmetric" part of order matching: if an order requires Ether, it must be the first order. */ if (msg.value > 0) { //payable(address(uint160(firstOrder.maker))).transfer(msg.value); require(payEthToProxy(ProxyRegistryInterface(secondOrder.registry), secondOrder.maker,msg.value), "payEthToProxy call failed"); } /* Execute first call, assert success. This is the second "asymmetric" part of order matching: execution of the second order can depend on state changes in the first order, but not vice-versa. */ require(executeCall(ProxyRegistryInterface(firstOrder.registry), firstOrder.maker, firstCall), "First call failed"); /* Execute second call, assert success. */ require(executeCall(ProxyRegistryInterface(secondOrder.registry), secondOrder.maker, secondCall), "Second call failed"); /* Static calls must happen after the effectful calls so that they can check the resulting state. */ /* Fetch previous first order fill. */ uint previousFirstFill = fills[firstOrder.maker][firstHash]; /* Fetch previous second order fill. */ uint previousSecondFill = fills[secondOrder.maker][secondHash]; /* Execute first order static call, assert success, capture returned new fill. */ uint firstFill = executeStaticCall(firstOrder, firstCall, secondOrder, secondCall, msg.sender, msg.value, previousFirstFill); /* Execute second order static call, assert success, capture returned new fill. */ uint secondFill = executeStaticCall(secondOrder, secondCall, firstOrder, firstCall, msg.sender, uint(0), previousSecondFill); /* EFFECTS */ /* Update first order fill, if necessary. */ if (firstOrder.maker != msg.sender) { if (firstFill != previousFirstFill) { fills[firstOrder.maker][firstHash] = firstFill; } } /* Update second order fill, if necessary. */ if (secondOrder.maker != msg.sender) { if (secondFill != previousSecondFill) { fills[secondOrder.maker][secondHash] = secondFill; } } /* LOGS */ /* Log match event. */ emit OrdersMatched(firstHash, secondHash, firstOrder.maker, secondOrder.maker, firstFill, secondFill, metadata); } } // File: localhost/SetExchange/exchange/Exchange.sol pragma solidity ^0.8.3; contract Exchange is ExchangeCore { /* external ABI-encodable method wrappers. */ function hashOrder_(address registry, address maker, address staticTarget, bytes4 staticSelector, bytes calldata staticExtradata, uint maximumFill, uint listingTime, uint expirationTime, uint salt) external pure returns (bytes32 hash) { return hashOrder(Order(registry, maker, staticTarget, staticSelector, staticExtradata, maximumFill, listingTime, expirationTime, salt)); } function hashToSign_(bytes32 orderHash) external view returns (bytes32 hash) { return hashToSign(orderHash); } function validateOrderParameters_(address registry, address maker, address staticTarget, bytes4 staticSelector, bytes calldata staticExtradata, uint maximumFill, uint listingTime, uint expirationTime, uint salt) external view returns (bool) { Order memory order = Order(registry, maker, staticTarget, staticSelector, staticExtradata, maximumFill, listingTime, expirationTime, salt); return validateOrderParameters(order, hashOrder(order)); } function validateOrderAuthorization_(bytes32 hash, address maker, bytes calldata signature) external view returns (bool) { return validateOrderAuthorization(hash, maker, signature); } function approveOrderHash_(bytes32 hash) external { return approveOrderHash(hash); } function approveOrder_(address registry, address maker, address staticTarget, bytes4 staticSelector, bytes calldata staticExtradata, uint maximumFill, uint listingTime, uint expirationTime, uint salt, bool orderbookInclusionDesired) external { return approveOrder(Order(registry, maker, staticTarget, staticSelector, staticExtradata, maximumFill, listingTime, expirationTime, salt), orderbookInclusionDesired); } function setOrderFill_(bytes32 hash, uint fill) external { return setOrderFill(hash, fill); } function atomicMatch_(address[8] memory addr,uint[8] memory uints, bytes4[2] memory staticSelectors, bytes memory firstExtradata, bytes memory firstCalldata, bytes memory secondExtradata, bytes memory secondCalldata, uint8[2] memory howToCalls, bytes32 metadata, bytes memory signatures) public payable { return atomicMatch( Order(addr[0], addr[1], addr[2], staticSelectors[0], firstExtradata, uints[0], uints[1], uints[2], uints[3]), Call(addr[3], AuthenticatedProxy.HowToCall(howToCalls[0]), firstCalldata), Order(addr[4], addr[5], addr[6], staticSelectors[1], secondExtradata, uints[4], uints[5], uints[6], uints[7]), Call(addr[7], AuthenticatedProxy.HowToCall(howToCalls[1]), secondCalldata), signatures, metadata ); } } // File: localhost/SetExchange/WyvernExchange.sol pragma solidity ^0.8.3; contract WyvernExchange is Exchange { string public constant name = "Wyvern Exchange"; string public constant version = "3.1"; string public constant codename = "Ancalagon"; //constructor (uint chainId, address[] memory registryAddrs, string memory customPersonalSignPrefix){ constructor (uint chainId, address[] memory registryAddrs){ DOMAIN_SEPARATOR = hash(EIP712Domain({ name : name, version : version, chainId : chainId, verifyingContract : address(this) })); for (uint i = 0; i < registryAddrs.length; i++) { registries[registryAddrs[i]] = true; } } }
Order must be listed and not be expired. / Order must not have already been completely filled. / Order static target must exist. /
function validateOrderParameters(Order memory order, bytes32 hash) internal view returns (bool) { if (order.listingTime > block.timestamp || (order.expirationTime != 0 && order.expirationTime <= block.timestamp)) { return false; } if (fills[order.maker][hash] >= order.maximumFill) { return false; } if (!exists(order.staticTarget)) { return false; } return true; }
15,420,273
// SPDX-License-Identifier: AGPL-3.0-or-later /// join.sol -- Basic token adapters // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; // FIXME: This contract was altered compared to the production version. // It doesn't use LibNote anymore. // New deployments of this contract will need to include custom events (TO DO). interface GemLike { function decimals() external view returns (uint); function transfer(address,uint) external returns (bool); function transferFrom(address,address,uint) external returns (bool); } interface DSTokenLike { function mint(address,uint) external; function burn(address,uint) external; } interface VatLike { function slip(bytes32,address,int) external; function move(address,address,uint) external; } /* Here we provide *adapters* to connect the Vat to arbitrary external token implementations, creating a bounded context for the Vat. The adapters here are provided as working examples: - `GemJoin`: For well behaved ERC20 tokens, with simple transfer semantics. - `ETHJoin`: For native Ether. - `USBJoin`: For connecting internal USB balances to an external `DSToken` implementation. In practice, adapter implementations will be varied and specific to individual collateral types, accounting for different transfer semantics and token standards. Adapters need to implement two basic methods: - `join`: enter collateral into the system - `exit`: remove collateral from the system */ contract GemJoin { // --- Auth --- mapping (address => uint) public wards; function rely(address usr) external auth { wards[usr] = 1; emit Rely(usr); } function deny(address usr) external auth { wards[usr] = 0; emit Deny(usr); } modifier auth { require(wards[msg.sender] == 1, "GemJoin/not-authorized"); _; } VatLike public vat; // CDP Engine bytes32 public ilk; // Collateral Type GemLike public gem; uint public dec; uint public live; // Active Flag // Events event Rely(address indexed usr); event Deny(address indexed usr); event Join(address indexed usr, uint256 wad); event Exit(address indexed usr, uint256 wad); event Cage(); constructor(address vat_, bytes32 ilk_, address gem_) public { wards[msg.sender] = 1; live = 1; vat = VatLike(vat_); ilk = ilk_; gem = GemLike(gem_); dec = gem.decimals(); emit Rely(msg.sender); } function cage() external auth { live = 0; emit Cage(); } function join(address usr, uint wad) external { require(live == 1, "GemJoin/not-live"); require(int(wad) >= 0, "GemJoin/overflow"); vat.slip(ilk, usr, int(wad)); require(gem.transferFrom(msg.sender, address(this), wad), "GemJoin/failed-transfer"); emit Join(usr, wad); } function exit(address usr, uint wad) external { require(wad <= 2 ** 255, "GemJoin/overflow"); vat.slip(ilk, msg.sender, -int(wad)); require(gem.transfer(usr, wad), "GemJoin/failed-transfer"); emit Exit(usr, wad); } } contract USBJoin { // --- Auth --- mapping (address => uint) public wards; function rely(address usr) external auth { wards[usr] = 1; emit Rely(usr); } function deny(address usr) external auth { wards[usr] = 0; emit Deny(usr); } modifier auth { require(wards[msg.sender] == 1, "USBJoin/not-authorized"); _; } VatLike public vat; // CDP Engine DSTokenLike public USB; // Stablecoin Token uint public live; // Active Flag // Events event Rely(address indexed usr); event Deny(address indexed usr); event Join(address indexed usr, uint256 wad); event Exit(address indexed usr, uint256 wad); event Cage(); constructor(address vat_, address USB_) public { wards[msg.sender] = 1; live = 1; vat = VatLike(vat_); USB = DSTokenLike(USB_); } function cage() external auth { live = 0; emit Cage(); } uint constant ONE = 10 ** 27; function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function join(address usr, uint wad) external { vat.move(address(this), usr, mul(ONE, wad)); USB.burn(msg.sender, wad); emit Join(usr, wad); } function exit(address usr, uint wad) external { require(live == 1, "USBJoin/not-live"); vat.move(msg.sender, address(this), mul(ONE, wad)); USB.mint(usr, wad); emit Exit(usr, wad); } } // SPDX-License-Identifier: AGPL-3.0-or-later /// clip.sol -- USB auction module 2.0 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; interface VatLike { function move(address,address,uint256) external; function flux(bytes32,address,address,uint256) external; function ilks(bytes32) external returns (uint256, uint256, uint256, uint256, uint256); function suck(address,address,uint256) external; } interface PipLike { function peek() external returns (bytes32, bool); } interface SpotterLike { function par() external returns (uint256); function ilks(bytes32) external returns (PipLike, uint256); } interface DogLike { function chop(bytes32) external returns (uint256); function digs(bytes32, uint256) external; } interface ClipperCallee { function clipperCall(address, uint256, uint256, bytes calldata) external; } interface AbacusLike { function price(uint256, uint256) external view returns (uint256); } contract Clipper { // --- Auth --- mapping (address => uint256) public wards; function rely(address usr) external auth { wards[usr] = 1; emit Rely(usr); } function deny(address usr) external auth { wards[usr] = 0; emit Deny(usr); } modifier auth { require(wards[msg.sender] == 1, "Clipper/not-authorized"); _; } // --- Data --- bytes32 immutable public ilk; // Collateral type of this Clipper VatLike immutable public vat; // Core CDP Engine DogLike public dog; // Liquidation module address public vow; // Recipient of USB raised in auctions SpotterLike public spotter; // Collateral price module AbacusLike public calc; // Current price calculator uint256 public buf; // Multiplicative factor to increase starting price [ray] uint256 public tail; // Time elapsed before auction reset [seconds] uint256 public cusp; // Percentage drop before auction reset [ray] uint64 public chip; // Percentage of tab to suck from vow to incentivize keepers [wad] uint192 public tip; // Flat fee to suck from vow to incentivize keepers [rad] uint256 public chost; // Cache the ilk dust times the ilk chop to prevent excessive SLOADs [rad] uint256 public kicks; // Total auctions uint256[] public active; // Array of active auction ids struct Sale { uint256 pos; // Index in active array uint256 tab; // USB to raise [rad] uint256 lot; // collateral to sell [wad] address usr; // Liquidated CDP uint96 tic; // Auction start time uint256 top; // Starting price [ray] } mapping(uint256 => Sale) public sales; uint256 internal locked; // Levels for circuit breaker // 0: no breaker // 1: no new kick() // 2: no new kick() or redo() // 3: no new kick(), redo(), or take() uint256 public stopped = 0; // --- Events --- event Rely(address indexed usr); event Deny(address indexed usr); event File(bytes32 indexed what, uint256 data); event File(bytes32 indexed what, address data); event Kick( uint256 indexed id, uint256 top, uint256 tab, uint256 lot, address indexed usr, address indexed kpr, uint256 coin ); event Take( uint256 indexed id, uint256 max, uint256 price, uint256 owe, uint256 tab, uint256 lot, address indexed usr ); event Redo( uint256 indexed id, uint256 top, uint256 tab, uint256 lot, address indexed usr, address indexed kpr, uint256 coin ); event Yank(uint256 id); // --- Init --- constructor(address vat_, address spotter_, address dog_, bytes32 ilk_) public { vat = VatLike(vat_); spotter = SpotterLike(spotter_); dog = DogLike(dog_); ilk = ilk_; buf = RAY; wards[msg.sender] = 1; emit Rely(msg.sender); } // --- Synchronization --- modifier lock { require(locked == 0, "Clipper/system-locked"); locked = 1; _; locked = 0; } modifier isStopped(uint256 level) { require(stopped < level, "Clipper/stopped-incorrect"); _; } // --- Administration --- function file(bytes32 what, uint256 data) external auth lock { if (what == "buf") buf = data; else if (what == "tail") tail = data; // Time elapsed before auction reset else if (what == "cusp") cusp = data; // Percentage drop before auction reset else if (what == "chip") chip = uint64(data); // Percentage of tab to incentivize (max: 2^64 - 1 => 18.xxx WAD = 18xx%) else if (what == "tip") tip = uint192(data); // Flat fee to incentivize keepers (max: 2^192 - 1 => 6.277T RAD) else if (what == "stopped") stopped = data; // Set breaker (0, 1, 2, or 3) else revert("Clipper/file-unrecognized-param"); emit File(what, data); } function file(bytes32 what, address data) external auth lock { if (what == "spotter") spotter = SpotterLike(data); else if (what == "dog") dog = DogLike(data); else if (what == "vow") vow = data; else if (what == "calc") calc = AbacusLike(data); else revert("Clipper/file-unrecognized-param"); emit File(what, data); } // --- Math --- uint256 constant BLN = 10 ** 9; uint256 constant WAD = 10 ** 18; uint256 constant RAY = 10 ** 27; function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x <= y ? x : y; } function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = mul(x, y) / WAD; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = mul(x, y) / RAY; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = mul(x, RAY) / y; } // --- Auction --- // get the price directly from the OSM // Could get this from rmul(Vat.ilks(ilk).spot, Spotter.mat()) instead, but // if mat has changed since the last poke, the resulting value will be // incorrect. function getFeedPrice() internal returns (uint256 feedPrice) { (PipLike pip, ) = spotter.ilks(ilk); (bytes32 val, bool has) = pip.peek(); require(has, "Clipper/invalid-price"); feedPrice = rdiv(mul(uint256(val), BLN), spotter.par()); } // start an auction // note: trusts the caller to transfer collateral to the contract // The starting price `top` is obtained as follows: // // top = val * buf / par // // Where `val` is the collateral's unitary value in USD, `buf` is a // multiplicative factor to increase the starting price, and `par` is a // reference per USB. function kick( uint256 tab, // Debt [rad] uint256 lot, // Collateral [wad] address usr, // Address that will receive any leftover collateral address kpr // Address that will receive incentives ) external auth lock isStopped(1) returns (uint256 id) { // Input validation require(tab > 0, "Clipper/zero-tab"); require(lot > 0, "Clipper/zero-lot"); require(usr != address(0), "Clipper/zero-usr"); id = ++kicks; require(id > 0, "Clipper/overflow"); active.push(id); sales[id].pos = active.length - 1; sales[id].tab = tab; sales[id].lot = lot; sales[id].usr = usr; sales[id].tic = uint96(block.timestamp); uint256 top; top = rmul(getFeedPrice(), buf); require(top > 0, "Clipper/zero-top-price"); sales[id].top = top; // incentive to kick auction uint256 _tip = tip; uint256 _chip = chip; uint256 coin; if (_tip > 0 || _chip > 0) { coin = add(_tip, wmul(tab, _chip)); vat.suck(vow, kpr, coin); } emit Kick(id, top, tab, lot, usr, kpr, coin); } // Reset an auction // See `kick` above for an explanation of the computation of `top`. function redo( uint256 id, // id of the auction to reset address kpr // Address that will receive incentives ) external lock isStopped(2) { // Read auction data address usr = sales[id].usr; uint96 tic = sales[id].tic; uint256 top = sales[id].top; require(usr != address(0), "Clipper/not-running-auction"); // Check that auction needs reset // and compute current price [ray] (bool done,) = status(tic, top); require(done, "Clipper/cannot-reset"); uint256 tab = sales[id].tab; uint256 lot = sales[id].lot; sales[id].tic = uint96(block.timestamp); uint256 feedPrice = getFeedPrice(); top = rmul(feedPrice, buf); require(top > 0, "Clipper/zero-top-price"); sales[id].top = top; // incentive to redo auction uint256 _tip = tip; uint256 _chip = chip; uint256 coin; if (_tip > 0 || _chip > 0) { uint256 _chost = chost; if (tab >= _chost && mul(lot, feedPrice) >= _chost) { coin = add(_tip, wmul(tab, _chip)); vat.suck(vow, kpr, coin); } } emit Redo(id, top, tab, lot, usr, kpr, coin); } // Buy up to `amt` of collateral from the auction indexed by `id`. // // Auctions will not collect more USB than their assigned USB target,`tab`; // thus, if `amt` would cost more USB than `tab` at the current price, the // amount of collateral purchased will instead be just enough to collect `tab` USB. // // To avoid partial purchases resulting in very small leftover auctions that will // never be cleared, any partial purchase must leave at least `Clipper.chost` // remaining USB target. `chost` is an asynchronously updated value equal to // (Vat.dust * Dog.chop(ilk) / WAD) where the values are understood to be determined // by whatever they were when Clipper.upchost() was last called. Purchase amounts // will be minimally decreased when necessary to respect this limit; i.e., if the // specified `amt` would leave `tab < chost` but `tab > 0`, the amount actually // purchased will be such that `tab == chost`. // // If `tab <= chost`, partial purchases are no longer possible; that is, the remaining // collateral can only be purchased entirely, or not at all. function take( uint256 id, // Auction id uint256 amt, // Upper limit on amount of collateral to buy [wad] uint256 max, // Maximum acceptable price (USB / collateral) [ray] address who, // Receiver of collateral and external call address bytes calldata data // Data to pass in external call; if length 0, no call is done ) external lock isStopped(3) { address usr = sales[id].usr; uint96 tic = sales[id].tic; require(usr != address(0), "Clipper/not-running-auction"); uint256 price; { bool done; (done, price) = status(tic, sales[id].top); // Check that auction doesn't need reset require(!done, "Clipper/needs-reset"); } // Ensure price is acceptable to buyer require(max >= price, "Clipper/too-expensive"); uint256 lot = sales[id].lot; uint256 tab = sales[id].tab; uint256 owe; { // Purchase as much as possible, up to amt uint256 slice = min(lot, amt); // slice <= lot // USB needed to buy a slice of this sale owe = mul(slice, price); // Don't collect more than tab of USB if (owe > tab) { // Total debt will be paid owe = tab; // owe' <= owe // Adjust slice slice = owe / price; // slice' = owe' / price <= owe / price == slice <= lot } else if (owe < tab && slice < lot) { // If slice == lot => auction completed => dust doesn't matter uint256 _chost = chost; if (tab - owe < _chost) { // safe as owe < tab // If tab <= chost, buyers have to take the entire lot. require(tab > _chost, "Clipper/no-partial-purchase"); // Adjust amount to pay owe = tab - _chost; // owe' <= owe // Adjust slice slice = owe / price; // slice' = owe' / price < owe / price == slice < lot } } // Calculate remaining tab after operation tab = tab - owe; // safe since owe <= tab // Calculate remaining lot after operation lot = lot - slice; // Send collateral to who vat.flux(ilk, address(this), who, slice); // Do external call (if data is defined) but to be // extremely careful we don't allow to do it to the two // contracts which the Clipper needs to be authorized DogLike dog_ = dog; if (data.length > 0 && who != address(vat) && who != address(dog_)) { ClipperCallee(who).clipperCall(msg.sender, owe, slice, data); } // Get USB from caller vat.move(msg.sender, vow, owe); // Removes USB out for liquidation from accumulator dog_.digs(ilk, lot == 0 ? tab + owe : owe); } if (lot == 0) { _remove(id); } else if (tab == 0) { vat.flux(ilk, address(this), usr, lot); _remove(id); } else { sales[id].tab = tab; sales[id].lot = lot; } emit Take(id, max, price, owe, tab, lot, usr); } function _remove(uint256 id) internal { uint256 _move = active[active.length - 1]; if (id != _move) { uint256 _index = sales[id].pos; active[_index] = _move; sales[_move].pos = _index; } active.pop(); delete sales[id]; } // The number of active auctions function count() external view returns (uint256) { return active.length; } // Return the entire array of active auctions function list() external view returns (uint256[] memory) { return active; } // Externally returns boolean for if an auction needs a redo and also the current price function getStatus(uint256 id) external view returns (bool needsRedo, uint256 price, uint256 lot, uint256 tab) { // Read auction data address usr = sales[id].usr; uint96 tic = sales[id].tic; bool done; (done, price) = status(tic, sales[id].top); needsRedo = usr != address(0) && done; lot = sales[id].lot; tab = sales[id].tab; } // Internally returns boolean for if an auction needs a redo function status(uint96 tic, uint256 top) internal view returns (bool done, uint256 price) { price = calc.price(top, sub(block.timestamp, tic)); done = (sub(block.timestamp, tic) > tail || rdiv(price, top) < cusp); } // Public function to update the cached dust*chop value. function upchost() external { (,,,, uint256 _dust) = VatLike(vat).ilks(ilk); chost = wmul(_dust, dog.chop(ilk)); } // Cancel an auction during ES or via governance action. function yank(uint256 id) external auth lock { require(sales[id].usr != address(0), "Clipper/not-running-auction"); dog.digs(ilk, sales[id].tab); vat.flux(ilk, address(this), msg.sender, sales[id].lot); _remove(id); emit Yank(id); } } /// VoteProxy.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // vote w/ a hot or cold wallet using a proxy identity pragma solidity >=0.4.24; interface TokenLike { function balanceOf(address) external view returns (uint256); function approve(address, uint256) external; function pull(address, uint256) external; function push(address, uint256) external; } interface ChiefLike { function GOV() external view returns (TokenLike); function IOU() external view returns (TokenLike); function deposits(address) external view returns (uint256); function lock(uint256) external; function free(uint256) external; function vote(address[] calldata) external returns (bytes32); function vote(bytes32) external; } contract VoteProxy { address public cold; address public hot; TokenLike public gov; TokenLike public iou; ChiefLike public chief; constructor(address _chief, address _cold, address _hot) public { chief = ChiefLike(_chief); cold = _cold; hot = _hot; gov = chief.GOV(); iou = chief.IOU(); gov.approve(address(chief), type(uint256).max); iou.approve(address(chief), type(uint256).max); } modifier auth() { require(msg.sender == hot || msg.sender == cold, "Sender must be a Cold or Hot Wallet"); _; } function lock(uint256 wad) public auth { gov.pull(cold, wad); // mkr from cold chief.lock(wad); // mkr out, ious in } function free(uint256 wad) public auth { chief.free(wad); // ious out, mkr in gov.push(cold, wad); // mkr to cold } function freeAll() public auth { chief.free(chief.deposits(address(this))); gov.push(cold, gov.balanceOf(address(this))); } function vote(address[] memory yays) public auth returns (bytes32) { return chief.vote(yays); } function vote(bytes32 slate) public auth { chief.vote(slate); } } // SPDX-License-Identifier: AGPL-3.0-or-later /// flop.sol -- Debt auction // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; // FIXME: This contract was altered compared to the production version. // It doesn't use LibNote anymore. // New deployments of this contract will need to include custom events (TO DO). interface VatLike { function move(address,address,uint) external; function suck(address,address,uint) external; } interface GemLike { function mint(address,uint) external; } interface VowLike { function Ash() external returns (uint); function kiss(uint) external; } /* This thing creates gems on demand in return for USB. - `lot` gems in return for bid - `bid` USB paid - `gal` receives USB income - `ttl` single bid lifetime - `beg` minimum bid increase - `end` max auction duration */ contract Flopper { // --- Auth --- mapping (address => uint) public wards; function rely(address usr) external auth { wards[usr] = 1; } function deny(address usr) external auth { wards[usr] = 0; } modifier auth { require(wards[msg.sender] == 1, "Flopper/not-authorized"); _; } // --- Data --- struct Bid { uint256 bid; // USB paid [rad] uint256 lot; // gems in return for bid [wad] address guy; // high bidder uint48 tic; // bid expiry time [unix epoch time] uint48 end; // auction expiry time [unix epoch time] } mapping (uint => Bid) public bids; VatLike public vat; // CDP Engine GemLike public gem; uint256 constant ONE = 1.00E18; uint256 public beg = 1.05E18; // 5% minimum bid increase uint256 public pad = 1.50E18; // 50% lot increase for tick uint48 public ttl = 3 hours; // 3 hours bid lifetime [seconds] uint48 public tau = 2 days; // 2 days total auction length [seconds] uint256 public kicks = 0; uint256 public live; // Active Flag address public vow; // not used until shutdown // --- Events --- event Kick( uint256 id, uint256 lot, uint256 bid, address indexed gal ); // --- Init --- constructor(address vat_, address gem_) public { wards[msg.sender] = 1; vat = VatLike(vat_); gem = GemLike(gem_); live = 1; } // --- Math --- function add(uint48 x, uint48 y) internal pure returns (uint48 z) { require((z = x + y) >= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function min(uint x, uint y) internal pure returns (uint z) { if (x > y) { z = y; } else { z = x; } } // --- Admin --- function file(bytes32 what, uint data) external auth { if (what == "beg") beg = data; else if (what == "pad") pad = data; else if (what == "ttl") ttl = uint48(data); else if (what == "tau") tau = uint48(data); else revert("Flopper/file-unrecognized-param"); } // --- Auction --- function kick(address gal, uint lot, uint bid) external auth returns (uint id) { require(live == 1, "Flopper/not-live"); require(kicks < type(uint256).max, "Flopper/overflow"); id = ++kicks; bids[id].bid = bid; bids[id].lot = lot; bids[id].guy = gal; bids[id].end = add(uint48(block.timestamp), tau); emit Kick(id, lot, bid, gal); } function tick(uint id) external { require(bids[id].end < block.timestamp, "Flopper/not-finished"); require(bids[id].tic == 0, "Flopper/bid-already-placed"); bids[id].lot = mul(pad, bids[id].lot) / ONE; bids[id].end = add(uint48(block.timestamp), tau); } function dent(uint id, uint lot, uint bid) external { require(live == 1, "Flopper/not-live"); require(bids[id].guy != address(0), "Flopper/guy-not-set"); require(bids[id].tic > block.timestamp || bids[id].tic == 0, "Flopper/already-finished-tic"); require(bids[id].end > block.timestamp, "Flopper/already-finished-end"); require(bid == bids[id].bid, "Flopper/not-matching-bid"); require(lot < bids[id].lot, "Flopper/lot-not-lower"); require(mul(beg, lot) <= mul(bids[id].lot, ONE), "Flopper/insufficient-decrease"); if (msg.sender != bids[id].guy) { vat.move(msg.sender, bids[id].guy, bid); // on first dent, clear as much Ash as possible if (bids[id].tic == 0) { uint Ash = VowLike(bids[id].guy).Ash(); VowLike(bids[id].guy).kiss(min(bid, Ash)); } bids[id].guy = msg.sender; } bids[id].lot = lot; bids[id].tic = add(uint48(block.timestamp), ttl); } function deal(uint id) external { require(live == 1, "Flopper/not-live"); require(bids[id].tic != 0 && (bids[id].tic < block.timestamp || bids[id].end < block.timestamp), "Flopper/not-finished"); gem.mint(bids[id].guy, bids[id].lot); delete bids[id]; } // --- Shutdown --- function cage() external auth { live = 0; vow = msg.sender; } function yank(uint id) external { require(live == 0, "Flopper/still-live"); require(bids[id].guy != address(0), "Flopper/guy-not-set"); vat.suck(vow, bids[id].guy, bids[id].bid); delete bids[id]; } } // SPDX-License-Identifier: AGPL-3.0-or-later /// cat.sol -- USB liquidation module // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; // FIXME: This contract was altered compared to the production version. // It doesn't use LibNote anymore. // New deployments of this contract will need to include custom events (TO DO). interface Kicker { function kick(address urn, address gal, uint256 tab, uint256 lot, uint256 bid) external returns (uint256); } interface VatLike { function ilks(bytes32) external view returns ( uint256 Art, // [wad] uint256 rate, // [ray] uint256 spot, // [ray] uint256 line, // [rad] uint256 dust // [rad] ); function urns(bytes32,address) external view returns ( uint256 ink, // [wad] uint256 art // [wad] ); function grab(bytes32,address,address,address,int256,int256) external; function hope(address) external; function nope(address) external; } interface VowLike { function fess(uint256) external; } contract Cat { // --- Auth --- mapping (address => uint256) public wards; function rely(address usr) external auth { wards[usr] = 1; } function deny(address usr) external auth { wards[usr] = 0; } modifier auth { require(wards[msg.sender] == 1, "Cat/not-authorized"); _; } // --- Data --- struct Ilk { address flip; // Liquidator uint256 chop; // Liquidation Penalty [wad] uint256 dunk; // Liquidation Quantity [rad] } mapping (bytes32 => Ilk) public ilks; uint256 public live; // Active Flag VatLike public vat; // CDP Engine VowLike public vow; // Debt Engine uint256 public box; // Max USB out for liquidation [rad] uint256 public litter; // Balance of USB out for liquidation [rad] // --- Events --- event Bite( bytes32 indexed ilk, address indexed urn, uint256 ink, uint256 art, uint256 tab, address flip, uint256 id ); // --- Init --- constructor(address vat_) public { wards[msg.sender] = 1; vat = VatLike(vat_); live = 1; } // --- Math --- uint256 constant WAD = 10 ** 18; function min(uint256 x, uint256 y) internal pure returns (uint256 z) { if (x > y) { z = y; } else { z = x; } } function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- function file(bytes32 what, address data) external auth { if (what == "vow") vow = VowLike(data); else revert("Cat/file-unrecognized-param"); } function file(bytes32 what, uint256 data) external auth { if (what == "box") box = data; else revert("Cat/file-unrecognized-param"); } function file(bytes32 ilk, bytes32 what, uint256 data) external auth { if (what == "chop") ilks[ilk].chop = data; else if (what == "dunk") ilks[ilk].dunk = data; else revert("Cat/file-unrecognized-param"); } function file(bytes32 ilk, bytes32 what, address flip) external auth { if (what == "flip") { vat.nope(ilks[ilk].flip); ilks[ilk].flip = flip; vat.hope(flip); } else revert("Cat/file-unrecognized-param"); } // --- CDP Liquidation --- function bite(bytes32 ilk, address urn) external returns (uint256 id) { (,uint256 rate,uint256 spot,,uint256 dust) = vat.ilks(ilk); (uint256 ink, uint256 art) = vat.urns(ilk, urn); require(live == 1, "Cat/not-live"); require(spot > 0 && mul(ink, spot) < mul(art, rate), "Cat/not-unsafe"); Ilk memory milk = ilks[ilk]; uint256 dart; { uint256 room = sub(box, litter); // test whether the remaining space in the litterbox is dusty require(litter < box && room >= dust, "Cat/liquidation-limit-hit"); dart = min(art, mul(min(milk.dunk, room), WAD) / rate / milk.chop); } uint256 dink = min(ink, mul(ink, dart) / art); require(dart > 0 && dink > 0 , "Cat/null-auction"); require(dart <= 2**255 && dink <= 2**255, "Cat/overflow" ); // This may leave the CDP in a dusty state vat.grab( ilk, urn, address(this), address(vow), -int256(dink), -int256(dart) ); vow.fess(mul(dart, rate)); { // Avoid stack too deep // This calcuation will overflow if dart*rate exceeds ~10^14, // i.e. the maximum dunk is roughly 100 trillion USB. uint256 tab = mul(mul(dart, rate), milk.chop) / WAD; litter = add(litter, tab); id = Kicker(milk.flip).kick({ urn: urn, gal: address(vow), tab: tab, lot: dink, bid: 0 }); } emit Bite(ilk, urn, dink, dart, mul(dart, rate), milk.flip, id); } function claw(uint256 rad) external auth { litter = sub(litter, rad); } function cage() external auth { live = 0; } } // SPDX-License-Identifier: AGPL-3.0-or-later /// vow.sol -- USB settlement module // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; // FIXME: This contract was altered compared to the production version. // It doesn't use LibNote anymore. // New deployments of this contract will need to include custom events (TO DO). interface FlopLike { function kick(address gal, uint lot, uint bid) external returns (uint); function cage() external; function live() external returns (uint); } interface FlapLike { function kick(uint lot, uint bid) external returns (uint); function cage(uint) external; function live() external returns (uint); } interface VatLike { function USB (address) external view returns (uint); function sin (address) external view returns (uint); function heal(uint256) external; function hope(address) external; function nope(address) external; } contract Vow { // --- Auth --- mapping (address => uint) public wards; function rely(address usr) external auth { require(live == 1, "Vow/not-live"); wards[usr] = 1; } function deny(address usr) external auth { wards[usr] = 0; } modifier auth { require(wards[msg.sender] == 1, "Vow/not-authorized"); _; } // --- Data --- VatLike public vat; // CDP Engine FlapLike public flapper; // Surplus Auction House FlopLike public flopper; // Debt Auction House mapping (uint256 => uint256) public sin; // debt queue uint256 public Sin; // Queued debt [rad] uint256 public Ash; // On-auction debt [rad] uint256 public wait; // Flop delay [seconds] uint256 public dump; // Flop initial lot size [wad] uint256 public sump; // Flop fixed bid size [rad] uint256 public bump; // Flap fixed lot size [rad] uint256 public hump; // Surplus buffer [rad] uint256 public live; // Active Flag // --- Init --- constructor(address vat_, address flapper_, address flopper_) public { wards[msg.sender] = 1; vat = VatLike(vat_); flapper = FlapLike(flapper_); flopper = FlopLike(flopper_); vat.hope(flapper_); live = 1; } // --- Math --- function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } // --- Administration --- function file(bytes32 what, uint data) external auth { if (what == "wait") wait = data; else if (what == "bump") bump = data; else if (what == "sump") sump = data; else if (what == "dump") dump = data; else if (what == "hump") hump = data; else revert("Vow/file-unrecognized-param"); } function file(bytes32 what, address data) external auth { if (what == "flapper") { vat.nope(address(flapper)); flapper = FlapLike(data); vat.hope(data); } else if (what == "flopper") flopper = FlopLike(data); else revert("Vow/file-unrecognized-param"); } // Push to debt-queue function fess(uint tab) external auth { sin[block.timestamp] = add(sin[block.timestamp], tab); Sin = add(Sin, tab); } // Pop from debt-queue function flog(uint era) external { require(add(era, wait) <= block.timestamp, "Vow/wait-not-finished"); Sin = sub(Sin, sin[era]); sin[era] = 0; } // Debt settlement function heal(uint rad) external { require(rad <= vat.USB(address(this)), "Vow/insufficient-surplus"); require(rad <= sub(sub(vat.sin(address(this)), Sin), Ash), "Vow/insufficient-debt"); vat.heal(rad); } function kiss(uint rad) external { require(rad <= Ash, "Vow/not-enough-ash"); require(rad <= vat.USB(address(this)), "Vow/insufficient-surplus"); Ash = sub(Ash, rad); vat.heal(rad); } // Debt auction function flop() external returns (uint id) { require(sump <= sub(sub(vat.sin(address(this)), Sin), Ash), "Vow/insufficient-debt"); require(vat.USB(address(this)) == 0, "Vow/surplus-not-zero"); Ash = add(Ash, sump); id = flopper.kick(address(this), dump, sump); } // Surplus auction function flap() external returns (uint id) { require(vat.USB(address(this)) >= add(add(vat.sin(address(this)), bump), hump), "Vow/insufficient-surplus"); require(sub(sub(vat.sin(address(this)), Sin), Ash) == 0, "Vow/debt-not-zero"); id = flapper.kick(bump, 0); } function cage() external auth { require(live == 1, "Vow/not-live"); live = 0; Sin = 0; Ash = 0; flapper.cage(vat.USB(address(flapper))); flopper.cage(); vat.heal(min(vat.USB(address(this)), vat.sin(address(this)))); } } // SPDX-License-Identifier: AGPL-3.0-or-later /// end.sol -- global settlement engine // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; interface VatLike { function dai(address) external view returns (uint256); function ilks(bytes32 ilk) external returns ( uint256 Art, // [wad] uint256 rate, // [ray] uint256 spot, // [ray] uint256 line, // [rad] uint256 dust // [rad] ); function urns(bytes32 ilk, address urn) external returns ( uint256 ink, // [wad] uint256 art // [wad] ); function debt() external returns (uint256); function move(address src, address dst, uint256 rad) external; function hope(address) external; function flux(bytes32 ilk, address src, address dst, uint256 rad) external; function grab(bytes32 i, address u, address v, address w, int256 dink, int256 dart) external; function suck(address u, address v, uint256 rad) external; function cage() external; } interface CatLike { function ilks(bytes32) external returns ( address flip, uint256 chop, // [ray] uint256 lump // [rad] ); function cage() external; } interface DogLike { function ilks(bytes32) external returns ( address clip, uint256 chop, uint256 hole, uint256 dirt ); function cage() external; } interface PotLike { function cage() external; } interface VowLike { function cage() external; } interface FlipLike { function bids(uint256 id) external view returns ( uint256 bid, // [rad] uint256 lot, // [wad] address guy, uint48 tic, // [unix epoch time] uint48 end, // [unix epoch time] address usr, address gal, uint256 tab // [rad] ); function yank(uint256 id) external; } interface ClipLike { function sales(uint256 id) external view returns ( uint256 pos, uint256 tab, uint256 lot, address usr, uint96 tic, uint256 top ); function yank(uint256 id) external; } interface PipLike { function read() external view returns (bytes32); } interface SpotLike { function par() external view returns (uint256); function ilks(bytes32) external view returns ( PipLike pip, uint256 mat // [ray] ); function cage() external; } /* This is the `End` and it coordinates Global Settlement. This is an involved, stateful process that takes place over nine steps. First we freeze the system and lock the prices for each ilk. 1. `cage()`: - freezes user entrypoints - cancels flop/flap auctions - starts cooldown period - stops pot drips 2. `cage(ilk)`: - set the cage price for each `ilk`, reading off the price feed We must process some system state before it is possible to calculate the final dai / collateral price. In particular, we need to determine a. `gap`, the collateral shortfall per collateral type by considering under-collateralised CDPs. b. `debt`, the outstanding dai supply after including system surplus / deficit We determine (a) by processing all under-collateralised CDPs with `skim`: 3. `skim(ilk, urn)`: - cancels CDP debt - any excess collateral remains - backing collateral taken We determine (b) by processing ongoing dai generating processes, i.e. auctions. We need to ensure that auctions will not generate any further dai income. In the two-way auction model (Flipper) this occurs when all auctions are in the reverse (`dent`) phase. There are two ways of ensuring this: 4a. i) `wait`: set the cooldown period to be at least as long as the longest auction duration, which needs to be determined by the cage administrator. This takes a fairly predictable time to occur but with altered auction dynamics due to the now varying price of dai. ii) `skip`: cancel all ongoing auctions and seize the collateral. This allows for faster processing at the expense of more processing calls. This option allows dai holders to retrieve their collateral faster. `skip(ilk, id)`: - cancel individual flip auctions in the `tend` (forward) phase - retrieves collateral and debt (including penalty) to owner's CDP - returns dai to last bidder - `dent` (reverse) phase auctions can continue normally Option (i), `wait`, is sufficient (if all auctions were bidded at least once) for processing the system settlement but option (ii), `skip`, will speed it up. Both options are available in this implementation, with `skip` being enabled on a per-auction basis. In the case of the Dutch Auctions model (Clipper) they keep recovering debt during the whole lifetime and there isn't a max duration time guaranteed for the auction to end. So the way to ensure the protocol will not receive extra dai income is: 4b. i) `snip`: cancel all ongoing auctions and seize the collateral. `snip(ilk, id)`: - cancel individual running clip auctions - retrieves remaining collateral and debt (including penalty) to owner's CDP When a CDP has been processed and has no debt remaining, the remaining collateral can be removed. 5. `free(ilk)`: - remove collateral from the caller's CDP - owner can call as needed After the processing period has elapsed, we enable calculation of the final price for each collateral type. 6. `thaw()`: - only callable after processing time period elapsed - assumption that all under-collateralised CDPs are processed - fixes the total outstanding supply of dai - may also require extra CDP processing to cover vow surplus 7. `flow(ilk)`: - calculate the `fix`, the cash price for a given ilk - adjusts the `fix` in the case of deficit / surplus At this point we have computed the final price for each collateral type and dai holders can now turn their dai into collateral. Each unit dai can claim a fixed basket of collateral. Dai holders must first `pack` some dai into a `bag`. Once packed, dai cannot be unpacked and is not transferrable. More dai can be added to a bag later. 8. `pack(wad)`: - put some dai into a bag in preparation for `cash` Finally, collateral can be obtained with `cash`. The bigger the bag, the more collateral can be released. 9. `cash(ilk, wad)`: - exchange some dai from your bag for gems from a specific ilk - the number of gems is limited by how big your bag is */ contract End { // --- Auth --- mapping (address => uint256) public wards; function rely(address usr) external auth { wards[usr] = 1; emit Rely(usr); } function deny(address usr) external auth { wards[usr] = 0; emit Deny(usr); } modifier auth { require(wards[msg.sender] == 1, "End/not-authorized"); _; } // --- Data --- VatLike public vat; // CDP Engine CatLike public cat; DogLike public dog; VowLike public vow; // Debt Engine PotLike public pot; SpotLike public spot; uint256 public live; // Active Flag uint256 public when; // Time of cage [unix epoch time] uint256 public wait; // Processing Cooldown Length [seconds] uint256 public debt; // Total outstanding dai following processing [rad] mapping (bytes32 => uint256) public tag; // Cage price [ray] mapping (bytes32 => uint256) public gap; // Collateral shortfall [wad] mapping (bytes32 => uint256) public Art; // Total debt per ilk [wad] mapping (bytes32 => uint256) public fix; // Final cash price [ray] mapping (address => uint256) public bag; // [wad] mapping (bytes32 => mapping (address => uint256)) public out; // [wad] // --- Events --- event Rely(address indexed usr); event Deny(address indexed usr); event File(bytes32 indexed what, uint256 data); event File(bytes32 indexed what, address data); event Cage(); event Cage(bytes32 indexed ilk); event Snip(bytes32 indexed ilk, uint256 indexed id, address indexed usr, uint256 tab, uint256 lot, uint256 art); event Skip(bytes32 indexed ilk, uint256 indexed id, address indexed usr, uint256 tab, uint256 lot, uint256 art); event Skim(bytes32 indexed ilk, address indexed urn, uint256 wad, uint256 art); event Free(bytes32 indexed ilk, address indexed usr, uint256 ink); event Thaw(); event Flow(bytes32 indexed ilk); event Pack(address indexed usr, uint256 wad); event Cash(bytes32 indexed ilk, address indexed usr, uint256 wad); // --- Init --- constructor() public { wards[msg.sender] = 1; live = 1; emit Rely(msg.sender); } // --- Math --- uint256 constant WAD = 10 ** 18; uint256 constant RAY = 10 ** 27; function add(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x + y; require(z >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { return x <= y ? x : y; } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = mul(x, y) / RAY; } function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { z = mul(x, WAD) / y; } // --- Administration --- function file(bytes32 what, address data) external auth { require(live == 1, "End/not-live"); if (what == "vat") vat = VatLike(data); else if (what == "cat") cat = CatLike(data); else if (what == "dog") dog = DogLike(data); else if (what == "vow") vow = VowLike(data); else if (what == "pot") pot = PotLike(data); else if (what == "spot") spot = SpotLike(data); else revert("End/file-unrecognized-param"); emit File(what, data); } function file(bytes32 what, uint256 data) external auth { require(live == 1, "End/not-live"); if (what == "wait") wait = data; else revert("End/file-unrecognized-param"); emit File(what, data); } // --- Settlement --- function cage() external auth { require(live == 1, "End/not-live"); live = 0; when = block.timestamp; vat.cage(); cat.cage(); dog.cage(); vow.cage(); spot.cage(); pot.cage(); emit Cage(); } function cage(bytes32 ilk) external { require(live == 0, "End/still-live"); require(tag[ilk] == 0, "End/tag-ilk-already-defined"); (Art[ilk],,,,) = vat.ilks(ilk); (PipLike pip,) = spot.ilks(ilk); // par is a ray, pip returns a wad tag[ilk] = wdiv(spot.par(), uint256(pip.read())); emit Cage(ilk); } function snip(bytes32 ilk, uint256 id) external { require(tag[ilk] != 0, "End/tag-ilk-not-defined"); (address _clip,,,) = dog.ilks(ilk); ClipLike clip = ClipLike(_clip); (, uint256 rate,,,) = vat.ilks(ilk); (, uint256 tab, uint256 lot, address usr,,) = clip.sales(id); vat.suck(address(vow), address(vow), tab); clip.yank(id); uint256 art = tab / rate; Art[ilk] = add(Art[ilk], art); require(int256(lot) >= 0 && int256(art) >= 0, "End/overflow"); vat.grab(ilk, usr, address(this), address(vow), int256(lot), int256(art)); emit Snip(ilk, id, usr, tab, lot, art); } function skip(bytes32 ilk, uint256 id) external { require(tag[ilk] != 0, "End/tag-ilk-not-defined"); (address _flip,,) = cat.ilks(ilk); FlipLike flip = FlipLike(_flip); (, uint256 rate,,,) = vat.ilks(ilk); (uint256 bid, uint256 lot,,,, address usr,, uint256 tab) = flip.bids(id); vat.suck(address(vow), address(vow), tab); vat.suck(address(vow), address(this), bid); vat.hope(address(flip)); flip.yank(id); uint256 art = tab / rate; Art[ilk] = add(Art[ilk], art); require(int256(lot) >= 0 && int256(art) >= 0, "End/overflow"); vat.grab(ilk, usr, address(this), address(vow), int256(lot), int256(art)); emit Skip(ilk, id, usr, tab, lot, art); } function skim(bytes32 ilk, address urn) external { require(tag[ilk] != 0, "End/tag-ilk-not-defined"); (, uint256 rate,,,) = vat.ilks(ilk); (uint256 ink, uint256 art) = vat.urns(ilk, urn); uint256 owe = rmul(rmul(art, rate), tag[ilk]); uint256 wad = min(ink, owe); gap[ilk] = add(gap[ilk], sub(owe, wad)); require(wad <= 2**255 && art <= 2**255, "End/overflow"); vat.grab(ilk, urn, address(this), address(vow), -int256(wad), -int256(art)); emit Skim(ilk, urn, wad, art); } function free(bytes32 ilk) external { require(live == 0, "End/still-live"); (uint256 ink, uint256 art) = vat.urns(ilk, msg.sender); require(art == 0, "End/art-not-zero"); require(ink <= 2**255, "End/overflow"); vat.grab(ilk, msg.sender, msg.sender, address(vow), -int256(ink), 0); emit Free(ilk, msg.sender, ink); } function thaw() external { require(live == 0, "End/still-live"); require(debt == 0, "End/debt-not-zero"); require(vat.dai(address(vow)) == 0, "End/surplus-not-zero"); require(block.timestamp >= add(when, wait), "End/wait-not-finished"); debt = vat.debt(); emit Thaw(); } function flow(bytes32 ilk) external { require(debt != 0, "End/debt-zero"); require(fix[ilk] == 0, "End/fix-ilk-already-defined"); (, uint256 rate,,,) = vat.ilks(ilk); uint256 wad = rmul(rmul(Art[ilk], rate), tag[ilk]); fix[ilk] = mul(sub(wad, gap[ilk]), RAY) / (debt / RAY); emit Flow(ilk); } function pack(uint256 wad) external { require(debt != 0, "End/debt-zero"); vat.move(msg.sender, address(vow), mul(wad, RAY)); bag[msg.sender] = add(bag[msg.sender], wad); emit Pack(msg.sender, wad); } function cash(bytes32 ilk, uint256 wad) external { require(fix[ilk] != 0, "End/fix-ilk-not-defined"); vat.flux(ilk, address(this), msg.sender, rmul(wad, fix[ilk])); out[ilk][msg.sender] = add(out[ilk][msg.sender], wad); require(out[ilk][msg.sender] <= bag[msg.sender], "End/insufficient-bag-balance"); emit Cash(ilk, msg.sender, wad); } } // DsrManager.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; interface VatLike { function hope(address) external; } interface PotLike { function vat() external view returns (address); function chi() external view returns (uint256); function rho() external view returns (uint256); function drip() external returns (uint256); function join(uint256) external; function exit(uint256) external; } interface JoinLike { function USB() external view returns (address); function join(address, uint256) external; function exit(address, uint256) external; } interface GemLike { function transferFrom(address,address,uint256) external returns (bool); function approve(address,uint256) external returns (bool); } contract DsrManager { PotLike public pot; GemLike public USB; JoinLike public USBJoin; uint256 public supply; mapping (address => uint256) public pieOf; event Join(address indexed dst, uint256 wad); event Exit(address indexed dst, uint256 wad); uint256 constant RAY = 10 ** 27; function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { // always rounds down z = mul(x, y) / RAY; } function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) { // always rounds down z = mul(x, RAY) / y; } function rdivup(uint256 x, uint256 y) internal pure returns (uint256 z) { // always rounds up z = add(mul(x, RAY), sub(y, 1)) / y; } constructor(address pot_, address USBJoin_) public { pot = PotLike(pot_); USBJoin = JoinLike(USBJoin_); USB = GemLike(USBJoin.USB()); VatLike vat = VatLike(pot.vat()); vat.hope(address(USBJoin)); vat.hope(address(pot)); USB.approve(address(USBJoin), type(uint256).max); } function USBBalance(address usr) external returns (uint256 wad) { uint256 chi = (block.timestamp > pot.rho()) ? pot.drip() : pot.chi(); wad = rmul(chi, pieOf[usr]); } // wad is denominated in USB function join(address dst, uint256 wad) external { uint256 chi = (block.timestamp > pot.rho()) ? pot.drip() : pot.chi(); uint256 pie = rdiv(wad, chi); pieOf[dst] = add(pieOf[dst], pie); supply = add(supply, pie); USB.transferFrom(msg.sender, address(this), wad); USBJoin.join(address(this), wad); pot.join(pie); emit Join(dst, wad); } // wad is denominated in USB function exit(address dst, uint256 wad) external { uint256 chi = (block.timestamp > pot.rho()) ? pot.drip() : pot.chi(); uint256 pie = rdivup(wad, chi); require(pieOf[msg.sender] >= pie, "insufficient-balance"); pieOf[msg.sender] = sub(pieOf[msg.sender], pie); supply = sub(supply, pie); pot.exit(pie); uint256 amt = rmul(chi, pie); USBJoin.exit(dst, amt); emit Exit(dst, amt); } function exitAll(address dst) external { uint256 chi = (block.timestamp > pot.rho()) ? pot.drip() : pot.chi(); uint256 pie = pieOf[msg.sender]; pieOf[msg.sender] = 0; supply = sub(supply, pie); pot.exit(pie); uint256 amt = rmul(chi, pie); USBJoin.exit(dst, amt); emit Exit(dst, amt); } } // SPDX-License-Identifier: AGPL-3.0-or-later /// flip.sol -- Collateral auction // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; // FIXME: This contract was altered compared to the production version. // It doesn't use LibNote anymore. // New deployments of this contract will need to include custom events (TO DO). interface VatLike { function move(address,address,uint256) external; function flux(bytes32,address,address,uint256) external; } interface CatLike { function claw(uint256) external; } /* This thing lets you flip some gems for a given amount of USB. Once the given amount of USB is raised, gems are forgone instead. - `lot` gems in return for bid - `tab` total USB wanted - `bid` USB paid - `gal` receives USB income - `usr` receives gem forgone - `ttl` single bid lifetime - `beg` minimum bid increase - `end` max auction duration */ contract Flipper { // --- Auth --- mapping (address => uint256) public wards; function rely(address usr) external auth { wards[usr] = 1; } function deny(address usr) external auth { wards[usr] = 0; } modifier auth { require(wards[msg.sender] == 1, "Flipper/not-authorized"); _; } // --- Data --- struct Bid { uint256 bid; // USB paid [rad] uint256 lot; // gems in return for bid [wad] address guy; // high bidder uint48 tic; // bid expiry time [unix epoch time] uint48 end; // auction expiry time [unix epoch time] address usr; address gal; uint256 tab; // total USB wanted [rad] } mapping (uint256 => Bid) public bids; VatLike public vat; // CDP Engine bytes32 public ilk; // collateral type uint256 constant ONE = 1.00E18; uint256 public beg = 1.05E18; // 5% minimum bid increase uint48 public ttl = 3 hours; // 3 hours bid duration [seconds] uint48 public tau = 2 days; // 2 days total auction length [seconds] uint256 public kicks = 0; CatLike public cat; // cat liquidation module // --- Events --- event Kick( uint256 id, uint256 lot, uint256 bid, uint256 tab, address indexed usr, address indexed gal ); // --- Init --- constructor(address vat_, address cat_, bytes32 ilk_) public { vat = VatLike(vat_); cat = CatLike(cat_); ilk = ilk_; wards[msg.sender] = 1; } // --- Math --- function add(uint48 x, uint48 y) internal pure returns (uint48 z) { require((z = x + y) >= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } // --- Admin --- function file(bytes32 what, uint256 data) external auth { if (what == "beg") beg = data; else if (what == "ttl") ttl = uint48(data); else if (what == "tau") tau = uint48(data); else revert("Flipper/file-unrecognized-param"); } function file(bytes32 what, address data) external auth { if (what == "cat") cat = CatLike(data); else revert("Flipper/file-unrecognized-param"); } // --- Auction --- function kick(address usr, address gal, uint256 tab, uint256 lot, uint256 bid) public auth returns (uint256 id) { require(kicks < type(uint256).max, "Flipper/overflow"); id = ++kicks; bids[id].bid = bid; bids[id].lot = lot; bids[id].guy = msg.sender; // configurable?? bids[id].end = add(uint48(block.timestamp), tau); bids[id].usr = usr; bids[id].gal = gal; bids[id].tab = tab; vat.flux(ilk, msg.sender, address(this), lot); emit Kick(id, lot, bid, tab, usr, gal); } function tick(uint256 id) external { require(bids[id].end < block.timestamp, "Flipper/not-finished"); require(bids[id].tic == 0, "Flipper/bid-already-placed"); bids[id].end = add(uint48(block.timestamp), tau); } function tend(uint256 id, uint256 lot, uint256 bid) external { require(bids[id].guy != address(0), "Flipper/guy-not-set"); require(bids[id].tic > block.timestamp || bids[id].tic == 0, "Flipper/already-finished-tic"); require(bids[id].end > block.timestamp, "Flipper/already-finished-end"); require(lot == bids[id].lot, "Flipper/lot-not-matching"); require(bid <= bids[id].tab, "Flipper/higher-than-tab"); require(bid > bids[id].bid, "Flipper/bid-not-higher"); require(mul(bid, ONE) >= mul(beg, bids[id].bid) || bid == bids[id].tab, "Flipper/insufficient-increase"); if (msg.sender != bids[id].guy) { vat.move(msg.sender, bids[id].guy, bids[id].bid); bids[id].guy = msg.sender; } vat.move(msg.sender, bids[id].gal, bid - bids[id].bid); bids[id].bid = bid; bids[id].tic = add(uint48(block.timestamp), ttl); } function dent(uint256 id, uint256 lot, uint256 bid) external { require(bids[id].guy != address(0), "Flipper/guy-not-set"); require(bids[id].tic > block.timestamp || bids[id].tic == 0, "Flipper/already-finished-tic"); require(bids[id].end > block.timestamp, "Flipper/already-finished-end"); require(bid == bids[id].bid, "Flipper/not-matching-bid"); require(bid == bids[id].tab, "Flipper/tend-not-finished"); require(lot < bids[id].lot, "Flipper/lot-not-lower"); require(mul(beg, lot) <= mul(bids[id].lot, ONE), "Flipper/insufficient-decrease"); if (msg.sender != bids[id].guy) { vat.move(msg.sender, bids[id].guy, bid); bids[id].guy = msg.sender; } vat.flux(ilk, address(this), bids[id].usr, bids[id].lot - lot); bids[id].lot = lot; bids[id].tic = add(uint48(block.timestamp), ttl); } function deal(uint256 id) external { require(bids[id].tic != 0 && (bids[id].tic < block.timestamp || bids[id].end < block.timestamp), "Flipper/not-finished"); cat.claw(bids[id].tab); vat.flux(ilk, address(this), bids[id].guy, bids[id].lot); delete bids[id]; } function yank(uint256 id) external auth { require(bids[id].guy != address(0), "Flipper/guy-not-set"); require(bids[id].bid < bids[id].tab, "Flipper/already-dent-phase"); cat.claw(bids[id].tab); vat.flux(ilk, address(this), msg.sender, bids[id].lot); vat.move(msg.sender, bids[id].guy, bids[id].bid); delete bids[id]; } } // SPDX-License-Identifier: AGPL-3.0-or-later /// flap.sol -- Surplus auction // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; // FIXME: This contract was altered compared to the production version. // It doesn't use LibNote anymore. // New deployments of this contract will need to include custom events (TO DO). interface VatLike { function move(address,address,uint) external; } interface GemLike { function move(address,address,uint) external; function burn(address,uint) external; } /* This thing lets you sell some USB in return for gems. - `lot` USB in return for bid - `bid` gems paid - `ttl` single bid lifetime - `beg` minimum bid increase - `end` max auction duration */ contract Flapper { // --- Auth --- mapping (address => uint) public wards; function rely(address usr) external auth { wards[usr] = 1; } function deny(address usr) external auth { wards[usr] = 0; } modifier auth { require(wards[msg.sender] == 1, "Flapper/not-authorized"); _; } // --- Data --- struct Bid { uint256 bid; // gems paid [wad] uint256 lot; // USB in return for bid [rad] address guy; // high bidder uint48 tic; // bid expiry time [unix epoch time] uint48 end; // auction expiry time [unix epoch time] } mapping (uint => Bid) public bids; VatLike public vat; // CDP Engine GemLike public gem; uint256 constant ONE = 1.00E18; uint256 public beg = 1.05E18; // 5% minimum bid increase uint48 public ttl = 3 hours; // 3 hours bid duration [seconds] uint48 public tau = 2 days; // 2 days total auction length [seconds] uint256 public kicks = 0; uint256 public live; // Active Flag // --- Events --- event Kick( uint256 id, uint256 lot, uint256 bid ); // --- Init --- constructor(address vat_, address gem_) public { wards[msg.sender] = 1; vat = VatLike(vat_); gem = GemLike(gem_); live = 1; } // --- Math --- function add(uint48 x, uint48 y) internal pure returns (uint48 z) { require((z = x + y) >= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Admin --- function file(bytes32 what, uint data) external auth { if (what == "beg") beg = data; else if (what == "ttl") ttl = uint48(data); else if (what == "tau") tau = uint48(data); else revert("Flapper/file-unrecognized-param"); } // --- Auction --- function kick(uint lot, uint bid) external auth returns (uint id) { require(live == 1, "Flapper/not-live"); require(kicks < type(uint256).max, "Flapper/overflow"); id = ++kicks; bids[id].bid = bid; bids[id].lot = lot; bids[id].guy = msg.sender; // configurable?? bids[id].end = add(uint48(block.timestamp), tau); vat.move(msg.sender, address(this), lot); emit Kick(id, lot, bid); } function tick(uint id) external { require(bids[id].end < block.timestamp, "Flapper/not-finished"); require(bids[id].tic == 0, "Flapper/bid-already-placed"); bids[id].end = add(uint48(block.timestamp), tau); } function tend(uint id, uint lot, uint bid) external { require(live == 1, "Flapper/not-live"); require(bids[id].guy != address(0), "Flapper/guy-not-set"); require(bids[id].tic > block.timestamp || bids[id].tic == 0, "Flapper/already-finished-tic"); require(bids[id].end > block.timestamp, "Flapper/already-finished-end"); require(lot == bids[id].lot, "Flapper/lot-not-matching"); require(bid > bids[id].bid, "Flapper/bid-not-higher"); require(mul(bid, ONE) >= mul(beg, bids[id].bid), "Flapper/insufficient-increase"); if (msg.sender != bids[id].guy) { gem.move(msg.sender, bids[id].guy, bids[id].bid); bids[id].guy = msg.sender; } gem.move(msg.sender, address(this), bid - bids[id].bid); bids[id].bid = bid; bids[id].tic = add(uint48(block.timestamp), ttl); } function deal(uint id) external { require(live == 1, "Flapper/not-live"); require(bids[id].tic != 0 && (bids[id].tic < block.timestamp || bids[id].end < block.timestamp), "Flapper/not-finished"); vat.move(address(this), bids[id].guy, bids[id].lot); gem.burn(address(this), bids[id].bid); delete bids[id]; } function cage(uint rad) external auth { live = 0; vat.move(address(this), msg.sender, rad); } function yank(uint id) external { require(live == 0, "Flapper/still-live"); require(bids[id].guy != address(0), "Flapper/guy-not-set"); gem.move(address(this), bids[id].guy, bids[id].bid); delete bids[id]; } } // SPDX-License-Identifier: AGPL-3.0-or-later /// spot.sol -- Spotter // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; // FIXME: This contract was altered compared to the production version. // It doesn't use LibNote anymore. // New deployments of this contract will need to include custom events (TO DO). interface VatLike { function file(bytes32, bytes32, uint) external; } interface PipLike { function peek() external returns (bytes32, bool); } contract Spotter { // --- Auth --- mapping (address => uint) public wards; function rely(address guy) external auth { wards[guy] = 1; } function deny(address guy) external auth { wards[guy] = 0; } modifier auth { require(wards[msg.sender] == 1, "Spotter/not-authorized"); _; } // --- Data --- struct Ilk { PipLike pip; // Price Feed uint256 mat; // Liquidation ratio [ray] } mapping (bytes32 => Ilk) public ilks; VatLike public vat; // CDP Engine uint256 public par; // ref per USB [ray] uint256 public live; // --- Events --- event Poke( bytes32 ilk, bytes32 val, // [wad] uint256 spot // [ray] ); // --- Init --- constructor(address vat_) public { wards[msg.sender] = 1; vat = VatLike(vat_); par = ONE; live = 1; } // --- Math --- uint constant ONE = 10 ** 27; function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function rdiv(uint x, uint y) internal pure returns (uint z) { z = mul(x, ONE) / y; } // --- Administration --- function file(bytes32 ilk, bytes32 what, address pip_) external auth { require(live == 1, "Spotter/not-live"); if (what == "pip") ilks[ilk].pip = PipLike(pip_); else revert("Spotter/file-unrecognized-param"); } function file(bytes32 what, uint data) external auth { require(live == 1, "Spotter/not-live"); if (what == "par") par = data; else revert("Spotter/file-unrecognized-param"); } function file(bytes32 ilk, bytes32 what, uint data) external auth { require(live == 1, "Spotter/not-live"); if (what == "mat") ilks[ilk].mat = data; else revert("Spotter/file-unrecognized-param"); } // --- Update value --- function poke(bytes32 ilk) external { (bytes32 val, bool has) = ilks[ilk].pip.peek(); uint256 spot = has ? rdiv(rdiv(mul(uint(val), 10 ** 9), par), ilks[ilk].mat) : 0; vat.file(ilk, "spot", spot); emit Poke(ilk, val, spot); } function cage() external auth { live = 0; } } // SPDX-License-Identifier: AGPL-3.0-or-later /// jug.sol -- USB Lending Rate // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; // FIXME: This contract was altered compared to the production version. // It doesn't use LibNote anymore. // New deployments of this contract will need to include custom events (TO DO). interface VatLike { function ilks(bytes32) external returns ( uint256 Art, // [wad] uint256 rate // [ray] ); function fold(bytes32,address,int) external; } contract Jug { // --- Auth --- mapping (address => uint) public wards; function rely(address usr) external auth { wards[usr] = 1; } function deny(address usr) external auth { wards[usr] = 0; } modifier auth { require(wards[msg.sender] == 1, "Jug/not-authorized"); _; } // --- Data --- struct Ilk { uint256 duty; // Collateral-specific, per-second stability fee contribution [ray] uint256 rho; // Time of last drip [unix epoch time] } mapping (bytes32 => Ilk) public ilks; VatLike public vat; // CDP Engine address public vow; // Debt Engine uint256 public base; // Global, per-second stability fee contribution [ray] // --- Init --- constructor(address vat_) public { wards[msg.sender] = 1; vat = VatLike(vat_); } // --- Math --- function rpow(uint x, uint n, uint b) internal pure returns (uint z) { assembly { switch x case 0 {switch n case 0 {z := b} default {z := 0}} default { switch mod(n, 2) case 0 { z := b } default { z := x } let half := div(b, 2) // for rounding. for { n := div(n, 2) } n { n := div(n,2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } x := div(xxRound, b) if mod(n,2) { let zx := mul(z, x) if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z := div(zxRound, b) } } } } } uint256 constant ONE = 10 ** 27; function add(uint x, uint y) internal pure returns (uint z) { z = x + y; require(z >= x); } function diff(uint x, uint y) internal pure returns (int z) { z = int(x) - int(y); require(int(x) >= 0 && int(y) >= 0); } function rmul(uint x, uint y) internal pure returns (uint z) { z = x * y; require(y == 0 || z / y == x); z = z / ONE; } // --- Administration --- function init(bytes32 ilk) external auth { Ilk storage i = ilks[ilk]; require(i.duty == 0, "Jug/ilk-already-init"); i.duty = ONE; i.rho = block.timestamp; } function file(bytes32 ilk, bytes32 what, uint data) external auth { require(block.timestamp == ilks[ilk].rho, "Jug/rho-not-updated"); if (what == "duty") ilks[ilk].duty = data; else revert("Jug/file-unrecognized-param"); } function file(bytes32 what, uint data) external auth { if (what == "base") base = data; else revert("Jug/file-unrecognized-param"); } function file(bytes32 what, address data) external auth { if (what == "vow") vow = data; else revert("Jug/file-unrecognized-param"); } // --- Stability Fee Collection --- function drip(bytes32 ilk) external returns (uint rate) { require(block.timestamp >= ilks[ilk].rho, "Jug/invalid-now"); (, uint prev) = vat.ilks(ilk); rate = rmul(rpow(add(base, ilks[ilk].duty), block.timestamp - ilks[ilk].rho, ONE), prev); vat.fold(ilk, vow, diff(rate, prev)); ilks[ilk].rho = block.timestamp; } } // SPDX-License-Identifier: AGPL-3.0-or-later /// vat.sol -- USB CDP database // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; // FIXME: This contract was altered compared to the production version. // It doesn't use LibNote anymore. // New deployments of this contract will need to include custom events (TO DO). contract Vat { // --- Auth --- mapping (address => uint) public wards; function rely(address usr) external auth { require(live == 1, "Vat/not-live"); wards[usr] = 1; } function deny(address usr) external auth { require(live == 1, "Vat/not-live"); wards[usr] = 0; } modifier auth { require(wards[msg.sender] == 1, "Vat/not-authorized"); _; } mapping(address => mapping (address => uint)) public can; function hope(address usr) external { can[msg.sender][usr] = 1; } function nope(address usr) external { can[msg.sender][usr] = 0; } function wish(address bit, address usr) internal view returns (bool) { return either(bit == usr, can[bit][usr] == 1); } // --- Data --- struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } mapping (bytes32 => Ilk) public ilks; mapping (bytes32 => mapping (address => Urn )) public urns; mapping (bytes32 => mapping (address => uint)) public gem; // [wad] mapping (address => uint256) public USB; // [rad] mapping (address => uint256) public sin; // [rad] uint256 public debt; // Total USB Issued [rad] uint256 public vice; // Total Unbacked USB [rad] uint256 public Line; // Total Debt Ceiling [rad] uint256 public live; // Active Flag // --- Init --- constructor() public { wards[msg.sender] = 1; live = 1; } // --- Math --- function add(uint x, int y) internal pure returns (uint z) { z = x + uint(y); require(y >= 0 || z <= x); require(y <= 0 || z >= x); } function sub(uint x, int y) internal pure returns (uint z) { z = x - uint(y); require(y <= 0 || z <= x); require(y >= 0 || z >= x); } function mul(uint x, int y) internal pure returns (int z) { z = int(x) * y; require(int(x) >= 0); require(y == 0 || z / y == int(x)); } function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- function init(bytes32 ilk) external auth { require(ilks[ilk].rate == 0, "Vat/ilk-already-init"); ilks[ilk].rate = 10 ** 27; } function file(bytes32 what, uint data) external auth { require(live == 1, "Vat/not-live"); if (what == "Line") Line = data; else revert("Vat/file-unrecognized-param"); } function file(bytes32 ilk, bytes32 what, uint data) external auth { require(live == 1, "Vat/not-live"); if (what == "spot") ilks[ilk].spot = data; else if (what == "line") ilks[ilk].line = data; else if (what == "dust") ilks[ilk].dust = data; else revert("Vat/file-unrecognized-param"); } function cage() external auth { live = 0; } // --- Fungibility --- function slip(bytes32 ilk, address usr, int256 wad) external auth { gem[ilk][usr] = add(gem[ilk][usr], wad); } function flux(bytes32 ilk, address src, address dst, uint256 wad) external { require(wish(src, msg.sender), "Vat/not-allowed"); gem[ilk][src] = sub(gem[ilk][src], wad); gem[ilk][dst] = add(gem[ilk][dst], wad); } function move(address src, address dst, uint256 rad) external { require(wish(src, msg.sender), "Vat/not-allowed"); USB[src] = sub(USB[src], rad); USB[dst] = add(USB[dst], rad); } function either(bool x, bool y) internal pure returns (bool z) { assembly{ z := or(x, y)} } function both(bool x, bool y) internal pure returns (bool z) { assembly{ z := and(x, y)} } // --- CDP Manipulation --- function frob(bytes32 i, address u, address v, address w, int dink, int dart) external { // system is live require(live == 1, "Vat/not-live"); Urn memory urn = urns[i][u]; Ilk memory ilk = ilks[i]; // ilk has been initialised require(ilk.rate != 0, "Vat/ilk-not-init"); urn.ink = add(urn.ink, dink); urn.art = add(urn.art, dart); ilk.Art = add(ilk.Art, dart); int dtab = mul(ilk.rate, dart); uint tab = mul(ilk.rate, urn.art); debt = add(debt, dtab); // either debt has decreased, or debt ceilings are not exceeded require(either(dart <= 0, both(mul(ilk.Art, ilk.rate) <= ilk.line, debt <= Line)), "Vat/ceiling-exceeded"); // urn is either less risky than before, or it is safe require(either(both(dart <= 0, dink >= 0), tab <= mul(urn.ink, ilk.spot)), "Vat/not-safe"); // urn is either more safe, or the owner consents require(either(both(dart <= 0, dink >= 0), wish(u, msg.sender)), "Vat/not-allowed-u"); // collateral src consents require(either(dink <= 0, wish(v, msg.sender)), "Vat/not-allowed-v"); // debt dst consents require(either(dart >= 0, wish(w, msg.sender)), "Vat/not-allowed-w"); // urn has no debt, or a non-dusty amount require(either(urn.art == 0, tab >= ilk.dust), "Vat/dust"); gem[i][v] = sub(gem[i][v], dink); USB[w] = add(USB[w], dtab); urns[i][u] = urn; ilks[i] = ilk; } // --- CDP Fungibility --- function fork(bytes32 ilk, address src, address dst, int dink, int dart) external { Urn storage u = urns[ilk][src]; Urn storage v = urns[ilk][dst]; Ilk storage i = ilks[ilk]; u.ink = sub(u.ink, dink); u.art = sub(u.art, dart); v.ink = add(v.ink, dink); v.art = add(v.art, dart); uint utab = mul(u.art, i.rate); uint vtab = mul(v.art, i.rate); // both sides consent require(both(wish(src, msg.sender), wish(dst, msg.sender)), "Vat/not-allowed"); // both sides safe require(utab <= mul(u.ink, i.spot), "Vat/not-safe-src"); require(vtab <= mul(v.ink, i.spot), "Vat/not-safe-dst"); // both sides non-dusty require(either(utab >= i.dust, u.art == 0), "Vat/dust-src"); require(either(vtab >= i.dust, v.art == 0), "Vat/dust-dst"); } // --- CDP Confiscation --- function grab(bytes32 i, address u, address v, address w, int dink, int dart) external auth { Urn storage urn = urns[i][u]; Ilk storage ilk = ilks[i]; urn.ink = add(urn.ink, dink); urn.art = add(urn.art, dart); ilk.Art = add(ilk.Art, dart); int dtab = mul(ilk.rate, dart); gem[i][v] = sub(gem[i][v], dink); sin[w] = sub(sin[w], dtab); vice = sub(vice, dtab); } // --- Settlement --- function heal(uint rad) external { address u = msg.sender; sin[u] = sub(sin[u], rad); USB[u] = sub(USB[u], rad); vice = sub(vice, rad); debt = sub(debt, rad); } function suck(address u, address v, uint rad) external auth { sin[u] = add(sin[u], rad); USB[v] = add(USB[v], rad); vice = add(vice, rad); debt = add(debt, rad); } // --- Rates --- function fold(bytes32 i, address u, int rate) external auth { require(live == 1, "Vat/not-live"); Ilk storage ilk = ilks[i]; ilk.rate = add(ilk.rate, rate); int rad = mul(ilk.Art, rate); USB[u] = add(USB[u], rad); debt = add(debt, rad); } } // SPDX-License-Identifier: AGPL-3.0-or-later // Copyright (C) 2017, 2018, 2019 dbrock, rain, mrchico // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; // FIXME: This contract was altered compared to the production version. // It doesn't use LibNote anymore. // New deployments of this contract will need to include custom events (TO DO). contract USB { // --- Auth --- mapping (address => uint) public wards; function rely(address guy) external auth { wards[guy] = 1; } function deny(address guy) external auth { wards[guy] = 0; } modifier auth { require(wards[msg.sender] == 1, "USB/not-authorized"); _; } // --- ERC20 Data --- string public constant name = "USB Stablecoin"; string public constant symbol = "USB"; string public constant version = "1"; uint8 public constant decimals = 18; uint256 public totalSupply; mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; mapping (address => uint) public nonces; event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); // --- Math --- function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } // --- EIP712 niceties --- bytes32 public DOMAIN_SEPARATOR; // bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)"); bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; constructor(uint256 chainId_) public { wards[msg.sender] = 1; DOMAIN_SEPARATOR = keccak256(abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes(version)), chainId_, address(this) )); } // --- Token --- function transfer(address dst, uint wad) external returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { require(balanceOf[src] >= wad, "USB/insufficient-balance"); if (src != msg.sender && allowance[src][msg.sender] != type(uint256).max) { require(allowance[src][msg.sender] >= wad, "USB/insufficient-allowance"); allowance[src][msg.sender] = sub(allowance[src][msg.sender], wad); } balanceOf[src] = sub(balanceOf[src], wad); balanceOf[dst] = add(balanceOf[dst], wad); emit Transfer(src, dst, wad); return true; } function mint(address usr, uint wad) external auth { balanceOf[usr] = add(balanceOf[usr], wad); totalSupply = add(totalSupply, wad); emit Transfer(address(0), usr, wad); } function burn(address usr, uint wad) external { require(balanceOf[usr] >= wad, "USB/insufficient-balance"); if (usr != msg.sender && allowance[usr][msg.sender] != type(uint256).max) { require(allowance[usr][msg.sender] >= wad, "USB/insufficient-allowance"); allowance[usr][msg.sender] = sub(allowance[usr][msg.sender], wad); } balanceOf[usr] = sub(balanceOf[usr], wad); totalSupply = sub(totalSupply, wad); emit Transfer(usr, address(0), wad); } function approve(address usr, uint wad) external returns (bool) { allowance[msg.sender][usr] = wad; emit Approval(msg.sender, usr, wad); return true; } // --- Alias --- function push(address usr, uint wad) external { transferFrom(msg.sender, usr, wad); } function pull(address usr, uint wad) external { transferFrom(usr, msg.sender, wad); } function move(address src, address dst, uint wad) external { transferFrom(src, dst, wad); } // --- Approve by signature --- function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external { bytes32 digest = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, holder, spender, nonce, expiry, allowed)) )); require(holder != address(0), "USB/invalid-address-0"); require(holder == ecrecover(digest, v, r, s), "USB/invalid-permit"); require(expiry == 0 || block.timestamp <= expiry, "USB/permit-expired"); require(nonce == nonces[holder]++, "USB/invalid-nonce"); uint wad = allowed ? type(uint256).max : 0; allowance[holder][spender] = wad; emit Approval(holder, spender, wad); } } // SPDX-License-Identifier: AGPL-3.0-or-later /// DssProxyActions.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity >=0.5.12; interface GemLike { function approve(address, uint) external; function transfer(address, uint) external; function transferFrom(address, address, uint) external; function deposit() external payable; function withdraw(uint) external; } interface ManagerLike { function cdpCan(address, uint, address) external view returns (uint); function ilks(uint) external view returns (bytes32); function owns(uint) external view returns (address); function urns(uint) external view returns (address); function vat() external view returns (address); function open(bytes32, address) external returns (uint); function give(uint, address) external; function cdpAllow(uint, address, uint) external; function urnAllow(address, uint) external; function frob(uint, int, int) external; function flux(uint, address, uint) external; function move(uint, address, uint) external; function exit(address, uint, address, uint) external; function quit(uint, address) external; function enter(address, uint) external; function shift(uint, uint) external; } interface VatLike { function can(address, address) external view returns (uint); function ilks(bytes32) external view returns (uint, uint, uint, uint, uint); function USB(address) external view returns (uint); function urns(bytes32, address) external view returns (uint, uint); function frob(bytes32, address, address, address, int, int) external; function hope(address) external; function move(address, address, uint) external; } interface GemJoinLike { function dec() external returns (uint); function gem() external returns (GemLike); function join(address, uint) external payable; function exit(address, uint) external; } interface GNTJoinLike { function bags(address) external view returns (address); function make(address) external returns (address); } interface USBJoinLike { function vat() external returns (VatLike); function USB() external returns (GemLike); function join(address, uint) external payable; function exit(address, uint) external; } interface HopeLike { function hope(address) external; function nope(address) external; } interface EndLike { function fix(bytes32) external view returns (uint); function cash(bytes32, uint) external; function free(bytes32) external; function pack(uint) external; function skim(bytes32, address) external; } interface JugLike { function drip(bytes32) external returns (uint); } interface PotLike { function pie(address) external view returns (uint); function drip() external returns (uint); function join(uint) external; function exit(uint) external; } interface ProxyRegistryLike { function proxies(address) external view returns (address); function build(address) external returns (address); } interface ProxyLike { function owner() external view returns (address); } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // WARNING: These functions meant to be used as a a library for a DSProxy. Some are unsafe if you call them directly. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! contract Common { uint256 constant RAY = 10 ** 27; // Internal functions function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "mul-overflow"); } // Public functions function USBJoin_join(address apt, address urn, uint wad) public { // Gets USB from the user's wallet USBJoinLike(apt).USB().transferFrom(msg.sender, address(this), wad); // Approves adapter to take the USB amount USBJoinLike(apt).USB().approve(apt, wad); // Joins USB into the vat USBJoinLike(apt).join(urn, wad); } } contract DssProxyActions is Common { // Internal functions function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "sub-overflow"); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0, "int-overflow"); } function toRad(uint wad) internal pure returns (uint rad) { rad = mul(wad, 10 ** 27); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function // Adapters will automatically handle the difference of precision wad = mul( amt, 10 ** (18 - GemJoinLike(gemJoin).dec()) ); } function _getDrawDart( address vat, address jug, address urn, bytes32 ilk, uint wad ) internal returns (int dart) { // Updates stability fee rate uint rate = JugLike(jug).drip(ilk); // Gets USB balance of the urn in the vat uint USB = VatLike(vat).USB(urn); // If there was already enough USB in the vat balance, just exits it without adding more debt if (USB < mul(wad, RAY)) { // Calculates the needed dart so together with the existing USB in the vat is enough to exit wad amount of USB tokens dart = toInt(sub(mul(wad, RAY), USB) / rate); // This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given USB wad amount) dart = mul(uint(dart), rate) < mul(wad, RAY) ? dart + 1 : dart; } } function _getWipeDart( address vat, uint USB, address urn, bytes32 ilk ) internal view returns (int dart) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Uses the whole USB balance in the vat to reduce the debt dart = toInt(USB / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint(dart) <= art ? - dart : - toInt(art); } function _getWipeAllWad( address vat, address usr, address urn, bytes32 ilk ) internal view returns (uint wad) { // Gets actual rate from the vat (, uint rate,,,) = VatLike(vat).ilks(ilk); // Gets actual art value of the urn (, uint art) = VatLike(vat).urns(ilk, urn); // Gets actual USB amount in the urn uint USB = VatLike(vat).USB(usr); uint rad = sub(mul(art, rate), USB); wad = rad / RAY; // If the rad precision has some dust, it will need to request for 1 extra wad wei wad = mul(wad, RAY) < rad ? wad + 1 : wad; } // Public functions function transfer(address gem, address dst, uint amt) public { GemLike(gem).transfer(dst, amt); } function ethJoin_join(address apt, address urn) public payable { // Wraps ETH in WETH GemJoinLike(apt).gem().deposit{value:(msg.value)}(); // Approves adapter to take the WETH amount GemJoinLike(apt).gem().approve(address(apt), msg.value); // Joins WETH collateral into the vat GemJoinLike(apt).join(urn, msg.value); } function gemJoin_join(address apt, address urn, uint amt, bool transferFrom) public { // Only executes for tokens that have approval/transferFrom implementation if (transferFrom) { // Gets token from the user's wallet GemJoinLike(apt).gem().transferFrom(msg.sender, address(this), amt); // Approves adapter to take the token amount GemJoinLike(apt).gem().approve(apt, amt); } // Joins token collateral into the vat GemJoinLike(apt).join(urn, amt); } function hope( address obj, address usr ) public { HopeLike(obj).hope(usr); } function nope( address obj, address usr ) public { HopeLike(obj).nope(usr); } function open( address manager, bytes32 ilk, address usr ) public returns (uint cdp) { cdp = ManagerLike(manager).open(ilk, usr); } function give( address manager, uint cdp, address usr ) public { ManagerLike(manager).give(cdp, usr); } function giveToProxy( address proxyRegistry, address manager, uint cdp, address dst ) public { // Gets actual proxy address address proxy = ProxyRegistryLike(proxyRegistry).proxies(dst); // Checks if the proxy address already existed and dst address is still the owner if (proxy == address(0) || ProxyLike(proxy).owner() != dst) { uint csize; assembly { csize := extcodesize(dst) } // We want to avoid creating a proxy for a contract address that might not be able to handle proxies, then losing the CDP require(csize == 0, "Dst-is-a-contract"); // Creates the proxy for the dst address proxy = ProxyRegistryLike(proxyRegistry).build(dst); } // Transfers CDP to the dst proxy give(manager, cdp, proxy); } function cdpAllow( address manager, uint cdp, address usr, uint ok ) public { ManagerLike(manager).cdpAllow(cdp, usr, ok); } function urnAllow( address manager, address usr, uint ok ) public { ManagerLike(manager).urnAllow(usr, ok); } function flux( address manager, uint cdp, address dst, uint wad ) public { ManagerLike(manager).flux(cdp, dst, wad); } function move( address manager, uint cdp, address dst, uint rad ) public { ManagerLike(manager).move(cdp, dst, rad); } function frob( address manager, uint cdp, int dink, int dart ) public { ManagerLike(manager).frob(cdp, dink, dart); } function quit( address manager, uint cdp, address dst ) public { ManagerLike(manager).quit(cdp, dst); } function enter( address manager, address src, uint cdp ) public { ManagerLike(manager).enter(src, cdp); } function shift( address manager, uint cdpSrc, uint cdpOrg ) public { ManagerLike(manager).shift(cdpSrc, cdpOrg); } function makeGemBag( address gemJoin ) public returns (address bag) { bag = GNTJoinLike(gemJoin).make(address(this)); } function lockETH( address manager, address ethJoin, uint cdp ) public payable { // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, address(this)); // Locks WETH amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(msg.value), 0 ); } function safeLockETH( address manager, address ethJoin, uint cdp, address owner ) public payable { require(ManagerLike(manager).owns(cdp) == owner, "owner-missmatch"); lockETH(manager, ethJoin, cdp); } function lockGem( address manager, address gemJoin, uint cdp, uint amt, bool transferFrom ) public { // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, address(this), amt, transferFrom); // Locks token amount into the CDP VatLike(ManagerLike(manager).vat()).frob( ManagerLike(manager).ilks(cdp), ManagerLike(manager).urns(cdp), address(this), address(this), toInt(convertTo18(gemJoin, amt)), 0 ); } function safeLockGem( address manager, address gemJoin, uint cdp, uint amt, bool transferFrom, address owner ) public { require(ManagerLike(manager).owns(cdp) == owner, "owner-missmatch"); lockGem(manager, gemJoin, cdp, amt, transferFrom); } function freeETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Unlocks WETH amount from the CDP frob(manager, cdp, -toInt(wad), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet payable(msg.sender).transfer(wad); } function freeGem( address manager, address gemJoin, uint cdp, uint amt ) public { uint wad = convertTo18(gemJoin, amt); // Unlocks token amount from the CDP frob(manager, cdp, -toInt(wad), 0); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, amt); } function exitETH( address manager, address ethJoin, uint cdp, uint wad ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wad); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet payable(msg.sender).transfer(wad); } function exitGem( address manager, address gemJoin, uint cdp, uint amt ) public { // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), convertTo18(gemJoin, amt)); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, amt); } function draw( address manager, address jug, address USBJoin, uint cdp, uint wad ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Generates debt in the CDP frob(manager, cdp, 0, _getDrawDart(vat, jug, urn, ilk, wad)); // Moves the USB amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wad)); // Allows adapter to access to proxy's USB balance in the vat if (VatLike(vat).can(address(this), address(USBJoin)) == 0) { VatLike(vat).hope(USBJoin); } // Exits USB to the user's wallet as a token USBJoinLike(USBJoin).exit(msg.sender, wad); } function wipe( address manager, address USBJoin, uint cdp, uint wad ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins USB amount into the vat USBJoin_join(USBJoin, urn, wad); // Paybacks debt to the CDP frob(manager, cdp, 0, _getWipeDart(vat, VatLike(vat).USB(urn), urn, ilk)); } else { // Joins USB amount into the vat USBJoin_join(USBJoin, address(this), wad); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, _getWipeDart(vat, wad * RAY, urn, ilk) ); } } function safeWipe( address manager, address USBJoin, uint cdp, uint wad, address owner ) public { require(ManagerLike(manager).owns(cdp) == owner, "owner-missmatch"); wipe(manager, USBJoin, cdp, wad); } function wipeAll( address manager, address USBJoin, uint cdp ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); address own = ManagerLike(manager).owns(cdp); if (own == address(this) || ManagerLike(manager).cdpCan(own, cdp, address(this)) == 1) { // Joins USB amount into the vat USBJoin_join(USBJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP frob(manager, cdp, 0, -int(art)); } else { // Joins USB amount into the vat USBJoin_join(USBJoin, address(this), _getWipeAllWad(vat, address(this), urn, ilk)); // Paybacks debt to the CDP VatLike(vat).frob( ilk, urn, address(this), address(this), 0, -int(art) ); } } function safeWipeAll( address manager, address USBJoin, uint cdp, address owner ) public { require(ManagerLike(manager).owns(cdp) == owner, "owner-missmatch"); wipeAll(manager, USBJoin, cdp); } function lockETHAndDraw( address manager, address jug, address ethJoin, address USBJoin, uint cdp, uint wadD ) public payable { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Receives ETH amount, converts it to WETH and joins it into the vat ethJoin_join(ethJoin, urn); // Locks WETH amount into the CDP and generates debt frob(manager, cdp, toInt(msg.value), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the USB amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's USB balance in the vat if (VatLike(vat).can(address(this), address(USBJoin)) == 0) { VatLike(vat).hope(USBJoin); } // Exits USB to the user's wallet as a token USBJoinLike(USBJoin).exit(msg.sender, wadD); } function openLockETHAndDraw( address manager, address jug, address ethJoin, address USBJoin, bytes32 ilk, uint wadD ) public payable returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockETHAndDraw(manager, jug, ethJoin, USBJoin, cdp, wadD); } function lockGemAndDraw( address manager, address jug, address gemJoin, address USBJoin, uint cdp, uint amtC, uint wadD, bool transferFrom ) public { address urn = ManagerLike(manager).urns(cdp); address vat = ManagerLike(manager).vat(); bytes32 ilk = ManagerLike(manager).ilks(cdp); // Takes token amount from user's wallet and joins into the vat gemJoin_join(gemJoin, urn, amtC, transferFrom); // Locks token amount into the CDP and generates debt frob(manager, cdp, toInt(convertTo18(gemJoin, amtC)), _getDrawDart(vat, jug, urn, ilk, wadD)); // Moves the USB amount (balance in the vat in rad) to proxy's address move(manager, cdp, address(this), toRad(wadD)); // Allows adapter to access to proxy's USB balance in the vat if (VatLike(vat).can(address(this), address(USBJoin)) == 0) { VatLike(vat).hope(USBJoin); } // Exits USB to the user's wallet as a token USBJoinLike(USBJoin).exit(msg.sender, wadD); } function openLockGemAndDraw( address manager, address jug, address gemJoin, address USBJoin, bytes32 ilk, uint amtC, uint wadD, bool transferFrom ) public returns (uint cdp) { cdp = open(manager, ilk, address(this)); lockGemAndDraw(manager, jug, gemJoin, USBJoin, cdp, amtC, wadD, transferFrom); } function openLockGNTAndDraw( address manager, address jug, address gntJoin, address USBJoin, bytes32 ilk, uint amtC, uint wadD ) public returns (address bag, uint cdp) { // Creates bag (if doesn't exist) to hold GNT bag = GNTJoinLike(gntJoin).bags(address(this)); if (bag == address(0)) { bag = makeGemBag(gntJoin); } // Transfer funds to the funds which previously were sent to the proxy GemLike(GemJoinLike(gntJoin).gem()).transfer(bag, amtC); cdp = openLockGemAndDraw(manager, jug, gntJoin, USBJoin, ilk, amtC, wadD, false); } function wipeAndFreeETH( address manager, address ethJoin, address USBJoin, uint cdp, uint wadC, uint wadD ) public { address urn = ManagerLike(manager).urns(cdp); // Joins USB amount into the vat USBJoin_join(USBJoin, urn, wadD); // Paybacks debt to the CDP and unlocks WETH amount from it frob( manager, cdp, -toInt(wadC), _getWipeDart(ManagerLike(manager).vat(), VatLike(ManagerLike(manager).vat()).USB(urn), urn, ManagerLike(manager).ilks(cdp)) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wadC); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet payable(msg.sender).transfer(wadC); } function wipeAllAndFreeETH( address manager, address ethJoin, address USBJoin, uint cdp, uint wadC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins USB amount into the vat USBJoin_join(USBJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); // Paybacks debt to the CDP and unlocks WETH amount from it frob( manager, cdp, -toInt(wadC), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wadC); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet payable(msg.sender).transfer(wadC); } function wipeAndFreeGem( address manager, address gemJoin, address USBJoin, uint cdp, uint amtC, uint wadD ) public { address urn = ManagerLike(manager).urns(cdp); // Joins USB amount into the vat USBJoin_join(USBJoin, urn, wadD); uint wadC = convertTo18(gemJoin, amtC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wadC), _getWipeDart(ManagerLike(manager).vat(), VatLike(ManagerLike(manager).vat()).USB(urn), urn, ManagerLike(manager).ilks(cdp)) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wadC); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, amtC); } function wipeAllAndFreeGem( address manager, address gemJoin, address USBJoin, uint cdp, uint amtC ) public { address vat = ManagerLike(manager).vat(); address urn = ManagerLike(manager).urns(cdp); bytes32 ilk = ManagerLike(manager).ilks(cdp); (, uint art) = VatLike(vat).urns(ilk, urn); // Joins USB amount into the vat USBJoin_join(USBJoin, urn, _getWipeAllWad(vat, urn, urn, ilk)); uint wadC = convertTo18(gemJoin, amtC); // Paybacks debt to the CDP and unlocks token amount from it frob( manager, cdp, -toInt(wadC), -int(art) ); // Moves the amount from the CDP urn to proxy's address flux(manager, cdp, address(this), wadC); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, amtC); } } contract DssProxyActionsEnd is Common { // Internal functions function _free( address manager, address end, uint cdp ) internal returns (uint ink) { bytes32 ilk = ManagerLike(manager).ilks(cdp); address urn = ManagerLike(manager).urns(cdp); VatLike vat = VatLike(ManagerLike(manager).vat()); uint art; (ink, art) = vat.urns(ilk, urn); // If CDP still has debt, it needs to be paid if (art > 0) { EndLike(end).skim(ilk, urn); (ink,) = vat.urns(ilk, urn); } // Approves the manager to transfer the position to proxy's address in the vat if (vat.can(address(this), address(manager)) == 0) { vat.hope(manager); } // Transfers position from CDP to the proxy address ManagerLike(manager).quit(cdp, address(this)); // Frees the position and recovers the collateral in the vat registry EndLike(end).free(ilk); } // Public functions function freeETH( address manager, address ethJoin, address end, uint cdp ) public { uint wad = _free(manager, end, cdp); // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wad); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wad); // Sends ETH back to the user's wallet payable(msg.sender).transfer(wad); } function freeGem( address manager, address gemJoin, address end, uint cdp ) public { uint amt = _free(manager, end, cdp) / 10 ** (18 - GemJoinLike(gemJoin).dec()); // Exits token amount to the user's wallet as a token GemJoinLike(gemJoin).exit(msg.sender, amt); } function pack( address USBJoin, address end, uint wad ) public { USBJoin_join(USBJoin, address(this), wad); VatLike vat = USBJoinLike(USBJoin).vat(); // Approves the end to take out USB from the proxy's balance in the vat if (vat.can(address(this), address(end)) == 0) { vat.hope(end); } EndLike(end).pack(wad); } function cashETH( address ethJoin, address end, bytes32 ilk, uint wad ) public { EndLike(end).cash(ilk, wad); uint wadC = mul(wad, EndLike(end).fix(ilk)) / RAY; // Exits WETH amount to proxy address as a token GemJoinLike(ethJoin).exit(address(this), wadC); // Converts WETH to ETH GemJoinLike(ethJoin).gem().withdraw(wadC); // Sends ETH back to the user's wallet payable(msg.sender).transfer(wadC); } function cashGem( address gemJoin, address end, bytes32 ilk, uint wad ) public { EndLike(end).cash(ilk, wad); // Exits token amount to the user's wallet as a token uint amt = mul(wad, EndLike(end).fix(ilk)) / RAY / 10 ** (18 - GemJoinLike(gemJoin).dec()); GemJoinLike(gemJoin).exit(msg.sender, amt); } } contract DssProxyActionsDsr is Common { function join( address USBJoin, address pot, uint wad ) public { VatLike vat = USBJoinLike(USBJoin).vat(); // Executes drip to get the chi rate updated to rho == now, otherwise join will fail uint chi = PotLike(pot).drip(); // Joins wad amount to the vat balance USBJoin_join(USBJoin, address(this), wad); // Approves the pot to take out USB from the proxy's balance in the vat if (vat.can(address(this), address(pot)) == 0) { vat.hope(pot); } // Joins the pie value (equivalent to the USB wad amount) in the pot PotLike(pot).join(mul(wad, RAY) / chi); } function exit( address USBJoin, address pot, uint wad ) public { VatLike vat = USBJoinLike(USBJoin).vat(); // Executes drip to count the savings accumulated until this moment uint chi = PotLike(pot).drip(); // Calculates the pie value in the pot equivalent to the USB wad amount uint pie = mul(wad, RAY) / chi; // Exits USB from the pot PotLike(pot).exit(pie); // Checks the actual balance of USB in the vat after the pot exit uint bal = USBJoinLike(USBJoin).vat().USB(address(this)); // Allows adapter to access to proxy's USB balance in the vat if (vat.can(address(this), address(USBJoin)) == 0) { vat.hope(USBJoin); } // It is necessary to check if due rounding the exact wad amount can be exited by the adapter. // Otherwise it will do the maximum USB balance in the vat USBJoinLike(USBJoin).exit( msg.sender, bal >= mul(wad, RAY) ? wad : bal / RAY ); } function exitAll( address USBJoin, address pot ) public { VatLike vat = USBJoinLike(USBJoin).vat(); // Executes drip to count the savings accumulated until this moment uint chi = PotLike(pot).drip(); // Gets the total pie belonging to the proxy address uint pie = PotLike(pot).pie(address(this)); // Exits USB from the pot PotLike(pot).exit(pie); // Allows adapter to access to proxy's USB balance in the vat if (vat.can(address(this), address(USBJoin)) == 0) { vat.hope(USBJoin); } // Exits the USB amount corresponding to the value of pie USBJoinLike(USBJoin).exit(msg.sender, mul(chi, pie) / RAY); } } // SPDX-License-Identifier: AGPL-3.0-or-later /// pot.sol -- USB Savings Rate // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; // FIXME: This contract was altered compared to the production version. // It doesn't use LibNote anymore. // New deployments of this contract will need to include custom events (TO DO). /* "Savings USB" is obtained when USB is deposited into this contract. Each "Savings USB" accrues USB interest at the "USB Savings Rate". This contract does not implement a user tradeable token and is intended to be used with adapters. --- `save` your `USB` in the `pot` --- - `dsr`: the USB Savings Rate - `pie`: user balance of Savings USB - `join`: start saving some USB - `exit`: remove some USB - `drip`: perform rate collection */ interface VatLike { function move(address,address,uint256) external; function suck(address,address,uint256) external; } contract Pot { // --- Auth --- mapping (address => uint) public wards; function rely(address guy) external auth { wards[guy] = 1; } function deny(address guy) external auth { wards[guy] = 0; } modifier auth { require(wards[msg.sender] == 1, "Pot/not-authorized"); _; } // --- Data --- mapping (address => uint256) public pie; // Normalised Savings USB [wad] uint256 public Pie; // Total Normalised Savings USB [wad] uint256 public dsr; // The USB Savings Rate [ray] uint256 public chi; // The Rate Accumulator [ray] VatLike public vat; // CDP Engine address public vow; // Debt Engine uint256 public rho; // Time of last drip [unix epoch time] uint256 public live; // Active Flag // --- Init --- constructor(address vat_) public { wards[msg.sender] = 1; vat = VatLike(vat_); dsr = ONE; chi = ONE; rho = block.timestamp; live = 1; } // --- Math --- uint256 constant ONE = 10 ** 27; function rpow(uint x, uint n, uint base) internal pure returns (uint z) { assembly { switch x case 0 {switch n case 0 {z := base} default {z := 0}} default { switch mod(n, 2) case 0 { z := base } default { z := x } let half := div(base, 2) // for rounding. for { n := div(n, 2) } n { n := div(n,2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } x := div(xxRound, base) if mod(n,2) { let zx := mul(z, x) if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z := div(zxRound, base) } } } } } function rmul(uint x, uint y) internal pure returns (uint z) { z = mul(x, y) / ONE; } function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- function file(bytes32 what, uint256 data) external auth { require(live == 1, "Pot/not-live"); require(block.timestamp == rho, "Pot/rho-not-updated"); if (what == "dsr") dsr = data; else revert("Pot/file-unrecognized-param"); } function file(bytes32 what, address addr) external auth { if (what == "vow") vow = addr; else revert("Pot/file-unrecognized-param"); } function cage() external auth { live = 0; dsr = ONE; } // --- Savings Rate Accumulation --- function drip() external returns (uint tmp) { require(block.timestamp >= rho, "Pot/invalid-now"); tmp = rmul(rpow(dsr, block.timestamp - rho, ONE), chi); uint chi_ = sub(tmp, chi); chi = tmp; rho = block.timestamp; vat.suck(address(vow), address(this), mul(Pie, chi_)); } // --- Savings USB Management --- function join(uint wad) external { require(block.timestamp == rho, "Pot/rho-not-updated"); pie[msg.sender] = add(pie[msg.sender], wad); Pie = add(Pie, wad); vat.move(msg.sender, address(this), mul(chi, wad)); } function exit(uint wad) external { pie[msg.sender] = sub(pie[msg.sender], wad); Pie = sub(Pie, wad); vat.move(address(this), msg.sender, mul(chi, wad)); } } // SPDX-License-Identifier: AGPL-3.0-or-later /// dog.sol -- Dai liquidation module 2.0 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; interface ClipperLike { function ilk() external view returns (bytes32); function kick( uint256 tab, uint256 lot, address usr, address kpr ) external returns (uint256); } interface VatLike { function ilks(bytes32) external view returns ( uint256 Art, // [wad] uint256 rate, // [ray] uint256 spot, // [ray] uint256 line, // [rad] uint256 dust // [rad] ); function urns(bytes32,address) external view returns ( uint256 ink, // [wad] uint256 art // [wad] ); function grab(bytes32,address,address,address,int256,int256) external; function hope(address) external; function nope(address) external; } interface VowLike { function fess(uint256) external; } contract Dog { // --- Auth --- mapping (address => uint256) public wards; function rely(address usr) external auth { wards[usr] = 1; emit Rely(usr); } function deny(address usr) external auth { wards[usr] = 0; emit Deny(usr); } modifier auth { require(wards[msg.sender] == 1, "Dog/not-authorized"); _; } // --- Data --- struct Ilk { address clip; // Liquidator uint256 chop; // Liquidation Penalty [wad] uint256 hole; // Max DAI needed to cover debt+fees of active auctions per ilk [rad] uint256 dirt; // Amt DAI needed to cover debt+fees of active auctions per ilk [rad] } VatLike immutable public vat; // CDP Engine mapping (bytes32 => Ilk) public ilks; VowLike public vow; // Debt Engine uint256 public live; // Active Flag uint256 public Hole; // Max DAI needed to cover debt+fees of active auctions [rad] uint256 public Dirt; // Amt DAI needed to cover debt+fees of active auctions [rad] // --- Events --- event Rely(address indexed usr); event Deny(address indexed usr); event File(bytes32 indexed what, uint256 data); event File(bytes32 indexed what, address data); event File(bytes32 indexed ilk, bytes32 indexed what, uint256 data); event File(bytes32 indexed ilk, bytes32 indexed what, address clip); event Bark( bytes32 indexed ilk, address indexed urn, uint256 ink, uint256 art, uint256 due, address clip, uint256 indexed id ); event Digs(bytes32 indexed ilk, uint256 rad); event Cage(); // --- Init --- constructor(address vat_) public { vat = VatLike(vat_); live = 1; wards[msg.sender] = 1; emit Rely(msg.sender); } // --- Math --- uint256 constant WAD = 10 ** 18; function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x <= y ? x : y; } function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } // --- Administration --- function file(bytes32 what, address data) external auth { if (what == "vow") vow = VowLike(data); else revert("Dog/file-unrecognized-param"); emit File(what, data); } function file(bytes32 what, uint256 data) external auth { if (what == "Hole") Hole = data; else revert("Dog/file-unrecognized-param"); emit File(what, data); } function file(bytes32 ilk, bytes32 what, uint256 data) external auth { if (what == "chop") { require(data >= WAD, "Dog/file-chop-lt-WAD"); ilks[ilk].chop = data; } else if (what == "hole") ilks[ilk].hole = data; else revert("Dog/file-unrecognized-param"); emit File(ilk, what, data); } function file(bytes32 ilk, bytes32 what, address clip) external auth { if (what == "clip") { require(ilk == ClipperLike(clip).ilk(), "Dog/file-ilk-neq-clip.ilk"); ilks[ilk].clip = clip; } else revert("Dog/file-unrecognized-param"); emit File(ilk, what, clip); } function chop(bytes32 ilk) external view returns (uint256) { return ilks[ilk].chop; } // --- CDP Liquidation: all bark and no bite --- // // Liquidate a Vault and start a Dutch auction to sell its collateral for DAI. // // The third argument is the address that will receive the liquidation reward, if any. // // The entire Vault will be liquidated except when the target amount of DAI to be raised in // the resulting auction (debt of Vault + liquidation penalty) causes either Dirt to exceed // Hole or ilk.dirt to exceed ilk.hole by an economically significant amount. In that // case, a partial liquidation is performed to respect the global and per-ilk limits on // outstanding DAI target. The one exception is if the resulting auction would likely // have too little collateral to be interesting to Keepers (debt taken from Vault < ilk.dust), // in which case the function reverts. Please refer to the code and comments within if // more detail is desired. function bark(bytes32 ilk, address urn, address kpr) external returns (uint256 id) { require(live == 1, "Dog/not-live"); (uint256 ink, uint256 art) = vat.urns(ilk, urn); Ilk memory milk = ilks[ilk]; uint256 dart; uint256 rate; uint256 dust; { uint256 spot; (,rate, spot,, dust) = vat.ilks(ilk); require(spot > 0 && mul(ink, spot) < mul(art, rate), "Dog/not-unsafe"); // Get the minimum value between: // 1) Remaining space in the general Hole // 2) Remaining space in the collateral hole require(Hole > Dirt && milk.hole > milk.dirt, "Dog/liquidation-limit-hit"); uint256 room = min(Hole - Dirt, milk.hole - milk.dirt); // uint256.max()/(RAD*WAD) = 115,792,089,237,316 dart = min(art, mul(room, WAD) / rate / milk.chop); // Partial liquidation edge case logic if (art > dart) { if (mul(art - dart, rate) < dust) { // If the leftover Vault would be dusty, just liquidate it entirely. // This will result in at least one of dirt_i > hole_i or Dirt > Hole becoming true. // The amount of excess will be bounded above by ceiling(dust_i * chop_i / WAD). // This deviation is assumed to be small compared to both hole_i and Hole, so that // the extra amount of target DAI over the limits intended is not of economic concern. dart = art; } else { // In a partial liquidation, the resulting auction should also be non-dusty. require(mul(dart, rate) >= dust, "Dog/dusty-auction-from-partial-liquidation"); } } } uint256 dink = mul(ink, dart) / art; require(dink > 0, "Dog/null-auction"); require(dart <= 2**255 && dink <= 2**255, "Dog/overflow"); vat.grab( ilk, urn, milk.clip, address(vow), -int256(dink), -int256(dart) ); uint256 due = mul(dart, rate); vow.fess(due); { // Avoid stack too deep // This calcuation will overflow if dart*rate exceeds ~10^14 uint256 tab = mul(due, milk.chop) / WAD; Dirt = add(Dirt, tab); ilks[ilk].dirt = add(milk.dirt, tab); id = ClipperLike(milk.clip).kick({ tab: tab, lot: dink, usr: urn, kpr: kpr }); } emit Bark(ilk, urn, dink, dart, due, milk.clip, id); } function digs(bytes32 ilk, uint256 rad) external auth { Dirt = sub(Dirt, rad); ilks[ilk].dirt = sub(ilks[ilk].dirt, rad); emit Digs(ilk, rad); } function cage() external auth { live = 0; emit Cage(); } } // SPDX-License-Identifier: AGPL-3.0-or-later /// DssCdpManager.sol // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; interface VatLike { function urns(bytes32, address) external view returns (uint, uint); function hope(address) external; function flux(bytes32, address, address, uint) external; function move(address, address, uint) external; function frob(bytes32, address, address, address, int, int) external; function fork(bytes32, address, address, int, int) external; } contract UrnHandler { constructor(address vat) public { VatLike(vat).hope(msg.sender); } } contract DssCdpManager { address public vat; uint public cdpi; // Auto incremental mapping (uint => address) public urns; // CDPId => UrnHandler mapping (uint => List) public list; // CDPId => Prev & Next CDPIds (double linked list) mapping (uint => address) public owns; // CDPId => Owner mapping (uint => bytes32) public ilks; // CDPId => Ilk mapping (address => uint) public first; // Owner => First CDPId mapping (address => uint) public last; // Owner => Last CDPId mapping (address => uint) public count; // Owner => Amount of CDPs mapping ( address => mapping ( uint => mapping ( address => uint ) ) ) public cdpCan; // Owner => CDPId => Allowed Addr => True/False mapping ( address => mapping ( address => uint ) ) public urnCan; // Urn => Allowed Addr => True/False struct List { uint prev; uint next; } event NewCdp(address indexed usr, address indexed own, uint indexed cdp); modifier cdpAllowed( uint cdp ) { require(msg.sender == owns[cdp] || cdpCan[owns[cdp]][cdp][msg.sender] == 1, "cdp-not-allowed"); _; } modifier urnAllowed( address urn ) { require(msg.sender == urn || urnCan[urn][msg.sender] == 1, "urn-not-allowed"); _; } constructor(address vat_) public { vat = vat_; } function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function toInt(uint x) internal pure returns (int y) { y = int(x); require(y >= 0); } // Allow/disallow a usr address to manage the cdp. function cdpAllow( uint cdp, address usr, uint ok ) public cdpAllowed(cdp) { cdpCan[owns[cdp]][cdp][usr] = ok; } // Allow/disallow a usr address to quit to the the sender urn. function urnAllow( address usr, uint ok ) public { urnCan[msg.sender][usr] = ok; } // Open a new cdp for a given usr address. function open( bytes32 ilk, address usr ) public returns (uint) { require(usr != address(0), "usr-address-0"); cdpi = add(cdpi, 1); urns[cdpi] = address(new UrnHandler(vat)); owns[cdpi] = usr; ilks[cdpi] = ilk; // Add new CDP to double linked list and pointers if (first[usr] == 0) { first[usr] = cdpi; } if (last[usr] != 0) { list[cdpi].prev = last[usr]; list[last[usr]].next = cdpi; } last[usr] = cdpi; count[usr] = add(count[usr], 1); emit NewCdp(msg.sender, usr, cdpi); return cdpi; } // Give the cdp ownership to a dst address. function give( uint cdp, address dst ) public cdpAllowed(cdp) { require(dst != address(0), "dst-address-0"); require(dst != owns[cdp], "dst-already-owner"); // Remove transferred CDP from double linked list of origin user and pointers if (list[cdp].prev != 0) { list[list[cdp].prev].next = list[cdp].next; // Set the next pointer of the prev cdp (if exists) to the next of the transferred one } if (list[cdp].next != 0) { // If wasn't the last one list[list[cdp].next].prev = list[cdp].prev; // Set the prev pointer of the next cdp to the prev of the transferred one } else { // If was the last one last[owns[cdp]] = list[cdp].prev; // Update last pointer of the owner } if (first[owns[cdp]] == cdp) { // If was the first one first[owns[cdp]] = list[cdp].next; // Update first pointer of the owner } count[owns[cdp]] = sub(count[owns[cdp]], 1); // Transfer ownership owns[cdp] = dst; // Add transferred CDP to double linked list of destiny user and pointers list[cdp].prev = last[dst]; list[cdp].next = 0; if (last[dst] != 0) { list[last[dst]].next = cdp; } if (first[dst] == 0) { first[dst] = cdp; } last[dst] = cdp; count[dst] = add(count[dst], 1); } // Frob the cdp keeping the generated USB or collateral freed in the cdp urn address. function frob( uint cdp, int dink, int dart ) public cdpAllowed(cdp) { address urn = urns[cdp]; VatLike(vat).frob( ilks[cdp], urn, urn, urn, dink, dart ); } // Transfer wad amount of cdp collateral from the cdp address to a dst address. function flux( uint cdp, address dst, uint wad ) public cdpAllowed(cdp) { VatLike(vat).flux(ilks[cdp], urns[cdp], dst, wad); } // Transfer wad amount of any type of collateral (ilk) from the cdp address to a dst address. // This function has the purpose to take away collateral from the system that doesn't correspond to the cdp but was sent there wrongly. function flux( bytes32 ilk, uint cdp, address dst, uint wad ) public cdpAllowed(cdp) { VatLike(vat).flux(ilk, urns[cdp], dst, wad); } // Transfer wad amount of USB from the cdp address to a dst address. function move( uint cdp, address dst, uint rad ) public cdpAllowed(cdp) { VatLike(vat).move(urns[cdp], dst, rad); } // Quit the system, migrating the cdp (ink, art) to a different dst urn function quit( uint cdp, address dst ) public cdpAllowed(cdp) urnAllowed(dst) { (uint ink, uint art) = VatLike(vat).urns(ilks[cdp], urns[cdp]); VatLike(vat).fork( ilks[cdp], urns[cdp], dst, toInt(ink), toInt(art) ); } // Import a position from src urn to the urn owned by cdp function enter( address src, uint cdp ) public urnAllowed(src) cdpAllowed(cdp) { (uint ink, uint art) = VatLike(vat).urns(ilks[cdp], src); VatLike(vat).fork( ilks[cdp], src, urns[cdp], toInt(ink), toInt(art) ); } // Move a position from cdpSrc urn to the cdpDst urn function shift( uint cdpSrc, uint cdpDst ) public cdpAllowed(cdpSrc) cdpAllowed(cdpDst) { require(ilks[cdpSrc] == ilks[cdpDst], "non-matching-cdps"); (uint ink, uint art) = VatLike(vat).urns(ilks[cdpSrc], urns[cdpSrc]); VatLike(vat).fork( ilks[cdpSrc], urns[cdpSrc], urns[cdpDst], toInt(ink), toInt(art) ); } } // SPDX-License-Identifier: AGPL-3.0-or-later // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity ^0.8.0; interface Abacus { // 1st arg: initial price [ray] // 2nd arg: seconds since auction start [seconds] // returns: current auction price [ray] function price(uint256, uint256) external view returns (uint256); } contract LinearDecrease is Abacus { // --- Auth --- mapping (address => uint256) public wards; function rely(address usr) external auth { wards[usr] = 1; emit Rely(usr); } function deny(address usr) external auth { wards[usr] = 0; emit Deny(usr); } modifier auth { require(wards[msg.sender] == 1, "LinearDecrease/not-authorized"); _; } // --- Data --- uint256 public tau; // Seconds after auction start when the price reaches zero [seconds] // --- Events --- event Rely(address indexed usr); event Deny(address indexed usr); event File(bytes32 indexed what, uint256 data); // --- Init --- constructor() public { wards[msg.sender] = 1; emit Rely(msg.sender); } // --- Administration --- function file(bytes32 what, uint256 data) external auth { if (what == "tau") tau = data; else revert("LinearDecrease/file-unrecognized-param"); emit File(what, data); } // --- Math --- uint256 constant RAY = 10 ** 27; function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x * y; require(y == 0 || z / y == x); z = z / RAY; } // Price calculation when price is decreased linearly in proportion to time: // tau: The number of seconds after the start of the auction where the price will hit 0 // top: Initial price // dur: current seconds since the start of the auction // // Returns y = top * ((tau - dur) / tau) // // Note the internal call to mul multiples by RAY, thereby ensuring that the rmul calculation // which utilizes top and tau (RAY values) is also a RAY value. function price(uint256 top, uint256 dur) override external view returns (uint256) { if (dur >= tau) return 0; return rmul(top, mul(tau - dur, RAY) / tau); } } contract StairstepExponentialDecrease is Abacus { // --- Auth --- mapping (address => uint256) public wards; function rely(address usr) external auth { wards[usr] = 1; emit Rely(usr); } function deny(address usr) external auth { wards[usr] = 0; emit Deny(usr); } modifier auth { require(wards[msg.sender] == 1, "StairstepExponentialDecrease/not-authorized"); _; } // --- Data --- uint256 public step; // Length of time between price drops [seconds] uint256 public cut; // Per-step multiplicative factor [ray] // --- Events --- event Rely(address indexed usr); event Deny(address indexed usr); event File(bytes32 indexed what, uint256 data); // --- Init --- // @notice: `cut` and `step` values must be correctly set for // this contract to return a valid price constructor() public { wards[msg.sender] = 1; emit Rely(msg.sender); } // --- Administration --- function file(bytes32 what, uint256 data) external auth { if (what == "cut") require((cut = data) <= RAY, "StairstepExponentialDecrease/cut-gt-RAY"); else if (what == "step") step = data; else revert("StairstepExponentialDecrease/file-unrecognized-param"); emit File(what, data); } // --- Math --- uint256 constant RAY = 10 ** 27; function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x * y; require(y == 0 || z / y == x); z = z / RAY; } // optimized version from dss PR #78 function rpow(uint256 x, uint256 n, uint256 b) internal pure returns (uint256 z) { assembly { switch n case 0 { z := b } default { switch x case 0 { z := 0 } default { switch mod(n, 2) case 0 { z := b } default { z := x } let half := div(b, 2) // for rounding. for { n := div(n, 2) } n { n := div(n,2) } { let xx := mul(x, x) if shr(128, x) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } x := div(xxRound, b) if mod(n,2) { let zx := mul(z, x) if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z := div(zxRound, b) } } } } } } // top: initial price // dur: seconds since the auction has started // step: seconds between a price drop // cut: cut encodes the percentage to decrease per step. // For efficiency, the values is set as (1 - (% value / 100)) * RAY // So, for a 1% decrease per step, cut would be (1 - 0.01) * RAY // // returns: top * (cut ^ dur) // // function price(uint256 top, uint256 dur) override external view returns (uint256) { return rmul(top, rpow(cut, dur / step, RAY)); } } // While an equivalent function can be obtained by setting step = 1 in StairstepExponentialDecrease, // this continous (i.e. per-second) exponential decrease has be implemented as it is more gas-efficient // than using the stairstep version with step = 1 (primarily due to 1 fewer SLOAD per price calculation). contract ExponentialDecrease is Abacus { // --- Auth --- mapping (address => uint256) public wards; function rely(address usr) external auth { wards[usr] = 1; emit Rely(usr); } function deny(address usr) external auth { wards[usr] = 0; emit Deny(usr); } modifier auth { require(wards[msg.sender] == 1, "ExponentialDecrease/not-authorized"); _; } // --- Data --- uint256 public cut; // Per-second multiplicative factor [ray] // --- Events --- event Rely(address indexed usr); event Deny(address indexed usr); event File(bytes32 indexed what, uint256 data); // --- Init --- // @notice: `cut` value must be correctly set for // this contract to return a valid price constructor() public { wards[msg.sender] = 1; emit Rely(msg.sender); } // --- Administration --- function file(bytes32 what, uint256 data) external auth { if (what == "cut") require((cut = data) <= RAY, "ExponentialDecrease/cut-gt-RAY"); else revert("ExponentialDecrease/file-unrecognized-param"); emit File(what, data); } // --- Math --- uint256 constant RAY = 10 ** 27; function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x * y; require(y == 0 || z / y == x); z = z / RAY; } // optimized version from dss PR #78 function rpow(uint256 x, uint256 n, uint256 b) internal pure returns (uint256 z) { assembly { switch n case 0 { z := b } default { switch x case 0 { z := 0 } default { switch mod(n, 2) case 0 { z := b } default { z := x } let half := div(b, 2) // for rounding. for { n := div(n, 2) } n { n := div(n,2) } { let xx := mul(x, x) if shr(128, x) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } x := div(xxRound, b) if mod(n,2) { let zx := mul(z, x) if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z := div(zxRound, b) } } } } } } // top: initial price // dur: seconds since the auction has started // cut: cut encodes the percentage to decrease per second. // For efficiency, the values is set as (1 - (% value / 100)) * RAY // So, for a 1% decrease per second, cut would be (1 - 0.01) * RAY // // returns: top * (cut ^ dur) // function price(uint256 top, uint256 dur) override external view returns (uint256) { return rmul(top, rpow(cut, dur, RAY)); } } /// token.sol -- ERC20 implementation with minting and burning // Copyright (C) 2015, 2016, 2017 DappHub, LLC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.23; interface DSAuthority { function canCall( address src, address dst, bytes4 sig ) external view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() public { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(address(0))) { return false; } else { return authority.canCall(src, address(this), sig); } } } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; //rounds to zero if x*y < WAD / 2 function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } //rounds to zero if x*y < WAD / 2 function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } //rounds to zero if x*y < WAD / 2 function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } //rounds to zero if x*y < RAY / 2 function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } contract DSToken is DSMath, DSAuth { bool public stopped; uint256 public totalSupply; mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; string public symbol; uint8 public decimals = 18; // standard token precision. override to customize string public name = ""; // Optional token name constructor(string memory symbol_) public { symbol = symbol_; } event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Mint(address indexed guy, uint wad); event Burn(address indexed guy, uint wad); event Stop(); event Start(); modifier stoppable { require(!stopped, "ds-stop-is-stopped"); _; } function approve(address guy) external returns (bool) { return approve(guy, type(uint256).max); } function approve(address guy, uint wad) public stoppable returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint wad) external returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public stoppable returns (bool) { if (src != msg.sender && allowance[src][msg.sender] != type(uint256).max) { require(allowance[src][msg.sender] >= wad, "ds-token-insufficient-approval"); allowance[src][msg.sender] = sub(allowance[src][msg.sender], wad); } require(balanceOf[src] >= wad, "ds-token-insufficient-balance"); balanceOf[src] = sub(balanceOf[src], wad); balanceOf[dst] = add(balanceOf[dst], wad); emit Transfer(src, dst, wad); return true; } function push(address dst, uint wad) external { transferFrom(msg.sender, dst, wad); } function pull(address src, uint wad) external { transferFrom(src, msg.sender, wad); } function move(address src, address dst, uint wad) external { transferFrom(src, dst, wad); } function mint(uint wad) external { mint(msg.sender, wad); } function burn(uint wad) external { burn(msg.sender, wad); } function mint(address guy, uint wad) public auth stoppable { balanceOf[guy] = add(balanceOf[guy], wad); totalSupply = add(totalSupply, wad); emit Mint(guy, wad); } function burn(address guy, uint wad) public auth stoppable { if (guy != msg.sender && allowance[guy][msg.sender] != type(uint256).max) { require(allowance[guy][msg.sender] >= wad, "ds-token-insufficient-approval"); allowance[guy][msg.sender] = sub(allowance[guy][msg.sender], wad); } require(balanceOf[guy] >= wad, "ds-token-insufficient-balance"); balanceOf[guy] = sub(balanceOf[guy], wad); totalSupply = sub(totalSupply, wad); emit Burn(guy, wad); } function stop() public auth { stopped = true; emit Stop(); } function start() public auth { stopped = false; emit Start(); } function setName(string memory name_) public auth { name = name_; } }
Moves the amount from the CDP urn to proxy's address Exits WETH amount to proxy address as a token Converts WETH to ETH Sends ETH back to the user's wallet
function exitETH( address manager, address ethJoin, uint cdp, uint wad ) public { flux(manager, cdp, address(this), wad); GemJoinLike(ethJoin).exit(address(this), wad); GemJoinLike(ethJoin).gem().withdraw(wad); payable(msg.sender).transfer(wad); }
6,289,980
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "./external/interfaces/IERC721VaultFactory.sol"; import "./external/interfaces/ITokenVault.sol"; interface IBounty { function redeemBounty( IBountyRedeemer redeemer, uint256 amount, bytes calldata data ) external; } interface IBountyRedeemer { function onRedeemBounty(address initiator, bytes calldata data) external payable returns (bytes32); } // @notice Bounty isn't upgradeable, but because it is deploys as a // static proxy, needs to extend upgradeable contracts. contract Bounty is ReentrancyGuardUpgradeable, ERC721HolderUpgradeable, IBounty { using Counters for Counters.Counter; enum BountyStatus { ACTIVE, ACQUIRED, EXPIRED } struct Contribution { uint256 priorTotalContributed; uint256 amount; } // tokens are minted at a rate of 1 ETH : 1000 tokens uint16 internal constant TOKEN_SCALE = 1000; uint8 internal constant RESALE_MULTIPLIER = 2; // immutable (across clones) address public immutable gov; IERC721VaultFactory public immutable tokenVaultFactory; // immutable (at clone level) IERC721 public nftContract; uint256 public nftTokenID; string public name; string public symbol; uint256 public contributionCap; uint256 public expiryTimestamp; // mutables mapping(address => Contribution[]) public contributions; mapping(address => uint256) public totalContributedByAddress; mapping(address => bool) public claimed; uint256 public totalContributed; uint256 public totalSpent; ITokenVault public tokenVault; Counters.Counter public contributors; event Contributed(address indexed contributor, uint256 amount); event Acquired(uint256 amount); event Claimed( address indexed contributor, uint256 tokenAmount, uint256 ethAmount ); modifier onlyGov() { require(msg.sender == gov, "Bounty:: only callable by gov"); _; } constructor(address _gov, IERC721VaultFactory _tokenVaultFactory) { gov = _gov; tokenVaultFactory = _tokenVaultFactory; } function initialize( IERC721 _nftContract, uint256 _nftTokenID, string memory _name, string memory _symbol, uint256 _contributionCap, uint256 _duration ) external initializer { __ReentrancyGuard_init(); __ERC721Holder_init(); nftContract = _nftContract; nftTokenID = _nftTokenID; name = _name; symbol = _symbol; contributionCap = _contributionCap; expiryTimestamp = block.timestamp + _duration; require( IERC721(nftContract).ownerOf(nftTokenID) != address(0), "Bounty::initialize: Token does not exist" ); } // @notice contribute (via msg.value) to active bounty as long as the contribution cap has not been reached function contribute() external payable nonReentrant { require( status() == BountyStatus.ACTIVE, "Bounty::contribute: bounty not active" ); address _contributor = msg.sender; uint256 _amount = msg.value; require(_amount > 0, "Bounty::contribute: must contribute more than 0"); require( contributionCap == 0 || totalContributed < contributionCap, "Bounty::contribute: at max contributions" ); if (contributions[_contributor].length == 0) { contributors.increment(); } Contribution memory _contribution = Contribution({ amount: _amount, priorTotalContributed: totalContributed }); contributions[_contributor].push(_contribution); totalContributedByAddress[_contributor] = totalContributedByAddress[_contributor] + _amount; totalContributed = totalContributed + _amount; emit Contributed(_contributor, _amount); } // @notice uses the redeemer to swap `_amount` ETH for the NFT // @param _redeemer The callback to acquire the NFT // @param _amount The amount of the bounty to redeem. Must be <= MIN(totalContributed, contributionCap) // @param _data Arbitrary calldata for the callback function redeemBounty( IBountyRedeemer _redeemer, uint256 _amount, bytes calldata _data ) external override nonReentrant { require( status() == BountyStatus.ACTIVE, "Bounty::redeemBounty: bounty isn't active" ); require(totalSpent == 0, "Bounty::redeemBounty: already acquired"); require(_amount > 0, "Bounty::redeemBounty: cannot redeem for free"); require( _amount <= totalContributed && _amount <= contributionCap, "Bounty::redeemBounty: not enough funds" ); totalSpent = _amount; require( _redeemer.onRedeemBounty{value: _amount}(msg.sender, _data) == keccak256("IBountyRedeemer.onRedeemBounty"), "Bounty::redeemBounty: callback failed" ); require( IERC721(nftContract).ownerOf(nftTokenID) == address(this), "Bounty::redeemBounty: NFT not delivered" ); emit Acquired(_amount); } // @notice Kicks off fractionalization once the NFT is acquired // @dev Also triggered by the first claim() function fractionalize() external nonReentrant { require( status() == BountyStatus.ACQUIRED, "Bounty::fractionalize: NFT not yet acquired" ); _fractionalizeNFTIfNeeded(); } // @notice Claims any tokens or eth for `_contributor` from active or expired bounties // @dev msg.sender does not necessarily match `_contributor` // @dev O(N) where N = number of contributions by `_contributor` // @param _contributor The address of the contributor to claim tokens for function claim(address _contributor) external nonReentrant { BountyStatus _status = status(); require( _status != BountyStatus.ACTIVE, "Bounty::claim: bounty still active" ); require( totalContributedByAddress[_contributor] != 0, "Bounty::claim: not a contributor" ); require( !claimed[_contributor], "Bounty::claim: bounty already claimed" ); claimed[_contributor] = true; if (_status == BountyStatus.ACQUIRED) { _fractionalizeNFTIfNeeded(); } (uint256 _tokenAmount, uint256 _ethAmount) = claimAmounts(_contributor); if (_ethAmount > 0) { _transferETH(_contributor, _ethAmount); } if (_tokenAmount > 0) { _transferTokens(_contributor, _tokenAmount); } emit Claimed(_contributor, _tokenAmount, _ethAmount); } // @notice (GOV ONLY) emergency: withdraw stuck ETH function emergencyWithdrawETH(uint256 _value) external onlyGov { _transferETH(gov, _value); } // @notice (GOV ONLY) emergency: execute arbitrary calls from contract function emergencyCall(address _contract, bytes memory _calldata) external onlyGov returns (bool _success, bytes memory _returnData) { (_success, _returnData) = _contract.call(_calldata); require(_success, string(_returnData)); } // @notice (GOV ONLY) emergency: immediately expires bounty function emergencyExpire() external onlyGov { expiryTimestamp = block.timestamp; } // @notice The amount of tokens and ETH that can or have been claimed by `_contributor` // @dev Check `claimed(address)` to see if already claimed // @param _contributor The address of the contributor to compute amounts for. function claimAmounts(address _contributor) public view returns (uint256 _tokenAmount, uint256 _ethAmount) { require( status() != BountyStatus.ACTIVE, "Bounty::claimAmounts: bounty still active" ); if (totalSpent > 0) { uint256 _ethUsed = ethUsedForAcquisition(_contributor); if (_ethUsed > 0) { _tokenAmount = valueToTokens(_ethUsed); } _ethAmount = totalContributedByAddress[_contributor] - _ethUsed; } else { _ethAmount = totalContributedByAddress[_contributor]; } } // @notice The amount of the contributor's ETH used to acquire the NFT // @notice Tokens owed will be proportional to eth used. // @notice ETH contributed = ETH used in acq + ETH left to be claimed // @param _contributor The address of the contributor to compute eth usd function ethUsedForAcquisition(address _contributor) public view returns (uint256 _total) { require( totalSpent > 0, "Bounty::ethUsedForAcquisition: NFT not acquired yet" ); // load from storage once and reuse uint256 _totalSpent = totalSpent; Contribution[] memory _contributions = contributions[_contributor]; for (uint256 _i = 0; _i < _contributions.length; _i++) { Contribution memory _contribution = _contributions[_i]; if ( _contribution.priorTotalContributed + _contribution.amount <= _totalSpent ) { _total = _total + _contribution.amount; } else if (_contribution.priorTotalContributed < _totalSpent) { uint256 _amountUsed = _totalSpent - _contribution.priorTotalContributed; _total = _total + _amountUsed; break; } else { break; } } } // @notice Computes the status of the bounty // Valid state transitions: // EXPIRED // ACTIVE -> EXPIRED // ACTIVE -> ACQUIRED function status() public view returns (BountyStatus) { if (totalSpent > 0) { return BountyStatus.ACQUIRED; } else if (block.timestamp >= expiryTimestamp) { return BountyStatus.EXPIRED; } else { return BountyStatus.ACTIVE; } } // @dev Helper function for translating ETH contributions into token amounts function valueToTokens(uint256 _value) public pure returns (uint256 _tokens) { _tokens = _value * TOKEN_SCALE; } function _transferETH(address _to, uint256 _value) internal { // guard against rounding errors uint256 _balance = address(this).balance; if (_value > _balance) { _value = _balance; } payable(_to).transfer(_value); } function _transferTokens(address _to, uint256 _value) internal { // guard against rounding errors uint256 _balance = tokenVault.balanceOf(address(this)); if (_value > _balance) { _value = _balance; } tokenVault.transfer(_to, _value); } function _fractionalizeNFTIfNeeded() internal { if (address(tokenVault) != address(0)) { return; } IERC721(nftContract).approve(address(tokenVaultFactory), nftTokenID); uint256 _vaultNumber = tokenVaultFactory.mint( name, symbol, address(nftContract), nftTokenID, valueToTokens(totalSpent), totalSpent * RESALE_MULTIPLIER, 0 // fees ); tokenVault = ITokenVault(tokenVaultFactory.vaults(_vaultNumber)); tokenVault.updateCurator(address(0)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721ReceiverUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}. */ contract ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable { function __ERC721Holder_init() internal initializer { __ERC721Holder_init_unchained(); } function __ERC721Holder_init_unchained() internal initializer { } /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.3; interface IERC721VaultFactory { /// @notice the mapping of vault number to vault address function vaults(uint256) external returns (address); /// @notice the function to mint a new vault /// @param _name the desired name of the vault /// @param _symbol the desired sumbol of the vault /// @param _token the ERC721 token address fo the NFT /// @param _id the uint256 ID of the token /// @param _listPrice the initial price of the NFT /// @return the ID of the vault function mint( string memory _name, string memory _symbol, address _token, uint256 _id, uint256 _supply, uint256 _listPrice, uint256 _fee ) external returns (uint256); } //SPDX-License-Identifier: MIT pragma solidity ^0.8.3; interface ITokenVault { /// @notice allow curator to update the curator address /// @param _curator the new curator function updateCurator(address _curator) external; /** * @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) external returns (bool); /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) external view returns (uint256); } // 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; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } }
uses the redeemer to swap `_amount` ETH for the NFT _redeemer The callback to acquire the NFT _amount The amount of the bounty to redeem. Must be <= MIN(totalContributed, contributionCap) _data Arbitrary calldata for the callback
function redeemBounty( IBountyRedeemer _redeemer, uint256 _amount, bytes calldata _data ) external override nonReentrant { require( status() == BountyStatus.ACTIVE, "Bounty::redeemBounty: bounty isn't active" ); require(totalSpent == 0, "Bounty::redeemBounty: already acquired"); require(_amount > 0, "Bounty::redeemBounty: cannot redeem for free"); require( _amount <= totalContributed && _amount <= contributionCap, "Bounty::redeemBounty: not enough funds" ); totalSpent = _amount; require( keccak256("IBountyRedeemer.onRedeemBounty"), "Bounty::redeemBounty: callback failed" ); require( IERC721(nftContract).ownerOf(nftTokenID) == address(this), "Bounty::redeemBounty: NFT not delivered" ); emit Acquired(_amount); }
1,180,117
./full_match/1/0xBD11Fa14B31eAfD4648a43D8e3f40c23dCa21C6C/sources/AdapterHelper.sol
Calculates ETH and token balances available for services -------------------------------- availableEther is ETH balance of the TokenProfit contract availableTokens is balances of all tokens in TokenProfit contract etherAmount is availableEther + ETH deposited in other services tokenAmounts is availableTokens + tokens deposited in other services/
function getTokenAmounts() public view returns ( uint256 etherAmount, uint256[] memory tokensAmounts, uint256 availableEther, uint256[] memory availableAmounts ) { uint256[] memory tokenAmounts = new uint256[](TOKENS); uint256[] memory availableTokens = new uint256[](TOKENS); ( availableEther, availableTokens ) = _getAvailableFunds(); for (uint256 i = 0; i < TOKENS; i++) { tokenAmounts[i] = _getReservesByToken( tokens[i].tokenERC20 ) + availableTokens[i]; } etherAmount = _calculateAmountFromShares( liquidNFTsWETHPool, TOKEN_PROFIT_ADDRESS ) + availableEther; return ( etherAmount, tokenAmounts, availableEther, availableTokens ); }
16,571,960
// declare which version of Solidity we are using // different versions of Solidity have different pragma solidity ^0.4.18; // define a smart contract called "BasicToken" contract BasicToken { // examples of simple variables // string myName; // bool isApproved; // uint daysRemaining; // an array is a list of individuals values, e.g. list of numbers, list of names // uint256[] numbers; // a mapping is a list of pairs mapping(address => uint256) balances; // a mapping of all user's balances // 0xa5c => 10 Ether // 0x91b => 5 Ether // 0xcdd => 1.25 Ether // another mapping example // mapping(address => bool) signatures; // a mapping of signatures // 0xa2d => true (approved) // 0xb24 => true (approved) // 0x515 => false (not approved) // address myAddress = 0x1235647381947839275893275893; // ethereum address // uint256 count = 10; // unsigned (non-negative) integer, 256-bytes in size /** * @dev transfer token for a specified address * @param recipient The address to transfer to. * @param value The amount to be transferred. */ // define a function called "transfer" // inputs? (parameters) an address called "recipient" and a uint256 called "value" function transfer(address recipient, uint256 value) public { // msg.sender is a predefined variable that specifies the address of the // person sending this transaction // address msg.sender = 0x5ba...; // balances[msg.sender] -> set the balance of the sender // set the balance of the sender to their current balance minus value // withdrawing tokens from the sender's account balances[msg.sender] -= value; // balances[recipient] -> set the balance of the receiver (recipient) // set the balance of the receiver to their current balance plus value // depositing tokens into the receiver's account balances[recipient] += value; } /** * @dev Gets the balance of the specified address. * @param account The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ // define function called "balanceOf" // inputs? (parameters) the address of the owner (account) // ontputs? (returns) the balance (number) function balanceOf(address account) public view returns (uint256) { // balances[account] -> return the balance of the owner return balances[account]; } }
Gets the balance of the specified address. account The address to query the the balance of. return An uint256 representing the amount owned by the passed address./ define function called "balanceOf" inputs? (parameters) the address of the owner (account) ontputs? (returns) the balance (number) balances[account] -> return the balance of the owner
function balanceOf(address account) public view returns (uint256) { return balances[account]; }
14,082,820
// File: contracts/support/IERC20.sol pragma solidity ^0.5.0; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/support/SafeMath.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted to use pragma ^0.4.24 and satisfy our linter rules pragma solidity ^0.5.0; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b, ERROR_MUL_OVERFLOW); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: contracts/support/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/support/Ownable.sol pragma solidity ^0.5.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. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address payable private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor (address payable owner) internal { _owner = owner; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address payable) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address payable newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address payable newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/core/Pool.sol pragma solidity ^0.5.0; /** a pegged contract that let's token holders redem tokens for a base token */ contract Pool is IERC20, Ownable { string public constant name = "FDAI-1"; string public constant symbol = "FDAI"; uint8 public constant decimals = 18; uint8 public status = 1; // 1: open, 0: closed uint256 totalSupply_; /** The pool will pay 1 base token per token once closed. It closes whenever the balance of baseToken is equal or larfer than the totalSupply */ IERC20 public baseToken; IERC20 public govToken; address public beneficiary; event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Transfer(address indexed from, address indexed to, uint tokens); mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; using SafeMath for uint256; constructor(address _beneficiary, IERC20 _baseToken, IERC20 _govToken, address payable owner) Ownable(owner) public { totalSupply_ = 0; beneficiary = _beneficiary; baseToken = _baseToken; govToken = _govToken; balances[msg.sender] = totalSupply_; } // SPECIAL METHODS function setBeneficiary(address newBeneficiary) public onlyOwner { beneficiary = newBeneficiary; } /** Anyone can close the pool once it has enough baseToken balance to it's name */ function close() public { require(baseToken.balanceOf(address(this)) >= totalSupply_, "balance of base token is not enough"); status = 0; } // once closed it cannot mint more tokens. It cannot be reopened function closeOwner() public onlyOwner () { status = 0; } /** Mints amount tokens to address "to" */ function mint(address account, uint256 amount) public onlyOwner returns (uint256) { require(status == 1, "token pool is closed"); totalSupply_ = totalSupply_.add(amount); balances[account] = balances[account].add(amount); emit Transfer(address(0), account, amount); } // burns the token balance of adr and transfer that amount of baseTokens to ita function payback(address adr) public { require(status == 0, "token pool is still open"); require(govToken.balanceOf(adr) == 0); uint256 balance = balances[adr]; balances[adr] = 0; totalSupply_ = totalSupply_.sub(balance); baseToken.transfer(adr, balance); } /** a function to move future revenue to the beneficiary (can be another pool)*/ function withdraw() public { require(status == 0, "token pool is still open"); require(totalSupply_ == 0, "withdraw is only valid once all debt is paid"); // transfer all baseTokens to beneficiary baseToken.transfer(beneficiary, baseToken.balanceOf(address(this))); } /** ERC20 STANDARD METHODS */ function totalSupply() public view returns (uint256) { return totalSupply_; } function balanceOf(address tokenOwner) public view returns (uint256) { return balances[tokenOwner]; } function transfer(address receiver, uint256 numTokens) public returns (bool) { require(numTokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(numTokens); balances[receiver] = balances[receiver].add(numTokens); emit Transfer(msg.sender, receiver, numTokens); return true; } function approve(address delegate, uint256 numTokens) public returns (bool) { allowed[msg.sender][delegate] = numTokens; emit Approval(msg.sender, delegate, numTokens); return true; } function allowance(address owner, address delegate) public view returns (uint) { return allowed[owner][delegate]; } function transferFrom(address owner, address buyer, uint256 numTokens) public returns (bool) { require(numTokens <= balances[owner]); require(numTokens <= allowed[owner][msg.sender]); balances[owner] = balances[owner].sub(numTokens); allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(numTokens); balances[buyer] = balances[buyer].add(numTokens); emit Transfer(owner, buyer, numTokens); return true; } } // File: contracts/pools/Pool1.sol pragma solidity ^0.5.0; /** a pegged contract that let's token holders redem tokens for a base token */ contract Pool1 is Pool { string public constant name = "FDAI+1"; constructor(address _beneficiary, IERC20 _baseToken, IERC20 _govToken, address payable owner) Pool(_beneficiary, _baseToken, _govToken, owner) public { } }
a function to move future revenue to the beneficiary (can be another pool)/ transfer all baseTokens to beneficiary
function withdraw() public { require(status == 0, "token pool is still open"); require(totalSupply_ == 0, "withdraw is only valid once all debt is paid"); baseToken.transfer(beneficiary, baseToken.balanceOf(address(this))); }
2,538,682
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.7.6; abstract contract ReentrancyGuard { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } } // ---------------------------------------------------------------------------- // SafeMath library // ---------------------------------------------------------------------------- library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function ceil(uint a, uint m) internal pure returns (uint r) { return (a + m - 1) / m * m; } } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address payable _newOwner) public onlyOwner { require(_newOwner != address(0), "ERC20: sending to the zero address"); owner = _newOwner; emit OwnershipTransferred(msg.sender, _newOwner); } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // ---------------------------------------------------------------------------- interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address tokenOwner) external view returns (uint256 balance); function allowance(address tokenOwner, address spender) external view returns (uint256 remaining); function transfer(address to, uint256 tokens) external returns (bool success); function approve(address spender, uint256 tokens) external returns (bool success); function transferFrom(address from, address to, uint256 tokens) external returns (bool success); function burnTokens(uint256 _amount) external; function calculateFeesBeforeSend( address sender, address recipient, uint256 amount ) external view returns (uint256, uint256); event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } interface regreward { function distributeV2() external; } interface FEGex2 { function BUY( address to, uint minAmountOut ) external payable returns (uint tokenAmountOut, uint spotPriceAfter); } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- library Roles { struct Role { mapping (address => bool) bearer; } function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } contract WhitelistAdminRole is Owned { using Roles for Roles.Role; event WhitelistAdminAdded(address indexed account); event WhitelistAdminRemoved(address indexed account); Roles.Role private _whitelistAdmins; constructor () { _addWhitelistAdmin(msg.sender); } modifier onlyWhitelistAdmin() { require(isWhitelistAdmin(msg.sender), "WhitelistAdminRole: caller does not have the WhitelistAdmin role"); _; } 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); } } contract FNum is ReentrancyGuard{ uint public constant BASE = 10**18; function badd(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } function bsub(uint a, uint b) internal pure returns (uint) { (uint c, bool flag) = bsubSign(a, b); require(!flag, "ERR_SUB_UNDERFLOW"); return c; } function bsubSign(uint a, uint b) internal pure returns (uint, bool) { if (a >= b) { return (a - b, false); } else { return (b - a, true); } } function bmul(uint a, uint b) internal pure returns (uint) { uint c0 = a * b; require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW"); uint c1 = c0 + (BASE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint c2 = c1 / BASE; return c2; } function bdiv(uint a, uint b) internal pure returns (uint) { require(b != 0, "ERR_DIV_ZERO"); uint c0 = a * BASE; require(a == 0 || c0 / a == BASE, "ERR_DIV_INTERNAL"); // bmul overflow uint c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint c2 = c1 / b; return c2; } function btoi(uint a) internal pure returns (uint) { return a / BASE; } function bfloor(uint a) internal pure returns (uint) { return btoi(a) * BASE; } function bpowi(uint a, uint n) internal pure returns (uint) { uint z = n % 2 != 0 ? a : BASE; for (n /= 2; n != 0; n /= 2) { a = bmul(a, a); if (n % 2 != 0) { z = bmul(z, a); } } return z; } function bpow(uint base, uint exp) internal pure returns (uint) { uint whole = bfloor(exp); uint remain = bsub(exp, whole); uint wholePow = bpowi(base, btoi(whole)); if (remain == 0) { return wholePow; } uint BPOW_PRECISION = BASE / 10**10; uint partialResult = bpowApprox(base, remain, BPOW_PRECISION); return bmul(wholePow, partialResult); } function bpowApprox(uint base, uint exp, uint precision) internal pure returns (uint) { // term 0: uint a = exp; (uint x, bool xneg) = bsubSign(base, BASE); uint term = BASE; uint sum = term; bool negative = false; for (uint i = 1; term >= precision; i++) { uint bigK = i * BASE; (uint c, bool cneg) = bsubSign(a, bsub(bigK, BASE)); term = bmul(term, bmul(c, x)); term = bdiv(term, bigK); if (term == 0) break; if (xneg) negative = !negative; if (cneg) negative = !negative; if (negative) { sum = bsub(sum, term); } else { sum = badd(sum, term); } } return sum; } } contract FTokenBase is FNum { mapping(address => uint) internal _balance; mapping(address => mapping(address=>uint)) internal _allowance; uint public _totalSupply; event Approval(address indexed src, address indexed dst, uint amt); event Transfer(address indexed src, address indexed dst, uint amt); function _mint(uint amt) internal { _balance[address(this)] = badd(_balance[address(this)], amt); _totalSupply = badd(_totalSupply, amt); emit Transfer(address(0), address(this), amt); } function _burn(uint amt) internal { require(_balance[address(this)] >= amt); _balance[address(this)] = bsub(_balance[address(this)], amt); _totalSupply = bsub(_totalSupply, amt); emit Transfer(address(this), address(0), amt); } function _move(address src, address dst, uint amt) internal { require(_balance[src] >= amt); _balance[src] = bsub(_balance[src], amt); _balance[dst] = badd(_balance[dst], amt); emit Transfer(src, dst, amt); } function _push(address to, uint amt) internal { _move(address(this), to, amt); } function _pull(address from, uint amt) internal { _move(from, address(this), amt); } } contract FToken is FTokenBase { string private _name = "FEG Stake Shares"; string private _symbol = "FSS"; uint8 private _decimals = 18; function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } function allowance(address src, address dst) external view returns (uint) { return _allowance[src][dst]; } function balanceOf(address whom) external view returns (uint) { return _balance[whom]; } function totalSupply() public view returns (uint) { return _totalSupply; } function approve(address dst, uint amt) external returns (bool) { _allowance[msg.sender][dst] = amt; emit Approval(msg.sender, dst, amt); return true; } function increaseApproval(address dst, uint amt) external returns (bool) { _allowance[msg.sender][dst] = badd(_allowance[msg.sender][dst], amt); emit Approval(msg.sender, dst, _allowance[msg.sender][dst]); return true; } function decreaseApproval(address dst, uint amt) external returns (bool) { uint oldValue = _allowance[msg.sender][dst]; if (amt > oldValue) { _allowance[msg.sender][dst] = 0; } else { _allowance[msg.sender][dst] = bsub(oldValue, amt); } emit Approval(msg.sender, dst, _allowance[msg.sender][dst]); return true; } function transfer(address dst, uint amt) external returns (bool) { _move(msg.sender, dst, amt); return true; } function transferFrom(address src, address dst, uint amt) external returns (bool) { require(msg.sender == src || amt <= _allowance[src][msg.sender]); _move(src, dst, amt); if (msg.sender != src && _allowance[src][msg.sender] != uint256(-1)) { _allowance[src][msg.sender] = bsub(_allowance[src][msg.sender], amt); emit Approval(msg.sender, dst, _allowance[src][msg.sender]); } return true; } } contract FEGstakeV2 is Owned, ReentrancyGuard, WhitelistAdminRole, FNum, FTokenBase, FToken{ using SafeMath for uint256; address public FEG = 0x389999216860AB8E0175387A0c90E5c52522C945; address public fETH = 0xf786c34106762Ab4Eeb45a51B42a62470E9D5332; address public USDT = 0x979838c9C16FD365C9fE028B0bEa49B1750d86e9; address public TRY = 0xc12eCeE46ed65D970EE5C899FCC7AE133AfF9b03; address public FETP = 0xa40462266dC28dB1d570FC8F8a0F4B72B8618f7a; address public BTC = 0xe3cDB92b094a3BeF3f16103b53bECfb17A3558ad; address public poolShares = address(this); address public regrewardContract; //Signs The Checks bool public live = false; bool public perform = false; //if true then distribution of rewards from the pool to stakers via the withdraw function is enabled bool public perform2 = true; //if true then distribution of TX rewards from unclaimed 1 and 2 wrap's will distribute to stakers bool public perform3 = true; //if true then distribution of TX rewards from unclaimed 3rd wrap's will distribute to stakers uint256 public scailment = 20; // FEG has TX fee, deduct this fee to not break maths uint256 public totalDividends = 0; uint256 public must = 3e15; uint256 public scaleatize = 99; uint256 private scaledRemainder = 0; uint256 private scaling = uint256(10) ** 12; uint public round = 1; uint256 public totalDividends1 = 0; uint256 private scaledRemainder1 = 0; uint256 private scaling1 = uint256(10) ** 12; uint public round1 = 1; uint256 public totalDividends2 = 0; uint256 private scaledRemainder2 = 0; uint256 private scaling2 = uint256(10) ** 12; uint public round2 = 1; mapping(address => uint) public farmTime; // When you staked struct USER{ uint256 lastDividends; uint256 fromTotalDividend; uint round; uint256 remainder; uint256 lastDividends1; uint256 fromTotalDividend1; uint round1; uint256 remainder1; uint256 lastDividends2; uint256 fromTotalDividend2; uint round2; uint256 remainder2; bool initialized; bool activated; } address[] internal stakeholders; uint public scalerize = 98; uint256 public scaletor = 1e17; uint256 public scaletor1 = 20e18; uint256 public scaletor2 = 1e15; uint256 public totalWrap; // total unclaimed fETH rewards uint256 public totalWrap1; // total unclaimed usdt rewards uint256 public totalWrap2; // total unclaimed btc rewards uint256 public totalWrapRef = bsub(IERC20(fETH).balanceOf(address(this)), totalWrap); //total fETH reflections unclaimed uint256 public totalWrapRef1 = bsub(IERC20(USDT).balanceOf(address(this)), totalWrap1); //total usdt reflections unclaimed uint256 public totalWrapRef2 = bsub(IERC20(BTC).balanceOf(address(this)), totalWrap2); //total BTC reflections unclaimed mapping(address => USER) stakers; mapping (uint => uint256) public payouts; // keeps record of each payout mapping (uint => uint256) public payouts1; // keeps record of each payout mapping (uint => uint256) public payouts2; // keeps record of each payout FEGex2 fegexpair; event STAKED(address staker, uint256 tokens); event ACTIVATED(address staker, uint256 cost); event START(address staker, uint256 tokens); event EARNED(address staker, uint256 tokens); event UNSTAKED(address staker, uint256 tokens); event PAYOUT(uint256 round, uint256 tokens, address sender); event PAYOUT1(uint256 round, uint256 tokens, address sender); event PAYOUT2(uint256 round, uint256 tokens, address sender); event CLAIMEDREWARD(address staker, uint256 reward); event CLAIMEDREWARD1(address staker, uint256 reward); event CLAIMEDREWARD2(address staker, uint256 reward); constructor(){ fegexpair = FEGex2(FETP); } receive() external payable { } function changeFEGExPair(FEGex2 _fegexpair, address addy) external onlyOwner{ // Incase FEGex updates in future require(address(_fegexpair) != address(0), "setting 0 to contract"); fegexpair = _fegexpair; FETP = addy; } function changeTRY(address _try) external onlyOwner{ // Incase TRY updates in future TRY = _try; } function changeScalerize(uint _sca) public onlyOwner{ require(_sca != 0, "You cannot turn off"); scalerize = _sca; } function changeScalatize(uint _scm) public onlyOwner { require(_scm != 0, "You cannot turn off"); scaleatize = _scm; } function isStakeholder(address _address) public view returns(bool) { if(stakers[_address].initialized) return true; else return false; } function addStakeholder(address _stakeholder) internal { (bool _isStakeholder) = isStakeholder(_stakeholder); if(!_isStakeholder) { farmTime[msg.sender] = block.timestamp; stakers[_stakeholder].initialized = true; } } // ------------------------------------------------------------------------ // Token holders can stake their tokens using this function // @param tokens number of tokens to stake // ------------------------------------------------------------------------ function calcPoolInGivenSingleOut( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint tokenAmountOut, uint swapFee ) public pure returns (uint poolAmountIn) { uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); uint zar = bmul(bsub(BASE, normalizedWeight), swapFee); uint tokenAmountOutBeforeSwapFee = bdiv(tokenAmountOut, bsub(BASE, zar)); uint newTokenBalanceOut = bsub(tokenBalanceOut, tokenAmountOutBeforeSwapFee); uint tokenOutRatio = bdiv(newTokenBalanceOut, tokenBalanceOut); uint poolRatio = bpow(tokenOutRatio, normalizedWeight); uint newPoolSupply = bmul(poolRatio, poolSupply); uint poolAmountInAfterExitFee = bsub(poolSupply, newPoolSupply); poolAmountIn = bdiv(poolAmountInAfterExitFee, bsub(BASE, 0)); return (poolAmountIn); } function calcSingleOutGivenPoolIn( uint tokenBalanceOut, uint tokenWeightOut, uint poolSupply, uint totalWeight, uint poolAmountIn, uint swapFee ) public pure returns (uint tokenAmountOut) { uint normalizedWeight = bdiv(tokenWeightOut, totalWeight); uint poolAmountInAfterExitFee = bmul(poolAmountIn, bsub(BASE, 0)); uint newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee); uint poolRatio = bdiv(newPoolSupply, poolSupply); uint tokenOutRatio = bpow(poolRatio, bdiv(BASE, normalizedWeight)); uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut); uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut); uint zaz = bmul(bsub(BASE, normalizedWeight), swapFee); tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BASE, zaz)); return tokenAmountOut; } function calcPoolOutGivenSingleIn( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint tokenAmountIn, uint swapFee ) public pure returns (uint poolAmountOut) { uint normalizedWeight = bdiv(tokenWeightIn, totalWeight); uint zaz = bmul(bsub(BASE, normalizedWeight), swapFee); uint tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BASE, zaz)); uint newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee); uint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn); uint poolRatio = bpow(tokenInRatio, normalizedWeight); uint newPoolSupply = bmul(poolRatio, poolSupply); poolAmountOut = bsub(newPoolSupply, poolSupply); return (poolAmountOut); } function calcOutGivenIn( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountIn, uint swapFee ) public pure returns (uint tokenAmountOut, uint tokenInFee) { uint weightRatio = bdiv(tokenWeightIn, tokenWeightOut); uint adjustedIn = bsub(BASE, swapFee); adjustedIn = bmul(tokenAmountIn, adjustedIn); uint y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn)); uint foo = bpow(y, weightRatio); uint bar = bsub(BASE, foo); tokenAmountOut = bmul(tokenBalanceOut, bar); tokenInFee = bsub(tokenAmountIn, adjustedIn); return (tokenAmountOut, tokenInFee); } function calcInGivenOut( uint tokenBalanceIn, uint tokenWeightIn, uint tokenBalanceOut, uint tokenWeightOut, uint tokenAmountOut, uint swapFee ) public pure returns (uint tokenAmountIn) { uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn); uint diff = bsub(tokenBalanceOut, tokenAmountOut); uint y = bdiv(tokenBalanceOut, diff); uint foo = bpow(y, weightRatio); foo = bsub(foo, BASE); foo = bmul(tokenBalanceIn, foo); tokenAmountIn = bsub(BASE, swapFee); tokenAmountIn = bdiv(foo, tokenAmountIn); return (tokenAmountIn); } function activateUserStaking() public payable{ // Activation of FEGstake costs 0.02 fETH which is automatically refunded to your wallet in the form of TRY. require(msg.value == must, "You must deposit the right amount to activate"); fegexpair.BUY{value: msg.value }(msg.sender, 100); stakers[msg.sender].activated = true; emit ACTIVATED(msg.sender, msg.value); } function isActivated(address staker) public view returns(bool){ if(stakers[staker].activated) return true; else return false; } function Start(uint256 tokens) public onlyOwner returns(uint poolAmountOut){ require(live == false, "Can only use once"); require(IERC20(FEG).transferFrom(msg.sender, address(this), tokens), "Tokens cannot be transferred from user for locking"); uint256 transferTxFee = (onePercent(tokens).mul(scailment)).div(10); uint256 tokensToStake = (tokens.sub(transferTxFee)); addStakeholder(msg.sender); _mint(tokensToStake); live = true; IERC20(poolShares).transfer(msg.sender, tokensToStake); IERC20(address(fETH)).approve(address(FETP), 1000000000000000000000e18); emit START(msg.sender, tokensToStake); return poolAmountOut; } function STAKE(uint256 tokens) public returns(uint poolAmountOut){ require(IERC20(FEG).balanceOf(msg.sender) >= tokens, "You do not have enough FEG"); require(stakers[msg.sender].activated == true); require(live == true); uint256 transferTxFee = (onePercent(tokens).mul(scailment)).div(10); uint256 tokensToStake = (tokens.sub(transferTxFee)); uint256 totalFEG = IERC20(FEG).balanceOf(address(this)); addStakeholder(msg.sender); // add pending rewards to remainder to be claimed by user later, if there is any existing stake uint256 owing = pendingReward(msg.sender); stakers[msg.sender].remainder += owing; stakers[msg.sender].lastDividends = owing; stakers[msg.sender].fromTotalDividend = totalDividends; stakers[msg.sender].round = round; uint256 owing1 = pendingReward1(msg.sender); stakers[msg.sender].remainder1 += owing1; stakers[msg.sender].lastDividends1 = owing1; stakers[msg.sender].fromTotalDividend1 = totalDividends1; stakers[msg.sender].round1 = round1; uint256 owing2 = pendingReward2(msg.sender); stakers[msg.sender].remainder2 += owing2; stakers[msg.sender].lastDividends2 = owing2; stakers[msg.sender].fromTotalDividend2 = totalDividends2; stakers[msg.sender].round2 = round2; poolAmountOut = calcPoolOutGivenSingleIn( totalFEG, bmul(BASE, 25), _totalSupply, bmul(BASE, 25), tokensToStake, 0 ); require(IERC20(FEG).transferFrom(msg.sender, address(this), tokens), "Tokens cannot be transferred from user for locking"); _mint(poolAmountOut); IERC20(poolShares).transfer(msg.sender, poolAmountOut); emit STAKED(msg.sender, tokens); return poolAmountOut; } // ------------------------------------------------------------------------ // Owners can send the funds to be distributed to stakers using this function // @param tokens number of tokens to distribute // ------------------------------------------------------------------------ function ADDFUNDS1(uint256 tokens) public onlyWhitelistAdmin{ require(IERC20(fETH).transferFrom(msg.sender, address(this), tokens), "Tokens cannot be transferred from funder account"); uint256 tokens_ = bmul(tokens, bdiv(99, 100)); totalWrap = badd(totalWrap, tokens_); _addPayout(tokens_); } function ADDFUNDS2(uint256 tokens) public onlyWhitelistAdmin{ require(IERC20(USDT).transferFrom(msg.sender, address(this), tokens), "Tokens cannot be transferred from funder account"); uint256 tokens_ = bmul(tokens, bdiv(99, 100)); totalWrap1 = badd(totalWrap1, tokens_); _addPayout1(tokens_); } function ADDFUNDS3(uint256 tokens) public onlyWhitelistAdmin{ require(IERC20(BTC).transferFrom(msg.sender, address(this), tokens), "Tokens cannot be transferred from funder account"); uint256 tokens_ = bmul(tokens, bdiv(99, 100)); totalWrap2 = badd(totalWrap2, tokens_); _addPayout2(tokens_); } // ------------------------------------------------------------------------ // Private function to register payouts // ------------------------------------------------------------------------ function _addPayout(uint256 tokens_) private { // divide the funds among the currently staked tokens // scale the deposit and add the previous remainder uint256 totalShares = _totalSupply; uint256 available = (tokens_.mul(scaling)).add(scaledRemainder); uint256 dividendPerToken = available.div(totalShares); scaledRemainder = available.mod(totalShares); totalDividends = totalDividends.add(dividendPerToken); payouts[round] = payouts[round - 1].add(dividendPerToken); emit PAYOUT(round, tokens_, msg.sender); round++; } function _addPayout1(uint256 tokens_1) private{ // divide the funds among the currently staked tokens // scale the deposit and add the previous remainder uint256 totalShares = _totalSupply; uint256 available = (tokens_1.mul(scaling)).add(scaledRemainder1); uint256 dividendPerToken = available.div(totalShares); scaledRemainder1 = available.mod(totalShares); totalDividends1 = totalDividends1.add(dividendPerToken); payouts1[round1] = payouts1[round1 - 1].add(dividendPerToken); emit PAYOUT1(round1, tokens_1, msg.sender); round1++; } function _addPayout2(uint256 tokens_2) private{ // divide the funds among the currently staked tokens // scale the deposit and add the previous remainder uint256 totalShares = _totalSupply; uint256 available = (tokens_2.mul(scaling)).add(scaledRemainder2); uint256 dividendPerToken = available.div(totalShares); scaledRemainder2 = available.mod(totalShares); totalDividends2 = totalDividends2.add(dividendPerToken); payouts2[round2] = payouts2[round2 - 1].add(dividendPerToken); emit PAYOUT2(round2, tokens_2, msg.sender); round2++; } // ------------------------------------------------------------------------ // Stakers can claim their pending rewards using this function // ------------------------------------------------------------------------ function CLAIMREWARD() public nonReentrant{ uint256 owing = pendingReward(msg.sender); if(owing > 0){ owing = owing.add(stakers[msg.sender].remainder); stakers[msg.sender].remainder = 0; require(IERC20(fETH).transfer(msg.sender,owing), "ERROR: error in sending reward from contract"); emit CLAIMEDREWARD(msg.sender, owing); totalWrap = bsub(totalWrap, owing); stakers[msg.sender].lastDividends = owing; // unscaled stakers[msg.sender].round = round; // update the round stakers[msg.sender].fromTotalDividend = totalDividends; // scaled } } function CLAIMREWARD1() public nonReentrant { uint256 owing1 = pendingReward1(msg.sender); if(owing1 > 0){ owing1 = owing1.add(stakers[msg.sender].remainder1); stakers[msg.sender].remainder1 = 0; require(IERC20(USDT).transfer(msg.sender,owing1), "ERROR: error in sending reward from contract"); emit CLAIMEDREWARD1(msg.sender, owing1); totalWrap1 = bsub(totalWrap1, owing1); stakers[msg.sender].lastDividends1 = owing1; // unscaled stakers[msg.sender].round1 = round1; // update the round stakers[msg.sender].fromTotalDividend1 = totalDividends1; // scaled } } function CLAIMREWARD2() public nonReentrant { uint256 owing2 = pendingReward2(msg.sender); if(owing2 > 0){ owing2 = owing2.add(stakers[msg.sender].remainder2); stakers[msg.sender].remainder2 = 0; require(IERC20(BTC).transfer(msg.sender, owing2), "ERROR: error in sending reward from contract"); emit CLAIMEDREWARD2(msg.sender, owing2); totalWrap2 = bsub(totalWrap2, owing2); stakers[msg.sender].lastDividends2 = owing2; // unscaled stakers[msg.sender].round2 = round2; // update the round stakers[msg.sender].fromTotalDividend2 = totalDividends2; // scaled } } function CLAIMALLREWARD() public { distribute12(); CLAIMREWARD(); CLAIMREWARD1(); if(perform3==true){ distribute23(); CLAIMREWARD2(); } } // ------------------------------------------------------------------------ // Get the pending rewards of the staker // @param _staker the address of the staker // ------------------------------------------------------------------------ function pendingReward(address staker) private returns (uint256) { require(staker != address(0), "ERC20: sending to the zero address"); uint256 yourBase = IERC20(poolShares).balanceOf(msg.sender); uint stakersRound = stakers[staker].round; uint256 amount = ((totalDividends.sub(payouts[stakersRound - 1])).mul(yourBase)).div(scaling); stakers[staker].remainder += ((totalDividends.sub(payouts[stakersRound - 1])).mul(yourBase)) % scaling; return (bmul(amount, bdiv(scalerize, 100))); } function pendingReward1(address staker) private returns (uint256) { require(staker != address(0), "ERC20: sending to the zero address"); uint256 yourBase = IERC20(poolShares).balanceOf(msg.sender); uint stakersRound = stakers[staker].round1; uint256 amount1 = ((totalDividends1.sub(payouts1[stakersRound - 1])).mul(yourBase)).div(scaling); stakers[staker].remainder1 += ((totalDividends1.sub(payouts1[stakersRound - 1])).mul(yourBase)) % scaling; return (bmul(amount1, bdiv(scalerize, 100))); } function pendingReward2(address staker) private returns (uint256) { require(staker != address(0), "ERC20: sending to the zero address"); uint256 yourBase = IERC20(poolShares).balanceOf(msg.sender); uint stakersRound = stakers[staker].round2; uint256 amount2 = ((totalDividends2.sub(payouts2[stakersRound - 1])).mul(yourBase)).div(scaling); stakers[staker].remainder2 += ((totalDividends2.sub(payouts2[stakersRound - 1])).mul(yourBase)) % scaling; return (bmul(amount2, bdiv(scalerize, 100))); } function getPending1(address staker) public view returns(uint256 _pendingReward) { require(staker != address(0), "ERC20: sending to the zero address"); uint256 yourBase = IERC20(poolShares).balanceOf(staker); uint stakersRound = stakers[staker].round; uint256 amount = ((totalDividends.sub(payouts[stakersRound - 1])).mul(yourBase)).div(scaling); amount += ((totalDividends.sub(payouts[stakersRound - 1])).mul(yourBase)) % scaling; return (bmul(amount.add(stakers[staker].remainder), bdiv(scalerize, 100))); } function getPending2(address staker) public view returns(uint256 _pendingReward) { require(staker != address(0), "ERC20: sending to the zero address"); uint256 yourBase = IERC20(poolShares).balanceOf(staker); uint stakersRound = stakers[staker].round1; uint256 amount1 = ((totalDividends1.sub(payouts1[stakersRound - 1])).mul(yourBase)).div(scaling); amount1 += ((totalDividends1.sub(payouts1[stakersRound - 1])).mul(yourBase)) % scaling; return (bmul(amount1.add(stakers[staker].remainder1), bdiv(scalerize, 100))); } function getPending3(address staker) public view returns(uint256 _pendingReward) { require(staker != address(0), "ERC20: sending to the zero address"); uint256 yourBase = IERC20(poolShares).balanceOf(staker); uint stakersRound = stakers[staker].round2; uint256 amount2 = ((totalDividends2.sub(payouts2[stakersRound - 1])).mul(yourBase)).div(scaling); amount2 += ((totalDividends2.sub(payouts2[stakersRound - 1])).mul(yourBase)) % scaling; return (bmul(amount2.add(stakers[staker].remainder2), bdiv(scalerize, 100))); } // ------------------------------------------------------------------------ // Get the FEG balance of the token holder // @param user the address of the token holder // ------------------------------------------------------------------------ function userStakedFEG(address user) external view returns(uint256 StakedFEG){ require(user != address(0), "ERC20: sending to the zero address"); uint256 totalFEG = IERC20(FEG).balanceOf(address(this)); uint256 yourStakedFEG = calcSingleOutGivenPoolIn( totalFEG, bmul(BASE, 25), _totalSupply, bmul(BASE, 25), IERC20(poolShares).balanceOf(address(user)), 0 ); return yourStakedFEG; } // ------------------------------------------------------------------------ // Stakers can un stake the staked tokens using this function // @param tokens the number of tokens to withdraw // ------------------------------------------------------------------------ function WITHDRAW(address to, uint256 _tokens) external returns (uint tokenAmountOut) { uint256 totalFEG = IERC20(FEG).balanceOf(address(this)); require(stakers[msg.sender].activated == true); if(perform==true) { regreward(regrewardContract).distributeV2(); } CLAIMALLREWARD(); uint256 tokens = calcPoolInGivenSingleOut( totalFEG, bmul(BASE, 25), _totalSupply, bmul(BASE, 25), _tokens, 0 ); tokenAmountOut = calcSingleOutGivenPoolIn( totalFEG, bmul(BASE, 25), _totalSupply, bmul(BASE, 25), tokens, 0 ); require(tokens <= IERC20(poolShares).balanceOf(msg.sender), "You don't have enough FEG"); _pullPoolShare(tokens); _burn(tokens); require(IERC20(FEG).transfer(to, tokenAmountOut), "Error in un-staking tokens"); emit UNSTAKED(msg.sender, tokens); return tokenAmountOut; } function _pullPoolShare(uint amount) internal { bool xfer = IERC20(poolShares).transferFrom(msg.sender, address(this), amount); require(xfer, "ERR_ERC20_FALSE"); } // ------------------------------------------------------------------------ // Private function to calculate 1% percentage // ------------------------------------------------------------------------ function onePercent(uint256 _tokens) private pure returns (uint256){ uint256 roundValue = _tokens.ceil(100); uint onePercentofTokens = roundValue.mul(100).div(100 * 10**uint(2)); return onePercentofTokens; } function emergencySaveLostTokens(address to, address _token, uint256 _amt) public onlyOwner { require(_token != FEG, "Cannot remove users FEG"); require(_token != fETH, "Cannot remove users fETH"); require(_token != USDT, "Cannot remove users fUSDT"); require(_token != BTC, "Cannot remove users fBTC"); require(IERC20(_token).transfer(to, _amt), "Error in retrieving tokens"); payable(owner).transfer(address(this).balance); } function changeregrewardContract(address _regrewardContract) external onlyOwner{ require(address(_regrewardContract) != address(0), "setting 0 to contract"); regrewardContract = _regrewardContract; } function changePerform(bool _bool) external onlyOwner{ perform = _bool; } function changePerform2(bool _bool) external onlyOwner{ perform2 = _bool; } function changePerform3(bool _bool) external onlyOwner{ perform3 = _bool; } function changeMust(uint256 _must) external onlyOwner{ require(must !=0, "Cannot set to 0"); require(must <= 3e15, "Cannot set over 0.003 fETH"); must = _must; } function updateBase(address _BTC, address _ETH, address _USDT) external onlyOwner{ // Incase wraps ever update BTC = _BTC; fETH = _ETH; USDT = _USDT; } function distribute12() public { if (IERC20(fETH).balanceOf(address(this)) > badd(totalWrap, scaletor)) { distributeWrap1(); } if(IERC20(USDT).balanceOf(address(this)) > badd(totalWrap1, scaletor1)){ distributeWrap2(); } } function distribute23() public { if(perform3==true){ if(IERC20(BTC).balanceOf(address(this)) > badd(totalWrap2, scaletor2)){ distributeWrap3();} } } function changeScaletor(uint256 _sca, uint256 _sca1, uint256 _sca2) public onlyOwner { require(_sca !=0 && _sca1 !=0 && _sca2 !=0, "You cannot turn off"); require(_sca >= 5e17 && _sca1 >= 20e18 && _sca2 >= 1e15, "Must be over minimum"); scaletor = _sca; scaletor1 = _sca1; scaletor2 = _sca2; } function distributeWrap1() internal { uint256 wrapped = bsub(IERC20(fETH).balanceOf(address(this)), totalWrap); totalWrap = badd(totalWrap, wrapped); _addPayout(wrapped); } function distributeWrap2() internal { uint256 wrapped = bsub(IERC20(USDT).balanceOf(address(this)), totalWrap1); totalWrap1 = badd(totalWrap1, wrapped); _addPayout1(wrapped); } function distributeWrap3() internal { uint256 wrapped = bsub(IERC20(BTC).balanceOf(address(this)), totalWrap2); totalWrap2 = badd(totalWrap2, wrapped); _addPayout2(wrapped); } }
------------------------------------------------------------------------ Private function to calculate 1% percentage ------------------------------------------------------------------------
function onePercent(uint256 _tokens) private pure returns (uint256){ uint256 roundValue = _tokens.ceil(100); uint onePercentofTokens = roundValue.mul(100).div(100 * 10**uint(2)); return onePercentofTokens; }
881,710
./full_match/5/0xC18fCDaf974a11e3DA66158027Dcda318ED81d6d/sources/contracts/CrowdFunding.sol
PAYABLE RETURNS TWO DIFFERENT THINGS WE ARE ONLY ACCESSING ONE FOR NOW SO WE PUT THE COMMA
function donateToCampaign(uint256 _id) public payable { uint256 amount = msg.value; Campaign storage campaign = campaigns[_id]; campaign.donators.push(msg.sender); campaign.donations.push(amount); if(sent){ campaign.amountCollected = campaign.amountCollected + amount; } }
1,922,088
./full_match/5/0xDb80166478D50EDEFc4dD72c304d44D270c6b494/sources/contracts/core/libs/attestations-registry/AttestationsRegistryConfigLogic.sol
Returns whether a specific issuer is authorized or not to record in a specific attestations collection issuer Issuer to be checked collectionId Collection Id for which the issuer will be checked/
function isAuthorized(address issuer, uint256 collectionId) external view returns (bool) { return _isAuthorized(issuer, collectionId); }
1,931,167
pragma solidity ^0.4.24; // File: openzeppelin-zos/contracts/introspection/ERC165.sol /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface ERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceId The interface identifier, as specified in ERC-165 * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas. */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // File: openzeppelin-zos/contracts/token/ERC721/ERC721Basic.sol /** * @title ERC721 Non-Fungible Token Standard basic interface * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Basic is ERC165 { 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) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function exists(uint256 _tokenId) public view returns (bool _exists); function approve(address _to, uint256 _tokenId) public; function getApproved(uint256 _tokenId) public view returns (address _operator); function setApprovalForAll(address _operator, bool _approved) public; function isApprovedForAll(address _owner, address _operator) public view returns (bool); function transferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) public; function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public; } // File: openzeppelin-zos/contracts/token/ERC721/ERC721.sol /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Enumerable is ERC721Basic { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256 _tokenId); function tokenByIndex(uint256 _index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Metadata is ERC721Basic { function name() external view returns (string _name); function symbol() external view returns (string _symbol); function tokenURI(uint256 _tokenId) public view returns (string); } /** * @title ERC-721 Non-Fungible Token Standard, full implementation interface * @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { } // File: openzeppelin-zos/contracts/token/ERC721/ERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract ERC721Receiver { /** * @dev Magic value to be returned upon successful reception of an NFT * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` */ bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the contract address is always the message sender. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _tokenId The NFT identifier which is being transfered * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public returns(bytes4); } // File: openzeppelin-zos/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } // File: openzeppelin-zos/contracts/AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly return size > 0; } } // File: openzeppelin-zos/contracts/introspection/ERC165Support.sol /** * @title ERC165Support * @dev Implements ERC165 returning true for ERC165 interface identifier */ contract ERC165Support is ERC165 { bytes4 internal constant InterfaceId_ERC165 = 0x01ffc9a7; /** * 0x01ffc9a7 === * bytes4(keccak256('supportsInterface(bytes4)')) */ function supportsInterface(bytes4 _interfaceId) external view returns (bool) { return _supportsInterface(_interfaceId); } function _supportsInterface(bytes4 _interfaceId) internal view returns (bool) { return _interfaceId == InterfaceId_ERC165; } } // File: openzeppelin-zos/contracts/token/ERC721/ERC721BasicToken.sol /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721BasicToken is ERC165Support, ERC721Basic { bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd; /* * 0x80ac58cd === * bytes4(keccak256('balanceOf(address)')) ^ * bytes4(keccak256('ownerOf(uint256)')) ^ * bytes4(keccak256('approve(address,uint256)')) ^ * bytes4(keccak256('getApproved(uint256)')) ^ * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ * bytes4(keccak256('isApprovedForAll(address,address)')) ^ * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) */ bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79; /* * 0x4f558e79 === * bytes4(keccak256('exists(uint256)')) */ using SafeMath for uint256; using AddressUtils for address; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` bytes4 private constant ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) internal tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) internal tokenApprovals; // Mapping from owner to number of owned token mapping (address => uint256) internal ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) internal operatorApprovals; /** * @dev Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator * @param _tokenId uint256 ID of the token to validate */ modifier canTransfer(uint256 _tokenId) { require(isApprovedOrOwner(msg.sender, _tokenId)); _; } function _supportsInterface(bytes4 _interfaceId) internal view returns (bool) { return super._supportsInterface(_interfaceId) || _interfaceId == InterfaceId_ERC721 || _interfaceId == InterfaceId_ERC721Exists; } /** * @dev Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokensCount[_owner]; } /** * @dev Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @dev Returns whether the specified token exists * @param _tokenId uint256 ID of the token to query the existence of * @return whether the token exists */ function exists(uint256 _tokenId) public view returns (bool) { address owner = tokenOwner[_tokenId]; return owner != address(0); } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) public { address owner = ownerOf(_tokenId); require(_to != owner); require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); tokenApprovals[_tokenId] = _to; emit Approval(owner, _to, _tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf * @param _to operator address to set the approval * @param _approved representing the status of the approval to be set */ function setApprovalForAll(address _to, bool _approved) public { require(_to != msg.sender); operatorApprovals[msg.sender][_to] = _approved; emit ApprovalForAll(msg.sender, _to, _approved); } /** * @dev Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll( address _owner, address _operator ) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @dev Transfers the ownership of a given token ID to another address * Usage of this method is discouraged, use `safeTransferFrom` whenever possible * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { require(_from != address(0)); require(_to != address(0)); clearApproval(_from, _tokenId); removeTokenFrom(_from, _tokenId); addTokenTo(_to, _tokenId); emit Transfer(_from, _to, _tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public canTransfer(_tokenId) { // solium-disable-next-line arg-overflow safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg sender to be the owner, approved, or operator * @param _from current owner of the token * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public canTransfer(_tokenId) { transferFrom(_from, _to, _tokenId); // solium-disable-next-line arg-overflow require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); } /** * @dev Returns whether the given spender can transfer a given token ID * @param _spender address of the spender to query * @param _tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function isApprovedOrOwner( address _spender, uint256 _tokenId ) internal view returns (bool) { address owner = ownerOf(_tokenId); // Disable solium check because of // https://github.com/duaraghav8/Solium/issues/175 // solium-disable-next-line operator-whitespace return ( _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender) ); } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); addTokenTo(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { clearApproval(_owner, _tokenId); removeTokenFrom(_owner, _tokenId); emit Transfer(_owner, address(0), _tokenId); } /** * @dev Internal function to clear current approval of a given token ID * Reverts if the given address is not indeed the owner of the token * @param _owner owner of the token * @param _tokenId uint256 ID of the token to be transferred */ function clearApproval(address _owner, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _owner); if (tokenApprovals[_tokenId] != address(0)) { tokenApprovals[_tokenId] = address(0); } } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; ownedTokensCount[_to] = ownedTokensCount[_to].add(1); } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { require(ownerOf(_tokenId) == _from); ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); tokenOwner[_tokenId] = address(0); } /** * @dev Internal function to invoke `onERC721Received` on a target address * The call is not executed if the target address is not a contract * @param _from address representing the previous owner of the given token ID * @param _to target address that will receive the tokens * @param _tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return whether the call correctly returned the expected magic value */ function checkAndCallSafeTransfer( address _from, address _to, uint256 _tokenId, bytes _data ) internal returns (bool) { if (!_to.isContract()) { return true; } bytes4 retval = ERC721Receiver(_to).onERC721Received( msg.sender, _from, _tokenId, _data); return (retval == ERC721_RECEIVED); } } // File: zos-lib/contracts/migrations/Migratable.sol /** * @title Migratable * Helper contract to support intialization and migration schemes between * different implementations of a contract in the context of upgradeability. * To use it, replace the constructor with a function that has the * `isInitializer` modifier starting with `"0"` as `migrationId`. * When you want to apply some migration code during an upgrade, increase * the `migrationId`. Or, if the migration code must be applied only after * another migration has been already applied, use the `isMigration` modifier. * This helper supports multiple inheritance. * WARNING: It is the developer's responsibility to ensure that migrations are * applied in a correct order, or that they are run at all. * See `Initializable` for a simpler version. */ contract Migratable { /** * @dev Emitted when the contract applies a migration. * @param contractName Name of the Contract. * @param migrationId Identifier of the migration applied. */ event Migrated(string contractName, string migrationId); /** * @dev Mapping of the already applied migrations. * (contractName => (migrationId => bool)) */ mapping (string => mapping (string => bool)) internal migrated; /** * @dev Internal migration id used to specify that a contract has already been initialized. */ string constant private INITIALIZED_ID = "initialized"; /** * @dev Modifier to use in the initialization function of a contract. * @param contractName Name of the contract. * @param migrationId Identifier of the migration. */ modifier isInitializer(string contractName, string migrationId) { validateMigrationIsPending(contractName, INITIALIZED_ID); validateMigrationIsPending(contractName, migrationId); _; emit Migrated(contractName, migrationId); migrated[contractName][migrationId] = true; migrated[contractName][INITIALIZED_ID] = true; } /** * @dev Modifier to use in the migration of a contract. * @param contractName Name of the contract. * @param requiredMigrationId Identifier of the previous migration, required * to apply new one. * @param newMigrationId Identifier of the new migration to be applied. */ modifier isMigration(string contractName, string requiredMigrationId, string newMigrationId) { require(isMigrated(contractName, requiredMigrationId), "Prerequisite migration ID has not been run yet"); validateMigrationIsPending(contractName, newMigrationId); _; emit Migrated(contractName, newMigrationId); migrated[contractName][newMigrationId] = true; } /** * @dev Returns true if the contract migration was applied. * @param contractName Name of the contract. * @param migrationId Identifier of the migration. * @return true if the contract migration was applied, false otherwise. */ function isMigrated(string contractName, string migrationId) public view returns(bool) { return migrated[contractName][migrationId]; } /** * @dev Initializer that marks the contract as initialized. * It is important to run this if you had deployed a previous version of a Migratable contract. * For more information see https://github.com/zeppelinos/zos-lib/issues/158. */ function initialize() isInitializer("Migratable", "1.2.1") public { } /** * @dev Reverts if the requested migration was already executed. * @param contractName Name of the contract. * @param migrationId Identifier of the migration. */ function validateMigrationIsPending(string contractName, string migrationId) private view { require(!isMigrated(contractName, migrationId), "Requested target migration ID has already been run"); } } // File: openzeppelin-zos/contracts/token/ERC721/ERC721Token.sol /** * @title Full ERC721 Token * This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology * @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md */ contract ERC721Token is Migratable, ERC165Support, ERC721BasicToken, ERC721 { bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63; /** * 0x780e9d63 === * bytes4(keccak256('totalSupply()')) ^ * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ * bytes4(keccak256('tokenByIndex(uint256)')) */ bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; /** * 0x5b5e139f === * bytes4(keccak256('name()')) ^ * bytes4(keccak256('symbol()')) ^ * bytes4(keccak256('tokenURI(uint256)')) */ // Token name string internal name_; // Token symbol string internal symbol_; // Mapping from owner to list of owned token IDs mapping(address => uint256[]) internal ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) internal ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] internal allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) internal allTokensIndex; // Optional mapping for token URIs mapping(uint256 => string) internal tokenURIs; /** * @dev Constructor function */ function initialize(string _name, string _symbol) public isInitializer("ERC721Token", "1.9.0") { name_ = _name; symbol_ = _symbol; } function _supportsInterface(bytes4 _interfaceId) internal view returns (bool) { return super._supportsInterface(_interfaceId) || _interfaceId == InterfaceId_ERC721Enumerable || _interfaceId == InterfaceId_ERC721Metadata; } /** * @dev Gets the token name * @return string representing the token name */ function name() external view returns (string) { return name_; } /** * @dev Gets the token symbol * @return string representing the token symbol */ function symbol() external view returns (string) { return symbol_; } /** * @dev Returns an URI for a given token ID * Throws if the token ID does not exist. May return an empty string. * @param _tokenId uint256 ID of the token to query */ function tokenURI(uint256 _tokenId) public view returns (string) { require(exists(_tokenId)); return tokenURIs[_tokenId]; } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner * @param _owner address owning the tokens list to be accessed * @param _index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) public view returns (uint256) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @dev Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens * @param _index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 _index) public view returns (uint256) { require(_index < totalSupply()); return allTokens[_index]; } /** * @dev Internal function to set the token URI for a given token * Reverts if the token ID does not exist * @param _tokenId uint256 ID of the token to set its URI * @param _uri string URI to assign */ function _setTokenURI(uint256 _tokenId, string _uri) internal { require(exists(_tokenId)); tokenURIs[_tokenId] = _uri; } /** * @dev Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function addTokenTo(address _to, uint256 _tokenId) internal { super.addTokenTo(_to, _tokenId); uint256 length = ownedTokens[_to].length; ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; } /** * @dev Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function removeTokenFrom(address _from, uint256 _tokenId) internal { super.removeTokenFrom(_from, _tokenId); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; } /** * @dev Internal function to mint a new token * Reverts if the given token ID already exists * @param _to address the beneficiary that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { super._mint(_to, _tokenId); allTokensIndex[_tokenId] = allTokens.length; allTokens.push(_tokenId); } /** * @dev Internal function to burn a specific token * Reverts if the token does not exist * @param _owner owner of the token to burn * @param _tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address _owner, uint256 _tokenId) internal { super._burn(_owner, _tokenId); // Clear metadata (if any) if (bytes(tokenURIs[_tokenId]).length != 0) { delete tokenURIs[_tokenId]; } // Reorg all tokens array uint256 tokenIndex = allTokensIndex[_tokenId]; uint256 lastTokenIndex = allTokens.length.sub(1); uint256 lastToken = allTokens[lastTokenIndex]; allTokens[tokenIndex] = lastToken; allTokens[lastTokenIndex] = 0; allTokens.length--; allTokensIndex[_tokenId] = 0; allTokensIndex[lastToken] = tokenIndex; } } // File: openzeppelin-zos/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable is Migratable { 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 initialize(address _sender) public isInitializer("Ownable", "1.9.0") { owner = _sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } // File: contracts/estate/IEstateRegistry.sol contract IEstateRegistry { function mint(address to, string metadata) external returns (uint256); function ownerOf(uint256 _tokenId) public view returns (address _owner); // from ERC721 // Events event CreateEstate( address indexed _owner, uint256 indexed _estateId, string _data ); event AddLand( uint256 indexed _estateId, uint256 indexed _landId ); event RemoveLand( uint256 indexed _estateId, uint256 indexed _landId, address indexed _destinatary ); event Update( uint256 indexed _assetId, address indexed _holder, address indexed _operator, string _data ); event UpdateOperator( uint256 indexed _estateId, address indexed _operator ); event SetLANDRegistry( address indexed _registry ); } // File: contracts/estate/EstateStorage.sol contract LANDRegistry { function decodeTokenId(uint value) external pure returns (int, int); function updateLandData(int x, int y, string data) external; function ping() public; function ownerOf(uint256 tokenId) public returns (address); function safeTransferFrom(address, address, uint256) public; } contract EstateStorage { bytes4 internal constant InterfaceId_GetMetadata = bytes4(keccak256("getMetadata(uint256)")); bytes4 internal constant InterfaceId_VerifyFingerprint = bytes4( keccak256("verifyFingerprint(uint256,bytes)") ); LANDRegistry public registry; // From Estate to list of owned LAND ids (LANDs) mapping(uint256 => uint256[]) public estateLandIds; // From LAND id (LAND) to its owner Estate id mapping(uint256 => uint256) public landIdEstate; // From Estate id to mapping of LAND id to index on the array above (estateLandIds) mapping(uint256 => mapping(uint256 => uint256)) public estateLandIndex; // Metadata of the Estate mapping(uint256 => string) internal estateData; // Operator of the Estate mapping (uint256 => address) internal updateOperator; } // File: contracts/estate/EstateRegistry.sol /** * @title ERC721 registry of every minted Estate and their owned LANDs * @dev Usings we are inheriting and depending on: * From ERC721Token: * - using SafeMath for uint256; * - using AddressUtils for address; */ // solium-disable-next-line max-len contract EstateRegistry is Migratable, IEstateRegistry, ERC721Token, ERC721Receiver, Ownable, EstateStorage { modifier canTransfer(uint256 estateId) { require(isApprovedOrOwner(msg.sender, estateId), "Only owner or operator can transfer"); _; } modifier onlyRegistry() { require(msg.sender == address(registry), "Only the registry can make this operation"); _; } modifier onlyUpdateAuthorized(uint256 estateId) { require(_isUpdateAuthorized(msg.sender, estateId), "Unauthorized user"); _; } /** * @dev Mint a new Estate with some metadata * @param to The address that will own the minted token * @param metadata Set an initial metadata * @return An uint256 representing the new token id */ function mint(address to, string metadata) external onlyRegistry returns (uint256) { return _mintEstate(to, metadata); } /** * @notice Transfer a LAND owned by an Estate to a new owner * @param estateId Current owner of the token * @param landId LAND to be transfered * @param destinatary New owner */ function transferLand( uint256 estateId, uint256 landId, address destinatary ) external canTransfer(estateId) { return _transferLand(estateId, landId, destinatary); } /** * @notice Transfer many tokens owned by an Estate to a new owner * @param estateId Current owner of the token * @param landIds LANDs to be transfered * @param destinatary New owner */ function transferManyLands( uint256 estateId, uint256[] landIds, address destinatary ) external canTransfer(estateId) { uint length = landIds.length; for (uint i = 0; i < length; i++) { _transferLand(estateId, landIds[i], destinatary); } } /** * @notice Get the Estate id for a given LAND id * @dev This information also lives on estateLandIds, * but it being a mapping you need to know the Estate id beforehand. * @param landId LAND to search * @return The corresponding Estate id */ function getLandEstateId(uint256 landId) external view returns (uint256) { return landIdEstate[landId]; } function setLANDRegistry(address _registry) external onlyOwner { require(_registry.isContract(), "The LAND registry address should be a contract"); require(_registry != 0, "The LAND registry address should be valid"); registry = LANDRegistry(_registry); emit SetLANDRegistry(registry); } function ping() external { registry.ping(); } /** * @notice Return the amount of tokens for a given Estate * @param estateId Estate id to search * @return Tokens length */ function getEstateSize(uint256 estateId) external view returns (uint256) { return estateLandIds[estateId].length; } /** * @notice Update the metadata of an Estate * @dev Reverts if the Estate does not exist or the user is not authorized * @param estateId Estate id to update * @param metadata string metadata */ function updateMetadata( uint256 estateId, string metadata ) external onlyUpdateAuthorized(estateId) { _updateMetadata(estateId, metadata); emit Update( estateId, ownerOf(estateId), msg.sender, metadata ); } function getMetadata(uint256 estateId) external view returns (string) { return estateData[estateId]; } function setUpdateOperator(uint256 estateId, address operator) external canTransfer(estateId) { updateOperator[estateId] = operator; emit UpdateOperator(estateId, operator); } function isUpdateAuthorized(address operator, uint256 estateId) external view returns (bool) { return _isUpdateAuthorized(operator, estateId); } function initialize( string _name, string _symbol, address _registry ) public isInitializer("EstateRegistry", "0.0.2") { require(_registry != 0, "The registry should be a valid address"); ERC721Token.initialize(_name, _symbol); Ownable.initialize(msg.sender); registry = LANDRegistry(_registry); } /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safetransfer`. This function MAY throw to revert and reject the * transfer. Return of other than the magic value MUST result in the * transaction being reverted. * Note: the contract address is always the message sender. * @param _operator The address which called `safeTransferFrom` function * @param _from The address which previously owned the token * @param _tokenId The NFT identifier which is being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes _data ) public onlyRegistry returns (bytes4) { uint256 estateId = _bytesToUint(_data); _pushLandId(estateId, _tokenId); return ERC721_RECEIVED; } /** * @dev Creates a checksum of the contents of the Estate * @param estateId the estateId to be verified */ function getFingerprint(uint256 estateId) public view returns (bytes32 result) { result = keccak256(abi.encodePacked("estateId", estateId)); uint256 length = estateLandIds[estateId].length; for (uint i = 0; i < length; i++) { result ^= keccak256(abi.encodePacked(estateLandIds[estateId][i])); } return result; } /** * @dev Verifies a checksum of the contents of the Estate * @param estateId the estateid to be verified * @param fingerprint the user provided identification of the Estate contents */ function verifyFingerprint(uint256 estateId, bytes fingerprint) public view returns (bool) { return getFingerprint(estateId) == _bytesToBytes32(fingerprint); } /** * @dev Safely transfers the ownership of multiple Estate IDs to another address * @dev Delegates to safeTransferFrom for each transfer * @dev Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param estateIds uint256 array of IDs to be transferred */ function safeTransferManyFrom(address from, address to, uint256[] estateIds) public { safeTransferManyFrom( from, to, estateIds, "" ); } /** * @dev Safely transfers the ownership of multiple Estate IDs to another address * @dev Delegates to safeTransferFrom for each transfer * @dev Requires the msg sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param estateIds uint256 array of IDs to be transferred * @param data bytes data to send along with a safe transfer check */ function safeTransferManyFrom( address from, address to, uint256[] estateIds, bytes data ) public { for (uint i = 0; i < estateIds.length; i++) { safeTransferFrom( from, to, estateIds[i], data ); } } /** * @dev update LAND data owned by an Estate * @param estateId Estate * @param landId LAND to be updated * @param data string metadata */ function updateLandData(uint256 estateId, uint256 landId, string data) public { _updateLandData(estateId, landId, data); } /** * @dev update LANDs data owned by an Estate * @param estateId Estate id * @param landIds LANDs to be updated * @param data string metadata */ function updateManyLandData(uint256 estateId, uint256[] landIds, string data) public { uint length = landIds.length; for (uint i = 0; i < length; i++) { _updateLandData(estateId, landIds[i], data); } } // check the supported interfaces via ERC165 function _supportsInterface(bytes4 _interfaceId) internal view returns (bool) { // solium-disable-next-line operator-whitespace return super._supportsInterface(_interfaceId) || _interfaceId == InterfaceId_GetMetadata || _interfaceId == InterfaceId_VerifyFingerprint; } /** * @dev Internal function to mint a new Estate with some metadata * @param to The address that will own the minted token * @param metadata Set an initial metadata * @return An uint256 representing the new token id */ function _mintEstate(address to, string metadata) internal returns (uint256) { require(to != address(0), "You can not mint to an empty address"); uint256 estateId = _getNewEstateId(); _mint(to, estateId); _updateMetadata(estateId, metadata); emit CreateEstate(to, estateId, metadata); return estateId; } /** * @dev Internal function to update an Estate metadata * @dev Does not require the Estate to exist, for a public interface use `updateMetadata` * @param estateId Estate id to update * @param metadata string metadata */ function _updateMetadata(uint256 estateId, string metadata) internal { estateData[estateId] = metadata; } /** * @notice Return a new unique id * @dev It uses totalSupply to determine the next id * @return uint256 Representing the new Estate id */ function _getNewEstateId() internal view returns (uint256) { return totalSupply().add(1); } /** * @dev Appends a new LAND id to an Estate updating all related storage * @param estateId Estate where the LAND should go * @param landId Transfered LAND */ function _pushLandId(uint256 estateId, uint256 landId) internal { require(exists(estateId), "The Estate id should exist"); require(landIdEstate[landId] == 0, "The LAND is already owned by an Estate"); require(registry.ownerOf(landId) == address(this), "The EstateRegistry cannot manage the LAND"); estateLandIds[estateId].push(landId); landIdEstate[landId] = estateId; estateLandIndex[estateId][landId] = estateLandIds[estateId].length; emit AddLand(estateId, landId); } /** * @dev Removes a LAND from an Estate and transfers it to a new owner * @param estateId Current owner of the LAND * @param landId LAND to be transfered * @param destinatary New owner */ function _transferLand( uint256 estateId, uint256 landId, address destinatary ) internal { require(destinatary != address(0), "You can not transfer LAND to an empty address"); uint256[] storage landIds = estateLandIds[estateId]; mapping(uint256 => uint256) landIndex = estateLandIndex[estateId]; /** * Using 1-based indexing to be able to make this check */ require(landIndex[landId] != 0, "The LAND is not part of the Estate"); uint lastIndexInArray = landIds.length.sub(1); /** * Get the landIndex of this token in the landIds list */ uint indexInArray = landIndex[landId].sub(1); /** * Get the landId at the end of the landIds list */ uint tempTokenId = landIds[lastIndexInArray]; /** * Store the last token in the position previously occupied by landId */ landIndex[tempTokenId] = indexInArray.add(1); landIds[indexInArray] = tempTokenId; /** * Delete the landIds[last element] */ delete landIds[lastIndexInArray]; landIds.length = lastIndexInArray; /** * Drop this landId from both the landIndex and landId list */ landIndex[landId] = 0; /** * Drop this landId Estate */ landIdEstate[landId] = 0; registry.safeTransferFrom(this, destinatary, landId); emit RemoveLand(estateId, landId, destinatary); } function _isUpdateAuthorized(address operator, uint256 estateId) internal view returns (bool) { return isApprovedOrOwner(operator, estateId) || updateOperator[estateId] == operator; } function _bytesToUint(bytes b) internal pure returns (uint256) { return uint256(_bytesToBytes32(b)); } function _bytesToBytes32(bytes b) internal pure returns (bytes32) { bytes32 out; for (uint i = 0; i < b.length; i++) { out |= bytes32(b[i] & 0xFF) >> i.mul(8); } return out; } function _updateLandData( uint256 estateId, uint256 landId, string data ) internal onlyUpdateAuthorized(estateId) { require(landIdEstate[landId] == estateId, "The LAND is not part of the Estate"); int x; int y; (x, y) = registry.decodeTokenId(landId); registry.updateLandData(x, y, data); } }
check the supported interfaces via ERC165 solium-disable-next-line operator-whitespace
function _supportsInterface(bytes4 _interfaceId) internal view returns (bool) { return super._supportsInterface(_interfaceId) || _interfaceId == InterfaceId_GetMetadata || _interfaceId == InterfaceId_VerifyFingerprint; }
12,118,394
./partial_match/42/0x2E8fcdF765ec0AeE0693Aa2eA1ED70457F30080b/sources/LevelsVault.sol
Super admin can transfer its powers to another address
function newSuperAdmin(address newOwner) public virtual onlySuperAdmin { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit SuperAdminTransfered(_superAdmin, newOwner); _superAdmin = newOwner; }
3,307,901
pragma solidity 0.5.11; // optimization runs: 200, evm version: petersburg /** * @title DTokenInterface * @author 0age * @notice Interface for dTokens (in addition to the standard ERC20 interface). */ interface DTokenInterface { // Events bear similarity to Compound's supply-related events. event Mint(address minter, uint256 mintAmount, uint256 mintDTokens); event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemDTokens); event Accrue(uint256 dTokenExchangeRate, uint256 cTokenExchangeRate); event CollectSurplus(uint256 surplusAmount, uint256 surplusCTokens); // The block number and cToken + dToken exchange rates are updated on accrual. struct AccrualIndex { uint112 dTokenExchangeRate; uint112 cTokenExchangeRate; uint32 block; } // These external functions trigger accrual on the dToken and backing cToken. function mint(uint256 underlyingToSupply) external returns (uint256 dTokensMinted); function redeem(uint256 dTokensToBurn) external returns (uint256 underlyingReceived); function redeemUnderlying(uint256 underelyingToReceive) external returns (uint256 dTokensBurned); function pullSurplus() external returns (uint256 cTokenSurplus); // These external functions only trigger accrual on the dToken. function mintViaCToken(uint256 cTokensToSupply) external returns (uint256 dTokensMinted); function redeemToCToken(uint256 dTokensToBurn) external returns (uint256 cTokensReceived); function redeemUnderlyingToCToken(uint256 underlyingToReceive) external returns (uint256 dTokensBurned); function accrueInterest() external; function transferUnderlying( address recipient, uint256 underlyingEquivalentAmount ) external returns (bool success); function transferUnderlyingFrom( address sender, address recipient, uint256 underlyingEquivalentAmount ) external returns (bool success); // This function provides basic meta-tx support and does not trigger accrual. function modifyAllowanceViaMetaTransaction( address owner, address spender, uint256 value, bool increase, uint256 expiration, bytes32 salt, bytes calldata signatures ) external returns (bool success); // View and pure functions do not trigger accrual on the dToken or the cToken. function getMetaTransactionMessageHash( bytes4 functionSelector, bytes calldata arguments, uint256 expiration, bytes32 salt ) external view returns (bytes32 digest, bool valid); function totalSupplyUnderlying() external view returns (uint256); function balanceOfUnderlying(address account) external view returns (uint256 underlyingBalance); function exchangeRateCurrent() external view returns (uint256 dTokenExchangeRate); function supplyRatePerBlock() external view returns (uint256 dTokenInterestRate); function accrualBlockNumber() external view returns (uint256 blockNumber); function getSurplus() external view returns (uint256 cTokenSurplus); function getSurplusUnderlying() external view returns (uint256 underlyingSurplus); function getSpreadPerBlock() external view returns (uint256 rateSpread); function getVersion() external pure returns (uint256 version); function getCToken() external pure returns (address cToken); function getUnderlying() external pure returns (address underlying); } interface ERC20Interface { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); } interface ERC1271Interface { function isValidSignature( bytes calldata data, bytes calldata signature ) external view returns (bytes4 magicValue); } interface CTokenInterface { function mint(uint256 mintAmount) external returns (uint256 err); function redeem(uint256 redeemAmount) external returns (uint256 err); function redeemUnderlying(uint256 redeemAmount) external returns (uint256 err); function accrueInterest() external returns (uint256 err); function transfer(address recipient, uint256 value) external returns (bool); function transferFrom(address sender, address recipient, uint256 value) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function balanceOfUnderlying(address account) external returns (uint256 balance); function exchangeRateCurrent() external returns (uint256 exchangeRate); function getCash() external view returns (uint256); function totalSupply() external view returns (uint256 supply); function totalBorrows() external view returns (uint256 borrows); function totalReserves() external view returns (uint256 reserves); function interestRateModel() external view returns (address model); function reserveFactorMantissa() external view returns (uint256 factor); function supplyRatePerBlock() external view returns (uint256 rate); function exchangeRateStored() external view returns (uint256 rate); function accrualBlockNumber() external view returns (uint256 blockNumber); function balanceOf(address account) external view returns (uint256 balance); function allowance(address owner, address spender) external view returns (uint256); } interface CUSDCInterestRateModelInterface { function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256 err, uint256 borrowRate); } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } /** * @title DharmaTokenOverrides * @author 0age * @notice A collection of internal view and pure functions that should be * overridden by the ultimate Dharma Token implementation. */ contract DharmaTokenOverrides { /** * @notice Internal view function to get the current cToken exchange rate and * supply rate per block. This function is meant to be overridden by the * dToken that inherits this contract. * @return The current cToken exchange rate, or amount of underlying tokens * that are redeemable for each cToken, and the cToken supply rate per block * (with 18 decimal places added to each returned rate). */ function _getCurrentCTokenRates() internal view returns ( uint256 exchangeRate, uint256 supplyRate ); /** * @notice Internal pure function to supply the name of the underlying token. * @return The name of the underlying token. */ function _getUnderlyingName() internal pure returns (string memory underlyingName); /** * @notice Internal pure function to supply the address of the underlying * token. * @return The address of the underlying token. */ function _getUnderlying() internal pure returns (address underlying); /** * @notice Internal pure function to supply the symbol of the backing cToken. * @return The symbol of the backing cToken. */ function _getCTokenSymbol() internal pure returns (string memory cTokenSymbol); /** * @notice Internal pure function to supply the address of the backing cToken. * @return The address of the backing cToken. */ function _getCToken() internal pure returns (address cToken); /** * @notice Internal pure function to supply the name of the dToken. * @return The name of the dToken. */ function _getDTokenName() internal pure returns (string memory dTokenName); /** * @notice Internal pure function to supply the symbol of the dToken. * @return The symbol of the dToken. */ function _getDTokenSymbol() internal pure returns (string memory dTokenSymbol); /** * @notice Internal pure function to supply the address of the vault that * receives surplus cTokens whenever the surplus is pulled. * @return The address of the vault. */ function _getVault() internal pure returns (address vault); } /** * @title DharmaTokenHelpers * @author 0age * @notice A collection of constants and internal pure functions used by Dharma * Tokens. */ contract DharmaTokenHelpers is DharmaTokenOverrides { using SafeMath for uint256; uint8 internal constant _DECIMALS = 8; // matches cToken decimals uint256 internal constant _SCALING_FACTOR = 1e18; uint256 internal constant _SCALING_FACTOR_MINUS_ONE = 999999999999999999; uint256 internal constant _HALF_OF_SCALING_FACTOR = 5e17; uint256 internal constant _COMPOUND_SUCCESS = 0; uint256 internal constant _MAX_UINT_112 = 5192296858534827628530496329220095; /* solhint-disable separate-by-one-line-in-contract */ uint256 internal constant _MAX_UNMALLEABLE_S = ( 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0 ); /* solhint-enable separate-by-one-line-in-contract */ /** * @notice Internal pure function to determine if a call to Compound succeeded * and to revert, supplying the reason, if it failed. Failure can be caused by * a call that reverts, or by a call that does not revert but returns a * non-zero error code. * @param functionSelector bytes4 The function selector that was called. * @param ok bool A boolean representing whether the call returned or * reverted. * @param data bytes The data provided by the returned or reverted call. */ function _checkCompoundInteraction( bytes4 functionSelector, bool ok, bytes memory data ) internal pure { CTokenInterface cToken; if (ok) { if ( functionSelector == cToken.transfer.selector || functionSelector == cToken.transferFrom.selector ) { require( abi.decode(data, (bool)), string( abi.encodePacked( "Compound ", _getCTokenSymbol(), " contract returned false on calling ", _getFunctionName(functionSelector), "." ) ) ); } else { uint256 compoundError = abi.decode(data, (uint256)); // throw on no data if (compoundError != _COMPOUND_SUCCESS) { revert( string( abi.encodePacked( "Compound ", _getCTokenSymbol(), " contract returned error code ", uint8((compoundError / 10) + 48), uint8((compoundError % 10) + 48), " on calling ", _getFunctionName(functionSelector), "." ) ) ); } } } else { revert( string( abi.encodePacked( "Compound ", _getCTokenSymbol(), " contract reverted while attempting to call ", _getFunctionName(functionSelector), ": ", _decodeRevertReason(data) ) ) ); } } /** * @notice Internal pure function to get a Compound function name based on the * selector. * @param functionSelector bytes4 The function selector. * @return The name of the function as a string. */ function _getFunctionName( bytes4 functionSelector ) internal pure returns (string memory functionName) { CTokenInterface cToken; if (functionSelector == cToken.mint.selector) { functionName = "mint"; } else if (functionSelector == cToken.redeem.selector) { functionName = "redeem"; } else if (functionSelector == cToken.redeemUnderlying.selector) { functionName = "redeemUnderlying"; } else if (functionSelector == cToken.transferFrom.selector) { functionName = "transferFrom"; } else if (functionSelector == cToken.transfer.selector) { functionName = "transfer"; } else if (functionSelector == cToken.accrueInterest.selector) { functionName = "accrueInterest"; } else { functionName = "an unknown function"; } } /** * @notice Internal pure function to decode revert reasons. The revert reason * prefix is removed and the remaining string argument is decoded. * @param revertData bytes The raw data supplied alongside the revert. * @return The decoded revert reason string. */ function _decodeRevertReason( bytes memory revertData ) internal pure returns (string memory revertReason) { // Solidity prefixes revert reason with 0x08c379a0 -> Error(string) selector if ( revertData.length > 68 && // prefix (4) + position (32) + length (32) revertData[0] == byte(0x08) && revertData[1] == byte(0xc3) && revertData[2] == byte(0x79) && revertData[3] == byte(0xa0) ) { // Get the revert reason without the prefix from the revert data. bytes memory revertReasonBytes = new bytes(revertData.length - 4); for (uint256 i = 4; i < revertData.length; i++) { revertReasonBytes[i - 4] = revertData[i]; } // Decode the resultant revert reason as a string. revertReason = abi.decode(revertReasonBytes, (string)); } else { // Simply return the default, with no revert reason. revertReason = "(no revert reason)"; } } /** * @notice Internal pure function to construct a failure message string for * the revert reason on transfers of underlying tokens that do not succeed. * @return The failure message. */ function _getTransferFailureMessage() internal pure returns ( string memory message ) { message = string( abi.encodePacked(_getUnderlyingName(), " transfer failed.") ); } /** * @notice Internal pure function to convert a uint256 to a uint112, reverting * if the conversion would cause an overflow. * @param input uint256 The unsigned integer to convert. * @return The converted unsigned integer. */ function _safeUint112(uint256 input) internal pure returns (uint112 output) { require(input <= _MAX_UINT_112, "Overflow on conversion to uint112."); output = uint112(input); } /** * @notice Internal pure function to convert an underlying amount to a dToken * or cToken amount using an exchange rate and fixed-point arithmetic. * @param underlying uint256 The underlying amount to convert. * @param exchangeRate uint256 The exchange rate (multiplied by 10^18). * @param roundUp bool Whether the final amount should be rounded up - it will * instead be truncated (rounded down) if this value is false. * @return The cToken or dToken amount. */ function _fromUnderlying( uint256 underlying, uint256 exchangeRate, bool roundUp ) internal pure returns (uint256 amount) { if (roundUp) { amount = ( (underlying.mul(_SCALING_FACTOR)).add(exchangeRate.sub(1)) ).div(exchangeRate); } else { amount = (underlying.mul(_SCALING_FACTOR)).div(exchangeRate); } } /** * @notice Internal pure function to convert a dToken or cToken amount to the * underlying amount using an exchange rate and fixed-point arithmetic. * @param amount uint256 The cToken or dToken amount to convert. * @param exchangeRate uint256 The exchange rate (multiplied by 10^18). * @param roundUp bool Whether the final amount should be rounded up - it will * instead be truncated (rounded down) if this value is false. * @return The underlying amount. */ function _toUnderlying( uint256 amount, uint256 exchangeRate, bool roundUp ) internal pure returns (uint256 underlying) { if (roundUp) { underlying = ( (amount.mul(exchangeRate).add(_SCALING_FACTOR_MINUS_ONE) ) / _SCALING_FACTOR); } else { underlying = amount.mul(exchangeRate) / _SCALING_FACTOR; } } /** * @notice Internal pure function to convert an underlying amount to a dToken * or cToken amount and back to the underlying, so as to properly capture * rounding errors, by using an exchange rate and fixed-point arithmetic. * @param underlying uint256 The underlying amount to convert. * @param exchangeRate uint256 The exchange rate (multiplied by 10^18). * @param roundUpOne bool Whether the intermediate dToken or cToken amount * should be rounded up - it will instead be truncated (rounded down) if this * value is false. * @param roundUpTwo bool Whether the final underlying amount should be * rounded up - it will instead be truncated (rounded down) if this value is * false. * @return The intermediate cToken or dToken amount and the final underlying * amount. */ function _fromUnderlyingAndBack( uint256 underlying, uint256 exchangeRate, bool roundUpOne, bool roundUpTwo ) internal pure returns (uint256 amount, uint256 adjustedUnderlying) { amount = _fromUnderlying(underlying, exchangeRate, roundUpOne); adjustedUnderlying = _toUnderlying(amount, exchangeRate, roundUpTwo); } } /** * @title DharmaTokenV2 * @author 0age (dToken mechanics derived from Compound cTokens, ERC20 mechanics * derived from Open Zeppelin's ERC20 contract) * @notice DharmaTokenV2 deprecates the interest-bearing component and prevents * minting of new tokens or redeeming to cTokens. It also returns COMP in * proportion to the respective dToken balance in relation to total supply. */ contract DharmaTokenV2 is ERC20Interface, DTokenInterface, DharmaTokenHelpers { // Set the version of the Dharma Token as a constant. uint256 private constant _DTOKEN_VERSION = 2; ERC20Interface internal constant _COMP = ERC20Interface( 0xc00e94Cb662C3520282E6f5717214004A7f26888 // mainnet ); // Set block number and dToken + cToken exchange rate in slot zero on accrual. AccrualIndex private _accrualIndex; // Slot one tracks the total issued dTokens. uint256 private _totalSupply; // Slots two and three are entrypoints into balance and allowance mappings. mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; // Slot four is an entrypoint into a mapping for used meta-transaction hashes. mapping (bytes32 => bool) private _executedMetaTxs; bool exchangeRateFrozen; // initially false /** * @notice Deprecated. */ function mint( uint256 underlyingToSupply ) external returns (uint256 dTokensMinted) { revert("Minting is no longer supported."); } /** * @notice Deprecated. */ function mintViaCToken( uint256 cTokensToSupply ) external returns (uint256 dTokensMinted) { revert("Minting is no longer supported."); } /** * @notice Redeem `dTokensToBurn` dTokens from `msg.sender`, use the * corresponding cTokens to redeem the required underlying, and transfer the * redeemed underlying tokens to `msg.sender`. * @param dTokensToBurn uint256 The amount of dTokens to provide in exchange * for underlying tokens. * @return The amount of underlying received in return for the provided * dTokens. */ function redeem( uint256 dTokensToBurn ) external returns (uint256 underlyingReceived) { require(exchangeRateFrozen, "Call `pullSurplus()` to freeze exchange rate first."); // Instantiate interface for the underlying token. ERC20Interface underlying = ERC20Interface(_getUnderlying()); require(dTokensToBurn > 0, "No funds specified to redeem."); // Get the total supply, as well as current underlying and COMP balances. uint256 originalSupply = _totalSupply; uint256 underlyingBalance = underlying.balanceOf(address(this)); uint256 compBalance = _COMP.balanceOf(address(this)); // Apply dToken ratio to balances to determine amount to transfer out. underlyingReceived = underlyingBalance.mul(dTokensToBurn) / originalSupply; uint256 compReceived = compBalance.mul(dTokensToBurn) / originalSupply; require( underlyingReceived.add(compReceived) > 0, "Supplied dTokens are insufficient to redeem." ); // Burn the dTokens. _burn(msg.sender, underlyingReceived, dTokensToBurn); // Transfer out the proportion of each associated with the burned tokens. if (underlyingReceived > 0) { require( underlying.transfer(msg.sender, underlyingReceived), _getTransferFailureMessage() ); } if (compReceived > 0) { require( _COMP.transfer(msg.sender, compReceived), "COMP transfer out failed." ); } } /** * @notice Deprecated. */ function redeemToCToken( uint256 dTokensToBurn ) external returns (uint256 cTokensReceived) { revert("Redeeming to cTokens is no longer supported."); } /** * @notice Redeem the dToken equivalent value of the underlying token amount * `underlyingToReceive` from `msg.sender`, use the corresponding cTokens to * redeem the underlying, and transfer the underlying to `msg.sender`. * @param underlyingToReceive uint256 The amount, denominated in the * underlying token, of the cToken to redeem in exchange for the received * underlying token. * @return The amount of dTokens burned in exchange for the returned * underlying tokens. */ function redeemUnderlying( uint256 underlyingToReceive ) external returns (uint256 dTokensBurned) { require(exchangeRateFrozen, "Call `pullSurplus()` to freeze exchange rate first."); // Instantiate interface for the underlying token. ERC20Interface underlying = ERC20Interface(_getUnderlying()); // Get the dToken exchange rate. (uint256 dTokenExchangeRate, ) = _accrue(false); // Determine dToken amount to burn using the exchange rate, rounded up. dTokensBurned = _fromUnderlying( underlyingToReceive, dTokenExchangeRate, true ); // Determine dToken amount for returning COMP by rounding down. uint256 dTokensForCOMP = _fromUnderlying( underlyingToReceive, dTokenExchangeRate, false ); // Get the total supply and current COMP balance. uint256 originalSupply = _totalSupply; uint256 compBalance = _COMP.balanceOf(address(this)); // Apply dToken ratio to COMP balance to determine amount to transfer out. uint256 compReceived = compBalance.mul(dTokensForCOMP) / originalSupply; require( underlyingToReceive.add(compReceived) > 0, "Supplied amount is insufficient to redeem." ); // Burn the dTokens. _burn(msg.sender, underlyingToReceive, dTokensBurned); // Transfer out the proportion of each associated with the burned tokens. if (underlyingToReceive > 0) { require( underlying.transfer(msg.sender, underlyingToReceive), _getTransferFailureMessage() ); } if (compReceived > 0) { require( _COMP.transfer(msg.sender, compReceived), "COMP transfer out failed." ); } } /** * @notice Deprecated. */ function redeemUnderlyingToCToken( uint256 underlyingToReceive ) external returns (uint256 dTokensBurned) { revert("Redeeming to cTokens is no longer supported."); } /** * @notice Transfer cTokens with underlying value in excess of the total * underlying dToken value to a dedicated "vault" account. A "hard" accrual * will first be performed, triggering an accrual on both the cToken and the * dToken. * @return The amount of cTokens transferred to the vault account. */ function pullSurplus() external returns (uint256 cTokenSurplus) { require(!exchangeRateFrozen, "No surplus left to pull."); // Instantiate the interface for the backing cToken. CTokenInterface cToken = CTokenInterface(_getCToken()); // Accrue interest on the cToken and ensure that the operation succeeds. (bool ok, bytes memory data) = address(cToken).call(abi.encodeWithSelector( cToken.accrueInterest.selector )); _checkCompoundInteraction(cToken.accrueInterest.selector, ok, data); // Accrue interest on the dToken, reusing the stored cToken exchange rate. _accrue(false); // Determine cToken surplus in underlying (cToken value - dToken value). uint256 underlyingSurplus; (underlyingSurplus, cTokenSurplus) = _getSurplus(); // Transfer cToken surplus to vault and ensure that the operation succeeds. (ok, data) = address(cToken).call(abi.encodeWithSelector( cToken.transfer.selector, _getVault(), cTokenSurplus )); _checkCompoundInteraction(cToken.transfer.selector, ok, data); emit CollectSurplus(underlyingSurplus, cTokenSurplus); exchangeRateFrozen = true; // Redeem all cTokens for underlying and ensure that the operation succeeds. (ok, data) = address(cToken).call(abi.encodeWithSelector( cToken.redeem.selector, cToken.balanceOf(address(this)) )); _checkCompoundInteraction(cToken.redeem.selector, ok, data); } /** * @notice Deprecated. */ function accrueInterest() external { revert("Interest accrual is longer supported."); } /** * @notice Transfer `amount` dTokens from `msg.sender` to `recipient`. * @param recipient address The account to transfer the dTokens to. * @param amount uint256 The amount of dTokens to transfer. * @return A boolean indicating whether the transfer was successful. */ function transfer( address recipient, uint256 amount ) external returns (bool success) { _transfer(msg.sender, recipient, amount); success = true; } /** * @notice Transfer dTokens equivalent to `underlyingEquivalentAmount` * underlying from `msg.sender` to `recipient`. * @param recipient address The account to transfer the dTokens to. * @param underlyingEquivalentAmount uint256 The underlying equivalent amount * of dTokens to transfer. * @return A boolean indicating whether the transfer was successful. */ function transferUnderlying( address recipient, uint256 underlyingEquivalentAmount ) external returns (bool success) { // Accrue interest and retrieve the current dToken exchange rate. (uint256 dTokenExchangeRate, ) = _accrue(true); // Determine dToken amount to transfer using the exchange rate, rounded up. uint256 dTokenAmount = _fromUnderlying( underlyingEquivalentAmount, dTokenExchangeRate, true ); // Transfer the dTokens. _transfer(msg.sender, recipient, dTokenAmount); success = true; } /** * @notice Approve `spender` to transfer up to `value` dTokens on behalf of * `msg.sender`. * @param spender address The account to grant the allowance. * @param value uint256 The size of the allowance to grant. * @return A boolean indicating whether the approval was successful. */ function approve( address spender, uint256 value ) external returns (bool success) { _approve(msg.sender, spender, value); success = true; } /** * @notice Transfer `amount` dTokens from `sender` to `recipient` as long as * `msg.sender` has sufficient allowance. * @param sender address The account to transfer the dTokens from. * @param recipient address The account to transfer the dTokens to. * @param amount uint256 The amount of dTokens to transfer. * @return A boolean indicating whether the transfer was successful. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool success) { _transferFrom(sender, recipient, amount); success = true; } /** * @notice Transfer dTokens eqivalent to `underlyingEquivalentAmount` * underlying from `sender` to `recipient` as long as `msg.sender` has * sufficient allowance. * @param sender address The account to transfer the dTokens from. * @param recipient address The account to transfer the dTokens to. * @param underlyingEquivalentAmount uint256 The underlying equivalent amount * of dTokens to transfer. * @return A boolean indicating whether the transfer was successful. */ function transferUnderlyingFrom( address sender, address recipient, uint256 underlyingEquivalentAmount ) external returns (bool success) { // Accrue interest and retrieve the current dToken exchange rate. (uint256 dTokenExchangeRate, ) = _accrue(true); // Determine dToken amount to transfer using the exchange rate, rounded up. uint256 dTokenAmount = _fromUnderlying( underlyingEquivalentAmount, dTokenExchangeRate, true ); // Transfer the dTokens and adjust allowance accordingly. _transferFrom(sender, recipient, dTokenAmount); success = true; } /** * @notice Increase the current allowance of `spender` by `value` dTokens. * @param spender address The account to grant the additional allowance. * @param addedValue uint256 The amount to increase the allowance by. * @return A boolean indicating whether the modification was successful. */ function increaseAllowance( address spender, uint256 addedValue ) external returns (bool success) { _approve( msg.sender, spender, _allowances[msg.sender][spender].add(addedValue) ); success = true; } /** * @notice Decrease the current allowance of `spender` by `value` dTokens. * @param spender address The account to decrease the allowance for. * @param subtractedValue uint256 The amount to subtract from the allowance. * @return A boolean indicating whether the modification was successful. */ function decreaseAllowance( address spender, uint256 subtractedValue ) external returns (bool success) { _approve( msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue) ); success = true; } /** * @notice Modify the current allowance of `spender` for `owner` by `value` * dTokens, increasing it if `increase` is true otherwise decreasing it, via a * meta-transaction that expires at `expiration` (or does not expire if the * value is zero) and uses `salt` as an additional input, validated using * `signatures`. * @param owner address The account granting the modified allowance. * @param spender address The account to modify the allowance for. * @param value uint256 The amount to modify the allowance by. * @param increase bool A flag that indicates whether the allowance will be * increased by the specified value (if true) or decreased by it (if false). * @param expiration uint256 A timestamp indicating how long the modification * meta-transaction is valid for - a value of zero will signify no expiration. * @param salt bytes32 An arbitrary salt to be provided as an additional input * to the hash digest used to validate the signatures. * @param signatures bytes A signature, or collection of signatures, that the * owner must provide in order to authorize the meta-transaction. If the * account of the owner does not have any runtime code deployed to it, the * signature will be verified using ecrecover; otherwise, it will be supplied * to the owner along with the message digest and context via ERC-1271 for * validation. * @return A boolean indicating whether the modification was successful. */ function modifyAllowanceViaMetaTransaction( address owner, address spender, uint256 value, bool increase, uint256 expiration, bytes32 salt, bytes calldata signatures ) external returns (bool success) { require(expiration == 0 || now <= expiration, "Meta-transaction expired."); // Construct the meta-transaction's message hash based on relevant context. bytes memory context = abi.encodePacked( address(this), // _DTOKEN_VERSION, this.modifyAllowanceViaMetaTransaction.selector, expiration, salt, abi.encode(owner, spender, value, increase) ); bytes32 messageHash = keccak256(context); // Ensure message hash has never been used before and register it as used. require(!_executedMetaTxs[messageHash], "Meta-transaction already used."); _executedMetaTxs[messageHash] = true; // Construct the digest to compare signatures against using EIP-191 0x45. bytes32 digest = keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", messageHash) ); // Calculate new allowance by applying modification to current allowance. uint256 currentAllowance = _allowances[owner][spender]; uint256 newAllowance = ( increase ? currentAllowance.add(value) : currentAllowance.sub(value) ); // Use EIP-1271 if owner is a contract - otherwise, use ecrecover. if (_isContract(owner)) { // Validate via ERC-1271 against the owner account. bytes memory data = abi.encode(digest, context); bytes4 magic = ERC1271Interface(owner).isValidSignature(data, signatures); require(magic == bytes4(0x20c13b0b), "Invalid signatures."); } else { // Validate via ecrecover against the owner account. _verifyRecover(owner, digest, signatures); } // Modify the allowance. _approve(owner, spender, newAllowance); success = true; } /** * @notice View function to determine a meta-transaction message hash, and to * determine if it is still valid (i.e. it has not yet been used and is not * expired). The returned message hash will need to be prefixed using EIP-191 * 0x45 and hashed again in order to generate a final digest for the required * signature - in other words, the same procedure utilized by `eth_Sign`. * @param functionSelector bytes4 The function selector for the given * meta-transaction. There is only one function selector available for V1: * `0x2d657fa5` (the selector for `modifyAllowanceViaMetaTransaction`). * @param arguments bytes The abi-encoded function arguments (aside from the * `expiration`, `salt`, and `signatures` arguments) that should be supplied * to the given function. * @param expiration uint256 A timestamp indicating how long the given * meta-transaction is valid for - a value of zero will signify no expiration. * @param salt bytes32 An arbitrary salt to be provided as an additional input * to the hash digest used to validate the signatures. * @return The total supply. */ function getMetaTransactionMessageHash( bytes4 functionSelector, bytes calldata arguments, uint256 expiration, bytes32 salt ) external view returns (bytes32 messageHash, bool valid) { // Construct the meta-transaction's message hash based on relevant context. messageHash = keccak256( abi.encodePacked( address(this), functionSelector, expiration, salt, arguments ) ); // The meta-transaction is valid if it has not been used and is not expired. valid = ( !_executedMetaTxs[messageHash] && (expiration == 0 || now <= expiration) ); } /** * @notice View function to get the total dToken supply. * @return The total supply. */ function totalSupply() external view returns (uint256 dTokenTotalSupply) { dTokenTotalSupply = _totalSupply; } /** * @notice View function to get the total dToken supply, denominated in the * underlying token. * @return The total supply. */ function totalSupplyUnderlying() external view returns ( uint256 dTokenTotalSupplyInUnderlying ) { (uint256 dTokenExchangeRate, ,) = _getExchangeRates(true); // Determine total value of all issued dTokens, denominated as underlying. dTokenTotalSupplyInUnderlying = _toUnderlying( _totalSupply, dTokenExchangeRate, false ); } /** * @notice View function to get the total dToken balance of an account. * @param account address The account to check the dToken balance for. * @return The balance of the given account. */ function balanceOf(address account) external view returns (uint256 dTokens) { dTokens = _balances[account]; } /** * @notice View function to get the dToken balance of an account, denominated * in the underlying equivalent value. * @param account address The account to check the balance for. * @return The total underlying-equivalent dToken balance. */ function balanceOfUnderlying( address account ) external view returns (uint256 underlyingBalance) { // Get most recent dToken exchange rate by determining accrued interest. (uint256 dTokenExchangeRate, ,) = _getExchangeRates(true); // Convert account balance to underlying equivalent using the exchange rate. underlyingBalance = _toUnderlying( _balances[account], dTokenExchangeRate, false ); } /** * @notice View function to get the total allowance that `spender` has to * transfer dTokens from the `owner` account using `transferFrom`. * @param owner address The account that is granting the allowance. * @param spender address The account that has been granted the allowance. * @return The allowance of the given spender for the given owner. */ function allowance( address owner, address spender ) external view returns (uint256 dTokenAllowance) { dTokenAllowance = _allowances[owner][spender]; } /** * @notice View function to get the current dToken exchange rate (multiplied * by 10^18). * @return The current exchange rate. */ function exchangeRateCurrent() external view returns ( uint256 dTokenExchangeRate ) { // Get most recent dToken exchange rate by determining accrued interest. (dTokenExchangeRate, ,) = _getExchangeRates(true); } /** * @notice View function to get the current dToken interest earned per block * (multiplied by 10^18). * @return The current interest rate. */ function supplyRatePerBlock() external view returns ( uint256 dTokenInterestRate ) { (dTokenInterestRate,) = _getRatePerBlock(); } /** * @notice View function to get the block number where accrual was last * performed. * @return The block number where accrual was last performed. */ function accrualBlockNumber() external view returns (uint256 blockNumber) { blockNumber = _accrualIndex.block; } /** * @notice View function to get the total surplus, or the cToken balance that * exceeds the aggregate underlying value of the total dToken supply. * @return The total surplus in cTokens. */ function getSurplus() external view returns (uint256 cTokenSurplus) { // Determine the cToken (cToken underlying value - dToken underlying value). (, cTokenSurplus) = _getSurplus(); } /** * @notice View function to get the total surplus in the underlying, or the * underlying equivalent of the cToken balance that exceeds the aggregate * underlying value of the total dToken supply. * @return The total surplus, denominated in the underlying. */ function getSurplusUnderlying() external view returns ( uint256 underlyingSurplus ) { // Determine cToken surplus in underlying (cToken value - dToken value). (underlyingSurplus, ) = _getSurplus(); } /** * @notice View function to get the interest rate spread taken by the dToken * from the current cToken supply rate per block (multiplied by 10^18). * @return The current interest rate spread. */ function getSpreadPerBlock() external view returns (uint256 rateSpread) { ( uint256 dTokenInterestRate, uint256 cTokenInterestRate ) = _getRatePerBlock(); rateSpread = cTokenInterestRate.sub(dTokenInterestRate); } /** * @notice Pure function to get the name of the dToken. * @return The name of the dToken. */ function name() external pure returns (string memory dTokenName) { dTokenName = _getDTokenName(); } /** * @notice Pure function to get the symbol of the dToken. * @return The symbol of the dToken. */ function symbol() external pure returns (string memory dTokenSymbol) { dTokenSymbol = _getDTokenSymbol(); } /** * @notice Pure function to get the number of decimals of the dToken. * @return The number of decimals of the dToken. */ function decimals() external pure returns (uint8 dTokenDecimals) { dTokenDecimals = _DECIMALS; } /** * @notice Pure function to get the dToken version. * @return The version of the dToken. */ function getVersion() external pure returns (uint256 version) { version = _DTOKEN_VERSION; } /** * @notice Pure function to get the address of the cToken backing this dToken. * @return The address of the cToken backing this dToken. */ function getCToken() external pure returns (address cToken) { cToken = _getCToken(); } /** * @notice Pure function to get the address of the underlying token of this * dToken. * @return The address of the underlying token for this dToken. */ function getUnderlying() external pure returns (address underlying) { underlying = _getUnderlying(); } /** * @notice Private function to trigger accrual and to update the dToken and * cToken exchange rates in storage if necessary. The `compute` argument can * be set to false if an accrual has already taken place on the cToken before * calling this function. * @param compute bool A flag to indicate whether the cToken exchange rate * needs to be computed - if false, it will simply be read from storage on the * cToken in question. * @return The current dToken and cToken exchange rates. */ function _accrue(bool compute) private returns ( uint256 dTokenExchangeRate, uint256 cTokenExchangeRate ) { bool alreadyAccrued; ( dTokenExchangeRate, cTokenExchangeRate, alreadyAccrued ) = _getExchangeRates(compute); if (!alreadyAccrued) { // Update storage with dToken + cToken exchange rates as of current block. AccrualIndex storage accrualIndex = _accrualIndex; accrualIndex.dTokenExchangeRate = _safeUint112(dTokenExchangeRate); accrualIndex.cTokenExchangeRate = _safeUint112(cTokenExchangeRate); accrualIndex.block = uint32(block.number); emit Accrue(dTokenExchangeRate, cTokenExchangeRate); } } /** * @notice Private function to burn `amount` tokens by exchanging `exchanged` * tokens from `account` and emit corresponding `Redeeem` & `Transfer` events. * @param account address The account to burn tokens from. * @param exchanged uint256 The amount of underlying tokens given for burning. * @param amount uint256 The amount of tokens to burn. */ function _burn(address account, uint256 exchanged, uint256 amount) private { require( exchanged > 0 && amount > 0, "Redeem failed: insufficient funds supplied." ); uint256 balancePriorToBurn = _balances[account]; require( balancePriorToBurn >= amount, "Supplied amount exceeds account balance." ); _totalSupply = _totalSupply.sub(amount); _balances[account] = balancePriorToBurn - amount; // overflow checked above emit Transfer(account, address(0), amount); emit Redeem(account, exchanged, amount); } /** * @notice Private function to move `amount` tokens from `sender` to * `recipient` and emit a corresponding `Transfer` event. * @param sender address The account to transfer tokens from. * @param recipient address The account to transfer tokens to. * @param amount uint256 The amount of tokens to transfer. */ function _transfer( address sender, address recipient, uint256 amount ) private { 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, "Insufficient funds."); _balances[sender] = senderBalance - amount; // overflow checked above. _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @notice Private function to transfer `amount` tokens from `sender` to * `recipient` and to deduct the transferred amount from the allowance of the * caller unless the allowance is set to the maximum amount. * @param sender address The account to transfer tokens from. * @param recipient address The account to transfer tokens to. * @param amount uint256 The amount of tokens to transfer. */ function _transferFrom( address sender, address recipient, uint256 amount ) private { _transfer(sender, recipient, amount); uint256 callerAllowance = _allowances[sender][msg.sender]; if (callerAllowance != uint256(-1)) { require(callerAllowance >= amount, "Insufficient allowance."); _approve(sender, msg.sender, callerAllowance - amount); // overflow safe. } } /** * @notice Private function to set the allowance for `spender` to transfer up * to `value` tokens on behalf of `owner`. * @param owner address The account that has granted the allowance. * @param spender address The account to grant the allowance. * @param value uint256 The size of the allowance to grant. */ function _approve(address owner, address spender, uint256 value) private { require(owner != address(0), "ERC20: approve for the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @notice Private view function to get the latest dToken and cToken exchange * rates and provide the value for each. The `compute` argument can be set to * false if an accrual has already taken place on the cToken before calling * this function. * @param compute bool A flag to indicate whether the cToken exchange rate * needs to be computed - if false, it will simply be read from storage on the * cToken in question. * @return The dToken and cToken exchange rate, as well as a boolean * indicating if interest accrual has been processed already or needs to be * calculated and placed in storage. */ function _getExchangeRates(bool compute) private view returns ( uint256 dTokenExchangeRate, uint256 cTokenExchangeRate, bool fullyAccrued ) { // Get the stored accrual block and dToken + cToken exhange rates. AccrualIndex memory accrualIndex = _accrualIndex; uint256 storedDTokenExchangeRate = uint256(accrualIndex.dTokenExchangeRate); uint256 storedCTokenExchangeRate = uint256(accrualIndex.cTokenExchangeRate); uint256 accrualBlock = uint256(accrualIndex.block); // Use stored exchange rates if an accrual has already occurred this block. fullyAccrued = (accrualBlock == block.number); if (fullyAccrued) { dTokenExchangeRate = storedDTokenExchangeRate; cTokenExchangeRate = storedCTokenExchangeRate; } else { // Only compute cToken exchange rate if it has not accrued this block. if (compute) { // Get current cToken exchange rate; inheriting contract overrides this. (cTokenExchangeRate,) = _getCurrentCTokenRates(); } else { // Otherwise, get the stored cToken exchange rate. cTokenExchangeRate = CTokenInterface(_getCToken()).exchangeRateStored(); } if (exchangeRateFrozen) { dTokenExchangeRate = storedDTokenExchangeRate; } else { // Determine the cToken interest earned during the period. uint256 cTokenInterest = ( (cTokenExchangeRate.mul(_SCALING_FACTOR)).div(storedCTokenExchangeRate) ).sub(_SCALING_FACTOR); // Calculate dToken exchange rate by applying 90% of the cToken interest. dTokenExchangeRate = storedDTokenExchangeRate.mul( _SCALING_FACTOR.add(cTokenInterest.mul(9) / 10) ) / _SCALING_FACTOR; } } } /** * @notice Private view function to get the total surplus, or cToken * balance that exceeds the total dToken balance. * @return The total surplus, denominated in both the underlying and in the * cToken. */ function _getSurplus() private view returns ( uint256 underlyingSurplus, uint256 cTokenSurplus ) { if (exchangeRateFrozen) { underlyingSurplus = 0; cTokenSurplus = 0; } else { // Instantiate the interface for the backing cToken. CTokenInterface cToken = CTokenInterface(_getCToken()); ( uint256 dTokenExchangeRate, uint256 cTokenExchangeRate, ) = _getExchangeRates(true); // Determine value of all issued dTokens in the underlying, rounded up. uint256 dTokenUnderlying = _toUnderlying( _totalSupply, dTokenExchangeRate, true ); // Determine value of all retained cTokens in the underlying, rounded down. uint256 cTokenUnderlying = _toUnderlying( cToken.balanceOf(address(this)), cTokenExchangeRate, false ); // Determine the size of the surplus in terms of underlying amount. underlyingSurplus = cTokenUnderlying > dTokenUnderlying ? cTokenUnderlying - dTokenUnderlying // overflow checked above : 0; // Determine the cToken equivalent of this surplus amount. cTokenSurplus = underlyingSurplus == 0 ? 0 : _fromUnderlying(underlyingSurplus, cTokenExchangeRate, false); } } /** * @notice Private view function to get the current dToken and cToken interest * supply rate per block (multiplied by 10^18). * @return The current dToken and cToken interest rates. */ function _getRatePerBlock() private view returns ( uint256 dTokenSupplyRate, uint256 cTokenSupplyRate ) { (, cTokenSupplyRate) = _getCurrentCTokenRates(); if (exchangeRateFrozen) { dTokenSupplyRate = 0; } else { dTokenSupplyRate = cTokenSupplyRate.mul(9) / 10; } } /** * @notice Private view function to determine if a given account has runtime * code or not - in other words, whether or not a contract is deployed to the * account in question. Note that contracts that are in the process of being * deployed will return false on this check. * @param account address The account to check for contract runtime code. * @return Whether or not there is contract runtime code at the account. */ function _isContract(address account) private view returns (bool isContract) { uint256 size; assembly { size := extcodesize(account) } isContract = size > 0; } /** * @notice Private pure function to verify that a given signature of a digest * resolves to the supplied account. Any error, including incorrect length, * malleable signature types, or unsupported `v` values, will cause a revert. * @param account address The account to validate against. * @param digest bytes32 The digest to use. * @param signature bytes The signature to verify. */ function _verifyRecover( address account, bytes32 digest, bytes memory signature ) private pure { // Ensure the signature length is correct. require( signature.length == 65, "Must supply a single 65-byte signature when owner is not a contract." ); // Divide the signature in r, s and v variables. bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } require( uint256(s) <= _MAX_UNMALLEABLE_S, "Signature `s` value cannot be potentially malleable." ); require(v == 27 || v == 28, "Signature `v` value not permitted."); require(account == ecrecover(digest, v, r, s), "Invalid signature."); } } /** * @title DharmaUSDCImplementationV2 * @author 0age (dToken mechanics derived from Compound cTokens, ERC20 methods * derived from Open Zeppelin's ERC20 contract) * @notice This contract provides the V2 implementation of Dharma USD Coin (or * dUSDC), which effectively deprecates Dharma USD Coin. */ contract DharmaUSDCImplementationV2 is DharmaTokenV2 { string internal constant _NAME = "Dharma USD Coin"; string internal constant _SYMBOL = "dUSDC"; string internal constant _UNDERLYING_NAME = "USD Coin"; string internal constant _CTOKEN_SYMBOL = "cUSDC"; CTokenInterface internal constant _CUSDC = CTokenInterface( 0x39AA39c021dfbaE8faC545936693aC917d5E7563 // mainnet ); ERC20Interface internal constant _USDC = ERC20Interface( 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet ); address internal constant _VAULT = 0x7e4A8391C728fEd9069B2962699AB416628B19Fa; uint256 internal constant _SCALING_FACTOR_SQUARED = 1e36; /** * @notice Internal view function to get the current cUSDC exchange rate and * supply rate per block. * @return The current cUSDC exchange rate, or amount of USDC that is * redeemable for each cUSDC, and the cUSDC supply rate per block (with 18 * decimal places added to each returned rate). */ function _getCurrentCTokenRates() internal view returns ( uint256 exchangeRate, uint256 supplyRate ) { // Determine number of blocks that have elapsed since last cUSDC accrual. uint256 blockDelta = block.number.sub(_CUSDC.accrualBlockNumber()); // Return stored values if accrual has already been performed this block. if (blockDelta == 0) return ( _CUSDC.exchangeRateStored(), _CUSDC.supplyRatePerBlock() ); // Determine total "cash" held by cUSDC contract. uint256 cash = _USDC.balanceOf(address(_CUSDC)); // Get the latest interest rate model from the cUSDC contract. CUSDCInterestRateModelInterface interestRateModel = ( CUSDCInterestRateModelInterface(_CUSDC.interestRateModel()) ); // Get the current stored total borrows, reserves, and reserve factor. uint256 borrows = _CUSDC.totalBorrows(); uint256 reserves = _CUSDC.totalReserves(); uint256 reserveFactor = _CUSDC.reserveFactorMantissa(); // Get the current borrow rate from the latest cUSDC interest rate model. (uint256 err, uint256 borrowRate) = interestRateModel.getBorrowRate( cash, borrows, reserves ); require( err == _COMPOUND_SUCCESS, "Interest Rate Model borrow rate check failed." ); // Get accumulated borrow interest via borrows, borrow rate, & block delta. uint256 interest = borrowRate.mul(blockDelta).mul(borrows) / _SCALING_FACTOR; // Update total borrows and reserves using calculated accumulated interest. borrows = borrows.add(interest); reserves = reserves.add(reserveFactor.mul(interest) / _SCALING_FACTOR); // Get "underlying" via (cash + borrows - reserves). uint256 underlying = (cash.add(borrows)).sub(reserves); // Determine cUSDC exchange rate via underlying / total supply. exchangeRate = (underlying.mul(_SCALING_FACTOR)).div(_CUSDC.totalSupply()); // Get "borrows per" by dividing total borrows by underlying and scaling up. uint256 borrowsPer = (borrows.mul(_SCALING_FACTOR)).div(underlying); // Supply rate is borrow rate * (1 - reserveFactor) * borrowsPer. supplyRate = ( borrowRate.mul(_SCALING_FACTOR.sub(reserveFactor)).mul(borrowsPer) ) / _SCALING_FACTOR_SQUARED; } /** * @notice Internal pure function to supply the name of the underlying token. * @return The name of the underlying token. */ function _getUnderlyingName() internal pure returns (string memory underlyingName) { underlyingName = _UNDERLYING_NAME; } /** * @notice Internal pure function to supply the address of the underlying * token. * @return The address of the underlying token. */ function _getUnderlying() internal pure returns (address underlying) { underlying = address(_USDC); } /** * @notice Internal pure function to supply the symbol of the backing cToken. * @return The symbol of the backing cToken. */ function _getCTokenSymbol() internal pure returns (string memory cTokenSymbol) { cTokenSymbol = _CTOKEN_SYMBOL; } /** * @notice Internal pure function to supply the address of the backing cToken. * @return The address of the backing cToken. */ function _getCToken() internal pure returns (address cToken) { cToken = address(_CUSDC); } /** * @notice Internal pure function to supply the name of the dToken. * @return The name of the dToken. */ function _getDTokenName() internal pure returns (string memory dTokenName) { dTokenName = _NAME; } /** * @notice Internal pure function to supply the symbol of the dToken. * @return The symbol of the dToken. */ function _getDTokenSymbol() internal pure returns (string memory dTokenSymbol) { dTokenSymbol = _SYMBOL; } /** * @notice Internal pure function to supply the address of the vault that * receives surplus cTokens whenever the surplus is pulled. * @return The address of the vault. */ function _getVault() internal pure returns (address vault) { vault = _VAULT; } }
Deprecated./
function redeemToCToken( uint256 dTokensToBurn ) external returns (uint256 cTokensReceived) { revert("Redeeming to cTokens is no longer supported."); }
1,547,820
./full_match/3/0x659E32E1d19699e290253e063dd6C5b6bd12d584/sources/contracts/ViperToken.sol
Function to create a new viper matron ID of new viper's matron (one parent) sire ID of new viper's sire (other parent) viperOwner Address of new viper's owner return The new viper's ID/
{ require(viperOwner != address(0)); uint8 newGenes = generateViperGenes(matron, sire); function generateViperGenes( uint256 matron, uint256 sire ) internal pure returns (uint8) } function createViper( uint256 matron, uint256 sire, address viperOwner ) public returns (uint) Viper memory newViper = Viper({ genes: newGenes, matronId: matron, sireId: sire }); vipers.push(newViper); uint256 newViperId = vipers.length - 1; super._mint(viperOwner, newViperId); emit Birth( viperOwner, newViperId, newViper.matronId, newViper.sireId, newViper.genes ); return newViperId; }
14,163,727
pragma solidity ^0.8.9; import "./utils/Strings.sol"; //Just a storage contract for base items at the moment. //TODO: standardize access controls contract RMRKBase { using Strings for uint256; string commonSrcPrefix; string commonSrcSuffix; //bytes8 is sort of arbitrary here--resource IDs in RMRK substrate are bytes8 for reference mapping (bytes8 => Base) private bases; bytes8[] private baseIds; enum ItemType { Slot, Fixed } struct IntakeStruct { bytes8 id; Base base; } //If IPFS storage as pure index is acceptable, this format is gas-efficient. //Double check to make sure this is effectively one storage slot. //Consider merkel tree for equippables array if stuff gets crazy struct Base { ItemType itemType; //1 byte uint8 z; //1 byte bool exists; //1 byte bytes8[] equippableIds; //n bytes, probably uses its own storage slot anyway string src; //n bytes string fallbackSrc; //n bytes } //Passing structs is messy Arrays of structs containing other structs a bit moreso. Make sure this is acceptable. constructor(IntakeStruct[] memory intakeStruct) { addBaseResourceList(intakeStruct); } function addBaseResourceList (IntakeStruct[] memory intakeStruct) public { for (uint i = 0; i<intakeStruct.length; i++) { addBaseResource(intakeStruct[i]); } } function addBaseResource (IntakeStruct memory intakeStruct) public { require(!bases[intakeStruct.id].exists, "Base already exists"); intakeStruct.base.exists = true; //enforce exists, can swap to require if need be. bases[intakeStruct.id] = intakeStruct.base; baseIds.push(intakeStruct.id); } /* //Overloaded function to add items piecemeal function addBaseResource (bytes8 _id, ItemType _itemType, uint32 _src, uint32 _fallbackSrc, uint8 _z, bytes8[] _equippable) public { bases[_id] = Base({ itemType: _itemType, src: _src, fallbackSrc: _fallbackSrc, z: _z, exists: true, equippableIds: _equippable }); } */ function removeBaseResource (bytes8 _id) public { uint i; while (i < baseIds.length) { if (baseIds[i] == _id) { baseIds[i] = baseIds[baseIds.length-1]; baseIds.pop(); } i++; delete bases[_id]; } } //Constructs src and fallbakcSrc from global constants. Gas-efficient if strict indexing of base by uint on IPFS is an acceptabe standard. //probably better if I reimplement Strings from uint256 to uint32, but this is still cheaper function getBaseResource (bytes8 _id) public view returns (Base memory, string memory, string memory) { Base memory base = bases[_id]; string memory src = string(abi.encodePacked(commonSrcPrefix, srcInt.toString(), commonSrcSuffix)); string memory fallbackSrc = string(abi.encodePacked(commonSrcPrefix, fallbackSrcInt.toString(), commonSrcSuffix)); return (base, src, fallbackSrc); } }
Constructs src and fallbakcSrc from global constants. Gas-efficient if strict indexing of base by uint on IPFS is an acceptabe standard.probably better if I reimplement Strings from uint256 to uint32, but this is still cheaper
function getBaseResource (bytes8 _id) public view returns (Base memory, string memory, string memory) { Base memory base = bases[_id]; string memory src = string(abi.encodePacked(commonSrcPrefix, srcInt.toString(), commonSrcSuffix)); string memory fallbackSrc = string(abi.encodePacked(commonSrcPrefix, fallbackSrcInt.toString(), commonSrcSuffix)); return (base, src, fallbackSrc); }
13,032,729
/* Copyright (c) 2020 Fuel Labs 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.5.1; /* Authors: DappHub License: GNU Modified by: FuelLabs */ contract DSMath { function ds_add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function ds_sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function ds_mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } } contract ERC20 { // METHODS function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); // EVENTS event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract FuelConstants { // CONSTANTS uint256 constant public BOND_SIZE = .1 ether; // required for block commitment uint256 constant public FINALIZATION_DELAY = 7 days / 12; // ~ 1 weeks at 12 second block times uint256 constant public SUBMISSION_DELAY = uint256(2 days) / 12; // ~ 2 day (should be 2 days) in Ethereum Blocks uint256 constant public CLOSING_DELAY = uint256(90 days) / 12; // (should be 2 months) uint256 constant public MAX_TRANSACTIONS_SIZE = 58823; uint256 constant public TRANSACTION_ROOTS_MAX = 256; // ASSEMBLY ONLY FRAUD CODES uint256 constant FraudCode_InvalidMetadataBlockHeight = 0; uint256 constant FraudCode_TransactionHashZero = 1; uint256 constant FraudCode_TransactionIndexOverflow = 2; uint256 constant FraudCode_MetadataOutputIndexOverflow = 3; uint256 constant FraudCode_InvalidUTXOHashReference = 4; uint256 constant FraudCode_InvalidReturnWitnessNotSpender = 5; uint256 constant FraudCode_InputDoubleSpend = 6; uint256 constant FraudCode_InvalidMerkleTreeRoot = 7; uint256 constant FraudCode_MetadataBlockHeightUnderflow = 8; uint256 constant FraudCode_MetadataBlockHeightOverflow = 9; uint256 constant FraudCode_InvalidHTLCDigest = 10; uint256 constant FraudCode_TransactionLengthUnderflow = 11; uint256 constant FraudCode_TransactionLengthOverflow = 12; uint256 constant FraudCode_InvalidTransactionInputType = 13; uint256 constant FraudCode_TransactionOutputWitnessReferenceOverflow = 14; uint256 constant FraudCode_InvalidTransactionOutputType = 15; uint256 constant FraudCode_TransactionSumMismatch = 16; uint256 constant FraudCode_TransactionInputWitnessReferenceOverflow = 17; uint256 constant FraudCode_TransactionInputDepositZero = 18; uint256 constant FraudCode_TransactionInputDepositWitnessOverflow = 19; uint256 constant FraudCode_TransactionHTLCWitnessOverflow = 20; uint256 constant FraudCode_TransactionOutputAmountLengthUnderflow = 21; uint256 constant FraudCode_TransactionOutputAmountLengthOverflow = 22; uint256 constant FraudCode_TransactionOutputTokenIDOverflow = 23; uint256 constant FraudCode_TransactionOutputHTLCDigestZero = 24; uint256 constant FraudCode_TransactionOutputHTLCExpiryZero = 25; uint256 constant FraudCode_InvalidTransactionWitnessSignature = 26; uint256 constant FraudCode_TransactionWitnessesLengthUnderflow = 27; uint256 constant FraudCode_TransactionWitnessesLengthOverflow = 28; uint256 constant FraudCode_TransactionInputsLengthUnderflow = 29; uint256 constant FraudCode_TransactionInputsLengthOverflow = 30; uint256 constant FraudCode_TransactionOutputsLengthUnderflow = 31; uint256 constant FraudCode_TransactionOutputsLengthOverflow = 32; uint256 constant FraudCode_TransactionMetadataLengthOverflow = 33; uint256 constant FraudCode_TransactionInputSelectorOverflow = 34; uint256 constant FraudCode_TransactionOutputSelectorOverflow = 35; uint256 constant FraudCode_TransactionWitnessSelectorOverflow = 37; uint256 constant FraudCode_TransactionUTXOType = 38; uint256 constant FraudCode_TransactionUTXOOutputIndexOverflow = 39; uint256 constant FraudCode_InvalidTransactionsNetLength = 40; uint256 constant FraudCode_MetadataTransactionsRootsLengthOverflow = 41; uint256 constant FraudCode_ComputedTransactionLengthOverflow = 42; uint256 constant FraudCode_ProvidedDataOverflow = 43; uint256 constant FraudCode_MetadataReferenceOverflow = 44; uint256 constant FraudCode_OutputHTLCExpiryUnderflow = 45; uint256 constant FraudCode_InvalidInputWithdrawalSpend = 46; uint256 constant FraudCode_InvalidTypeReferenceMismatch = 47; uint256 constant FraudCode_InvalidChangeInputSpender = 48; uint256 constant FraudCode_InvalidTransactionRootIndexOverflow = 49; // ASSEMBLY ONLY ERROR CODES uint256 constant ErrorCode_InvalidTypeDeposit = 0; uint256 constant ErrorCode_InputReferencedNotProvided = 1; uint256 constant ErrorCode_InvalidReturnWitnessSelected = 2; uint256 constant ErrroCode_InvalidReturnWitnessAddressEmpty = 3; uint256 constant ErrroCode_InvalidSpenderWitnessAddressEmpty = 4; uint256 constant ErrorCode_InvalidTransactionComparison = 5; uint256 constant ErrorCode_WithdrawalAlreadyHappened = 6; uint256 constant ErrorCode_BlockProducerNotCaller = 7; uint256 constant ErrorCode_BlockBondAlreadyWithdrawn = 8; uint256 constant ErrorCode_InvalidProofType = 9; uint256 constant ErrorCode_BlockHashNotFound = 10; uint256 constant ErrorCode_BlockHeightOverflow = 11; uint256 constant ErrorCode_BlockHeightUnderflow = 12; uint256 constant ErrorCode_BlockNotFinalized = 13; uint256 constant ErrorCode_BlockFinalized = 14; uint256 constant ErrorCode_TransactionRootLengthUnderflow = 15; uint256 constant ErrorCode_TransactionRootIndexOverflow = 16; uint256 constant ErrorCode_TransactionRootHashNotInBlockHeader = 17; uint256 constant ErrorCode_TransactionRootHashInvalid = 18; uint256 constant ErrorCode_TransactionLeafHashInvalid = 19; uint256 constant ErrorCode_MerkleTreeHeightOverflow = 20; uint256 constant ErrorCode_MerkleTreeRootInvalid = 21; uint256 constant ErrorCode_InputIndexSelectedOverflow = 22; uint256 constant ErrorCode_OutputIndexSelectedOverflow = 23; uint256 constant ErrorCode_WitnessIndexSelectedOverflow = 24; uint256 constant ErrorCode_TransactionUTXOIDInvalid = 25; uint256 constant ErrorCode_FraudBlockHeightUnderflow = 26; uint256 constant ErrorCode_FraudBlockFinalized = 27; uint256 constant ErrorCode_SafeMathAdditionOverflow = 28; uint256 constant ErrorCode_SafeMathSubtractionUnderflow = 29; uint256 constant ErrorCode_SafeMathMultiplyOverflow = 30; uint256 constant ErrorCode_TransferAmountUnderflow = 31; uint256 constant ErrorCode_TransferOwnerInvalid = 32; uint256 constant ErrorCode_TransferTokenIDOverflow = 33; uint256 constant ErrorCode_TransferEtherCallResult = 34; uint256 constant ErrorCode_TransferERC20Result = 35; uint256 constant ErrorCode_TransferTokenAddress = 36; uint256 constant ErrorCode_InvalidPreviousBlockHash = 37; uint256 constant ErrorCode_TransactionRootsLengthUnderflow = 38; uint256 constant ErrorCode_TransactionRootsLengthOverflow = 39; uint256 constant ErrorCode_InvalidWithdrawalOutputType = 40; uint256 constant ErrorCode_InvalidWithdrawalOwner = 41; uint256 constant ErrorCode_InvalidDepositProof = 42; uint256 constant ErrorCode_InvalidTokenAddress = 43; uint256 constant ErrorCode_InvalidBlockHeightReference = 44; uint256 constant ErrorCode_InvalidOutputIndexReference = 45; uint256 constant ErrorCode_InvalidTransactionRootReference = 46; uint256 constant ErrorCode_InvalidTransactionIndexReference = 47; uint256 constant ErrorCode_ProofLengthOverflow = 48; uint256 constant ErrorCode_InvalidTransactionsABILengthOverflow = 49; // ASSEMBLY ONLY CONSTANTS // Memory Layout * 32 // 0 -> 12 Swap for hashing, ecrecover, events data etc] // 12 -> 44 Virtual Stack Memory (stack and swap behind writeable calldata for safety) // 44 -> calldatasize() Calldata // 44 + calldatasize() Free Memory // Calldata Memory Position uint256 constant Swap_MemoryPosition = 0 * 32; // Swap -> 12 uint256 constant Stack_MemoryPosition = 12 * 32; // Virtual Stack -> 44 uint256 constant Calldata_MemoryPosition = 44 * 32; // Calldata // Length and Index max/min for Inputs, Outputs, Witnesses, Metadata uint256 constant TransactionLengthMax = 8; uint256 constant TransactionLengthMin = 0; // Metadata, Witness and UTXO Proof Byte Size, Types and Lengths etc.. uint256 constant MetadataSize = 8; uint256 constant WitnessSize = 65; uint256 constant UTXOProofSize = 9 * 32; uint256 constant DepositProofSize = 96; uint256 constant TypeSize = 1; uint256 constant LengthSize = 1; uint256 constant TransactionLengthSize = 2; uint256 constant DigestSize = 32; uint256 constant ExpirySize = 4; uint256 constant IndexSize = 1; // Booleans uint256 constant True = 1; uint256 constant False = 0; // Minimum and Maximum transaction byte length uint256 constant TransactionSizeMinimum = 100; uint256 constant TransactionSizeMaximum = 800; // Maximum Merkle Tree Height uint256 constant MerkleTreeHeightMaximum = 256; // Select maximum number of transactions that can be included in a Side Chain block uint256 constant MaxTransactionsInBlock = 2048; // Ether Token Address (u256 chunk for assembly usage == address(0)) uint256 constant EtherToken = 0; // Genesis Block Height uint256 constant GenesisBlockHeight = 0; // 4 i.e. (1) Input / (2) Output / (3) Witness Selection / (4) Metadata Selection uint256 constant SelectionStackOffsetSize = 4; // Topic Hashes uint256 constant WithdrawalEventTopic = 0x782748bc04673eff1ae34a02239afa5a53a83abdfa31d65d7eea2684c4b31fe4; uint256 constant FraudEventTopic = 0x62a5229d18b497dceab57b82a66fb912a8139b88c6b7979ad25772dc9d28ddbd; // ASSEMBLY ONLY ENUMS // Method Enums uint256 constant Not_Finalized = 0; uint256 constant Is_Finalized = 1; uint256 constant Include_UTXOProofs = 1; uint256 constant No_UTXOProofs = 0; uint256 constant FirstProof = 0; uint256 constant SecondProof = 1; uint256 constant OneProof = 1; uint256 constant TwoProofs = 2; // Input Types Enums uint256 constant InputType_UTXO = 0; uint256 constant InputType_Deposit = 1; uint256 constant InputType_HTLC = 2; uint256 constant InputType_Change = 3; // Input Sizes uint256 constant InputSizes_UTXO = 33; uint256 constant InputSizes_Change = 33; uint256 constant InputSizes_Deposit = 33; uint256 constant InputSizes_HTLC = 65; // Output Types Enums uint256 constant OutputType_UTXO = 0; uint256 constant OutputType_withdrawal = 1; uint256 constant OutputType_HTLC = 2; uint256 constant OutputType_Change = 3; // ASSEMBLY ONLY MEMORY STACK POSITIONS uint256 constant Stack_InputsSum = 0; uint256 constant Stack_OutputsSum = 1; uint256 constant Stack_Metadata = 2; uint256 constant Stack_BlockTip = 3; uint256 constant Stack_UTXOProofs = 4; uint256 constant Stack_TransactionHashID = 5; uint256 constant Stack_BlockHeader = 6; uint256 constant Stack_RootHeader = 19; uint256 constant Stack_SelectionOffset = 7; uint256 constant Stack_Index = 28; uint256 constant Stack_SummingTokenID = 29; uint256 constant Stack_SummingToken = 30; // Selection Stack Positions (Comparison Proof Selections) uint256 constant Stack_MetadataSelected = 8; uint256 constant Stack_SelectedInputLength = 9; uint256 constant Stack_OutputSelected = 10; uint256 constant Stack_WitnessSelected = 11; uint256 constant Stack_MetadataSelected2 = 12; uint256 constant Stack_SelectedInputLength2 = 13; uint256 constant Stack_OutputSelected2 = 14; uint256 constant Stack_WitnessSelected2 = 15; uint256 constant Stack_RootProducer = 16; uint256 constant Stack_Witnesses = 17; uint256 constant Stack_MerkleProofLeftish = 23; uint256 constant Stack_ProofNumber = 25; uint256 constant Stack_FreshMemory = 26; uint256 constant Stack_MetadataLength = 31; // Storage Positions (based on Solidity compilation) uint256 constant Storage_deposits = 0; uint256 constant Storage_withdrawals = 1; uint256 constant Storage_blockTransactionRoots = 2; uint256 constant Storage_blockCommitments = 3; uint256 constant Storage_tokens = 4; uint256 constant Storage_numTokens = 5; uint256 constant Storage_blockTip = 6; uint256 constant Storage_blockProducer = 7; } contract Fuel is FuelConstants, DSMath { // EVENTS event DepositMade(address indexed account, address indexed token, uint256 amount); event WithdrawalMade(address indexed account, address token, uint256 amount, uint256 indexed blockHeight, uint256 transactionRootIndex, bytes32 indexed transactionLeafHash, uint8 outputIndex, bytes32 transactionHashId); event TransactionsSubmitted(bytes32 indexed transactionRoot, address producer, bytes32 indexed merkleTreeRoot, bytes32 indexed commitmentHash); event BlockCommitted(address blockProducer, bytes32 indexed previousBlockHash, uint256 indexed blockHeight, bytes32[] transactionRoots); event FraudCommitted(uint256 indexed previousTip, uint256 indexed currentTip, uint256 indexed fraudCode); event TokenIndex(address indexed token, uint256 indexed index); // STATE STORAGE // depositHashID => amount [later clearable in deposit] sload(keccak256(0, 64) + 5) mapping(bytes32 => uint256) public deposits; // STORAGE 0 // block height => withdrawal id => bool(has been withdrawn) [later clearable in withdraw] // lets treat block withdrawals as tx hash bytes(0) output (0) mapping(uint256 => mapping(bytes32 => bool)) public withdrawals; // STORAGE 1 // transactions hash => Ethereum block number included [later clearable in withdraw] mapping(bytes32 => uint256) public blockTransactionRoots; // STORAGE 2 // blockNumber => blockHash all block commitment hash headers Mapping actually better than array IMO, use tip as len mapping(uint256 => bytes32) public blockCommitments; // STORAGE 3 // tokens address => token ID number mapping(address => uint256) public tokens; // STORAGE 4 // number of tokens (1 for Ether ID 0) uint256 public numTokens = 1; // STORAGE 5 // the current side-chain block height/tip [changed in commitBlock / submitFraudProof] uint256 public blockTip; // STORAGE 6 // block producer (set to zero for permissionless, must be account) [changed in constructor / submitFraudProof] address public blockProducer; // STORAGE 7 // CONSTRUCTOR constructor(address producer) public { // compute genesis block hash address genesisProducer = address(0); // TODO low-priority set a clever previous block hash bytes32 previousBlockHash = bytes32(0); uint256 blockHeight = uint256(0); bytes32[] memory transactionRoots; bytes32 genesisBlockHash = keccak256(abi.encode(genesisProducer, previousBlockHash, blockHeight, GenesisBlockHeight, transactionRoots)); // STORAGE commit the genesis block hash header to storage as Zero block.. blockCommitments[GenesisBlockHeight] = genesisBlockHash; // STORAGE setup block producer blockProducer = producer; // Setup Ether token index emit TokenIndex(address(0), 1); // LOG emit all pertinent details of the Genesis block emit BlockCommitted(genesisProducer, previousBlockHash, blockHeight, transactionRoots); } // STATE Changing Methods function deposit(address account, address token, uint256 amount) external payable { // Compute deposit hash Identifier bytes32 depositHashId = keccak256(abi.encode(account, token, block.number)); // Assert amount is greater than Zero assert(amount > 0); // Handle transfer details if (token != address(0)) { assert(ERC20(token).allowance(msg.sender, address(this)) >= amount); // check allowance assert(ERC20(token).transferFrom(msg.sender, address(this), amount)); // transferFrom } else { assert(msg.value == amount); // commit ether transfer } // register token with an index if it isn't already if (token != address(0) && tokens[token] == 0) { // STORAGE register token with index tokens[token] = numTokens; // STORAGE MOD increase token index numTokens = ds_add(numTokens, 1); // LOG emit token registry index emit TokenIndex(token, numTokens); } // STORAGE notate deposit in storage deposits[depositHashId] = ds_add(deposits[depositHashId], amount); // Log essential deposit details emit DepositMade(account, token, amount); } function submitTransactions(bytes32 merkleTreeRoot, bytes calldata transactions) external { // require the sender is not a contract assembly { // Require if caller/msg.sender is a contract if gt(extcodesize(caller()), 0) { revert(0, 0) } // Calldata Max size enforcement (4m / 68) if gt(calldatasize(), MAX_TRANSACTIONS_SIZE) { revert(0, 0) } } // Commitment hash bytes32 commitmentHash = keccak256(transactions); // Construct Transaction Root Hash bytes32 transactionRoot = keccak256(abi.encode(msg.sender, merkleTreeRoot, commitmentHash)); // Assert this transactions blob cannot already exist assert(blockTransactionRoots[transactionRoot] == 0); // STORAGE notate transaction root in storage at a specified Ethereum block blockTransactionRoots[transactionRoot] = block.number; // LOG Transaction submitted, the original data emit TransactionsSubmitted(transactionRoot, msg.sender, merkleTreeRoot, commitmentHash); } function commitBlock(uint256 blockHeight, bytes32[] calldata transactionRoots) external payable { bytes32 previousBlockHash = blockCommitments[blockTip]; bytes32 blockHash = keccak256(abi.encode(msg.sender, previousBlockHash, blockHeight, block.number, transactionRoots)); // Assert require value be bond size assert(msg.value == BOND_SIZE); // Assert at least one root submission assert(transactionRoots.length > 0); // Assert at least one root submission assert(transactionRoots.length < TRANSACTION_ROOTS_MAX); // Assert the transaction roots exists for (uint256 transactionRootIndex = 0; transactionRootIndex < transactionRoots.length; transactionRootIndex = ds_add(transactionRootIndex, 1)) { // Transaction Root must Exist in State assert(blockTransactionRoots[transactionRoots[transactionRootIndex]] > 0); // add root expiry here.. // Assert transaction root is younger than 3 days, and block producer set, than only block producer can make the block if (block.number < ds_add(blockTransactionRoots[transactionRoots[transactionRootIndex]], SUBMISSION_DELAY) && blockProducer != address(0)) { assert(msg.sender == blockProducer); } } // Require block height must be 1 ahead of tip REVERT nicely (be forgiving) require(blockHeight == ds_add(blockTip, 1)); // STORAGE write block hash commitment to storage blockCommitments[blockHeight] = blockHash; // STORAGE set new block tip blockTip = blockHeight; // LOG emit all pertinant details in Log Data emit BlockCommitted(msg.sender, previousBlockHash, blockHeight, transactionRoots); } // Submit Fraud or withdrawal proofs (i.e. Implied Consensus Rule Enforcement) function submitProof(bytes calldata) external payable { assembly { // Assign all calldata into free memory, remove 4 byte signature and 64 bytes size/length data (68 bytes) // Note, We only write data to memory once, than reuse it for almost every function for better computational efficiency calldatacopy(Calldata_MemoryPosition, 68, calldatasize()) // Assign fresh memory pointer to Virtual Stack mpush(Stack_FreshMemory, add3(Calldata_MemoryPosition, calldatasize(), mul32(2))) // Handle Proof Type switch selectProofType() case 0 { // ProofType_MalformedBlock verifyBlockProof() } case 1 { // ProofType_MalformedTransaction // Check proof lengths for overflow verifyTransactionProofLengths(OneProof) // Verify Malformed Transaction Proof verifyTransactionProof(FirstProof, No_UTXOProofs, Not_Finalized) } case 2 { // ProofType_InvalidTransaction // Check proof lengths for overflow verifyTransactionProofLengths(OneProof) // Check for Invalid Transaction Sum Amount Totals // Check for HTLC Data Construction / Witness Signature Specification verifyTransactionProof(FirstProof, Include_UTXOProofs, Not_Finalized) } case 3 { // ProofType_InvalidTransactionInput // Check proof lengths for overflow verifyTransactionProofLengths(TwoProofs) // Check for Invalid UTXO Reference (i.e. Reference a UTXO that does not exist or is Invalid!) verifyTransactionProof(FirstProof, No_UTXOProofs, Not_Finalized) // Fraud Tx verifyTransactionProof(SecondProof, No_UTXOProofs, Not_Finalized) // Valid Tx // Select Input Type let firstInputType := selectInputType(selectInputSelected(FirstProof)) // Assert fraud input is not a Deposit Type (deposits are checked in verifyTransactionProof) assertOrInvalidProof(iszero(eq(firstInputType, InputType_Deposit)), ErrorCode_InvalidTypeDeposit) // Fraud Tx 0 Proof: Block Height, Root Index, Tx Index Selected by Metadata let firstMetadataBlockHeight, firstMetadataTransactionRootIndex, firstMetadataTransactionIndex, firstMetadataOutputIndex := selectMetadata( selectMetadataSelected(FirstProof)) // Ensure block heights are the same Metadata Block Height = Second Proof Block Height assertOrInvalidProof(eq(firstMetadataBlockHeight, selectBlockHeight(selectBlockHeader(SecondProof))), ErrorCode_InvalidBlockHeightReference) // Check transaction root index overflow Metadata Roots Index < Second Proof Block Roots Length assertOrFraud(lt(firstMetadataTransactionRootIndex, selectTransactionRootsLength(selectBlockHeader(SecondProof))), FraudCode_InvalidTransactionRootIndexOverflow) // Check transaction roots assertOrInvalidProof(eq(firstMetadataTransactionRootIndex, selectTransactionRootIndex(selectTransactionRoot(SecondProof))), ErrorCode_InvalidTransactionRootReference) // Check transaction index overflow // Second Proof is Leftish (false if Rightmost Leaf in Merkle Tree!) let secondProofIsLeftish := mstack(Stack_MerkleProofLeftish) // Enforce transactionIndexOverflow assertOrFraud(or( secondProofIsLeftish, lte(firstMetadataTransactionIndex, selectTransactionIndex(selectTransactionData(SecondProof))) // Or is most right! ), FraudCode_TransactionIndexOverflow) // Check transaction index assertOrInvalidProof(eq(firstMetadataTransactionIndex, selectTransactionIndex(selectTransactionData(SecondProof))), ErrorCode_InvalidTransactionIndexReference) // Check that second transaction isn't empty assertOrFraud(gt(constructTransactionLeafHash(selectTransactionData(SecondProof)), 0), FraudCode_TransactionHashZero) // Select Lengths and Use Them as Indexes (let Index = Length; lt; Index--) let transactionLeafData, inputsLength, secondOutputsLength, witnessesLength := selectAndVerifyTransactionDetails(selectTransactionData(SecondProof)) // Check output selection overflow assertOrFraud(lt(firstMetadataOutputIndex, secondOutputsLength), FraudCode_MetadataOutputIndexOverflow) // Second output index let secondOutputIndex := selectOutputIndex(selectTransactionData(SecondProof)) // Check outputs are the same assertOrInvalidProof(eq(firstMetadataOutputIndex, secondOutputIndex), ErrorCode_InvalidOutputIndexReference) // Select second output let secondOutput := selectOutputSelected(SecondProof) let secondOutputType := selectOutputType(secondOutput) // Check output is not spending withdrawal assertOrFraud(iszero(eq(secondOutputType, OutputType_withdrawal)), FraudCode_InvalidInputWithdrawalSpend) // Invalid Type Spend assertOrFraud(eq(firstInputType, secondOutputType), FraudCode_InvalidTypeReferenceMismatch) // Construct second transaction hash id let secondTransactionHashID := constructTransactionHashID(selectTransactionData(SecondProof)) // Construct Second UTXO ID Proof let secondUTXOProof := constructUTXOProof(secondTransactionHashID, selectOutputIndex(selectTransactionData(SecondProof)), selectOutputSelected(SecondProof)) let secondUTXOID := constructUTXOID(secondUTXOProof) // Select first UTXO ID let firstUTXOID := selectUTXOID(selectInputSelected(FirstProof)) // Check UTXOs are the same assertOrFraud(eq(firstUTXOID, secondUTXOID), FraudCode_InvalidUTXOHashReference) // Handle Change Input Enforcement if eq(selectOutputType(secondOutput), OutputType_Change) { // Output HTLC let length, amount, ownerAsWitnessIndex, tokenID := selectAndVerifyOutput(secondOutput, True) // Return Witness Recovery // Return Witness Signature let outputWitnessSignature := selectWitnessSignature(selectTransactionWitnesses(selectTransactionData(SecondProof)), ownerAsWitnessIndex) // Construct Second Transaction Hash ID let outputTransactionHashID := constructTransactionHashID(selectTransactionData(SecondProof)) // Get Witness Signature let outputWitnessAddress := ecrecoverPacked(outputTransactionHashID, outputWitnessSignature) // Spender Witness Recovery // Select First Proof Witness Index from Input let unused1, unused2, spenderWitnessIndex := selectAndVerifyInputUTXO(selectInputSelected(FirstProof), TransactionLengthMax) // Spender Witness Signature let spenderWitnessSignature := selectWitnessSignature(selectTransactionWitnesses(selectTransactionData(FirstProof)), spenderWitnessIndex) // Construct First Tx ID let spenderTransactionHashID := constructTransactionHashID(selectTransactionData(FirstProof)) // Spender Witness Address let spenderWitnessAddress := ecrecoverPacked(spenderTransactionHashID, spenderWitnessSignature) // Assert Spender must be Output Witness assertOrFraud(eq(spenderWitnessAddress, outputWitnessAddress), FraudCode_InvalidChangeInputSpender) } // Handle HTLC Input Enforcement if eq(selectOutputType(secondOutput), OutputType_HTLC) { // Output HTLC let length, amount, owner, tokenID, digest, expiry, returnWitnessIndex := selectAndVerifyOutputHTLC(secondOutput, TransactionLengthMax) // Handle Is HTLC Expired, must be returnWitness if gte(selectBlockHeight(selectBlockHeader(FirstProof)), expiry) { // Return Witness Recovery // Return Witness Signature let returnWitnessSignature := selectWitnessSignature(selectTransactionWitnesses(selectTransactionData(SecondProof)), returnWitnessIndex) // Construct Second Transaction Hash ID let returnTransactionHashID := constructTransactionHashID(selectTransactionData(SecondProof)) // Get Witness Signature let returnWitnessAddress := ecrecoverPacked(returnTransactionHashID, returnWitnessSignature) // Spender Witness Recovery // Select First Proof Witness Index from Input let unused1, unused2, inputWitnessIndex, preImage := selectAndVerifyInputHTLC(selectInputSelected(FirstProof), TransactionLengthMax) // Spender Witness Signature let spenderWitnessSignature := selectWitnessSignature(selectTransactionWitnesses(selectTransactionData(FirstProof)), inputWitnessIndex) // Construct First Tx ID let spenderTransactionHashID := constructTransactionHashID(selectTransactionData(FirstProof)) // Spender Witness Address let spenderWitnessAddress := ecrecoverPacked(spenderTransactionHashID, spenderWitnessSignature) // Assert Spender must be Return Witness! assertOrFraud(eq(spenderWitnessAddress, returnWitnessAddress), FraudCode_InvalidReturnWitnessNotSpender) } } } case 4 { // ProofType_InvalidTransactionDoubleSpend // Check proof lengths for overflow verifyTransactionProofLengths(TwoProofs) // Check for Invalid Transaction Double Spend (Same Input Twice) verifyTransactionProof(FirstProof, No_UTXOProofs, Not_Finalized) // Accused Fraud Tx verifyTransactionProof(SecondProof, No_UTXOProofs, Not_Finalized) // Valid Tx // Get transaction data zero and 1 let transaction0 := selectTransactionData(FirstProof) let transaction1 := selectTransactionData(SecondProof) // Block Height Difference let blockHeightDifference := iszero(eq(selectBlockHeight(selectBlockHeader(FirstProof)), selectBlockHeight(selectBlockHeader(SecondProof)))) // Transaction Root Difference let transactionRootIndexDifference := iszero(eq(selectTransactionRootIndex(selectTransactionRoot(FirstProof)), selectTransactionRootIndex(selectTransactionRoot(SecondProof)))) // Transaction Index Difference let transactionIndexDifference := iszero(eq(selectTransactionIndex(transaction0), selectTransactionIndex(transaction1))) // Transaction Input Index Difference let transactionInputIndexDifference := iszero(eq(selectInputIndex(transaction0), selectInputIndex(transaction1))) // Check that the transactions are different assertOrInvalidProof(or( or(blockHeightDifference, transactionRootIndexDifference), or(transactionIndexDifference, transactionInputIndexDifference) // Input Index is Different ), ErrorCode_InvalidTransactionComparison) // Assert Inputs are Different OR FRAUD Double Spend! assertOrFraud(iszero(eq(selectInputSelectedHash(FirstProof), selectInputSelectedHash(SecondProof))), FraudCode_InputDoubleSpend) } case 5 { // ProofType_UserWithdrawal // Check proof lengths for overflow verifyTransactionProofLengths(OneProof) // Verify transaction proof verifyTransactionProof(FirstProof, No_UTXOProofs, Is_Finalized) // Run the withdrawal Sequence let output := selectOutputSelected(FirstProof) let length, outputAmount, outputOwner, outputTokenID := selectAndVerifyOutput(output, False) // Check Proof Type is Correct assertOrInvalidProof(eq(selectOutputType(output), 1), ErrorCode_InvalidWithdrawalOutputType) // Check Proof Type is Correct assertOrInvalidProof(eq(outputOwner, caller()), ErrorCode_InvalidWithdrawalOwner) // Get transaction details let transactionRootIndex := selectTransactionRootIndex(selectTransactionRoot(FirstProof)) let transactionLeafHash := constructTransactionLeafHash(selectTransactionData(FirstProof)) let outputIndex := selectOutputIndex(selectTransactionData(FirstProof)) let blockHeight := selectBlockHeight(selectBlockHeader(FirstProof)) // Construct withdrawal hash id let withdrawalHashID := constructWithdrawalHashID(transactionRootIndex, transactionLeafHash, outputIndex) // This output has not been withdrawn yet! assertOrInvalidProof(eq(getWithdrawals(blockHeight, withdrawalHashID), False), ErrorCode_WithdrawalAlreadyHappened) // withdrawal Token let withdrawalToken := selectWithdrawalToken(FirstProof) // Transfer amount out transfer(outputAmount, outputTokenID, withdrawalToken, outputOwner) // Set withdrawals setWithdrawals(blockHeight, withdrawalHashID, True) // Construct Log Data for withdrawal mstore(mul32(1), withdrawalToken) mstore(mul32(2), outputAmount) mstore(mul32(3), transactionRootIndex) mstore(mul32(4), outputIndex) mstore(mul32(5), constructTransactionHashID(selectTransactionData(FirstProof))) // add transactionHash // Log withdrawal data and topics log4(mul32(1), mul32(5), WithdrawalEventTopic, outputOwner, blockHeight, transactionLeafHash) } case 6 { // ProofType_BondWithdrawal // Select proof block header let blockHeader := selectBlockHeader(FirstProof) // Setup block producer withdrawal hash ID (i.e. Zero) let withdrawalHashID := 0 // Transaction Leaf Hash (bond withdrawal hash is zero) let transactionLeafHash := 0 // Block Producer let blockProducer := caller() // block height let blockHeight := selectBlockHeight(blockHeader) // Verify block header proof is finalized! verifyBlockHeader(blockHeader, Is_Finalized) // Assert Caller is Block Producer assertOrInvalidProof(eq(selectBlockProducer(blockHeader), blockProducer), ErrorCode_BlockProducerNotCaller) // Assert Block Bond withdrawal has not been Made! assertOrInvalidProof(eq(getWithdrawals(blockHeight, withdrawalHashID), False), ErrorCode_BlockBondAlreadyWithdrawn) // Transfer Bond Amount back to Block Producer transfer(BOND_SIZE, EtherToken, EtherToken, blockProducer) // Set withdrawal setWithdrawals(blockHeight, withdrawalHashID, True) // Construct Log Data for withdrawal mstore(mul32(1), EtherToken) mstore(mul32(2), BOND_SIZE) mstore(mul32(3), 0) mstore(mul32(4), 0) // Log withdrawal data and topics log4(mul32(1), mul32(4), WithdrawalEventTopic, blockProducer, blockHeight, transactionLeafHash) } // Invalid Proof Type default { assertOrInvalidProof(0, ErrorCode_InvalidProofType) } // Ensure Execution Stop stop() // // VERIFICATION METHODS // For verifying proof data and determine fraud or validate withdrawals // // Verify Invalid Block Proof function verifyBlockProof() { /* Block Construction Proof: - Type - Lengths - BlockHeader - TransactionRootHeader - TransactionRootData */ // Start Proof Position past Proof Type let proofMemoryPosition := safeAdd(Calldata_MemoryPosition, mul32(1)) // Select Proof Lengths let blockHeaderLength := load32(proofMemoryPosition, 0) let transactionRootLength := load32(proofMemoryPosition, 1) let transactionsLength := load32(proofMemoryPosition, 2) // Verify the Lengths add up to calldata size verifyProofLength(add4(mul32(3), blockHeaderLength, transactionRootLength, transactionsLength)) // Select Proof Memory Positions let blockHeader := selectBlockHeader(FirstProof) let transactionRoot := selectTransactionRoot(FirstProof) // Transactions are After Transaction Root, Plus 64 Bytes (for bytes type metadata from ABI Encoding) let transactions := safeAdd(transactionRoot, transactionRootLength) // Verify Block Header verifyBlockHeader(blockHeader, Not_Finalized) // Verify Transaction Root Header verifyTransactionRootHeader(blockHeader, transactionRoot) // Get solidity abi encoded length for transactions blob let transactionABILength := selectTransactionABILength(transactions) // Check for overflow assertOrInvalidProof(lt(transactionABILength, transactionsLength), ErrorCode_InvalidTransactionsABILengthOverflow) // Verify Transaction Hash Commitment verifyTransactionRootData(transactionRoot, selectTransactionABIData(transactions), transactionABILength) } // Verify proof length for overflows function verifyProofLength(proofLengthWithoutType) { let calldataMetadataSize := 68 let typeSize := mul32(1) let computedCalldataSize := add3(calldataMetadataSize, typeSize, proofLengthWithoutType) // Check for overflow assertOrInvalidProof(eq(computedCalldataSize, calldatasize()), ErrorCode_ProofLengthOverflow) } // Verify Block Header function verifyBlockHeader(blockHeader, assertFinalized) { /* - Block Header: - blockProducer [32 bytes] -- padded address - previousBlockHash [32 bytes] - blockHeight [32 bytes] - ethereumBlockNumber [32 bytes] - transactionRoots [64 + dynamic bytes] */ // Construct blockHash from Block Header let blockHash := constructBlockHash(blockHeader) // Select BlockHeight from Memory let blockHeight := selectBlockHeight(blockHeader) // Previous block hash let previousBlockHash := selectPreviousBlockHash(blockHeader) // Transaction Roots Length let transactionRootsLength := selectTransactionRootsLength(blockHeader) // Assert Block is not Genesis assertOrInvalidProof(gt(blockHeight, GenesisBlockHeight), ErrorCode_BlockHeightUnderflow) // Assert Block Height is Valid (i.e. before tip) assertOrInvalidProof(lte(blockHeight, getBlockTip()), ErrorCode_BlockHeightOverflow) // Assert Previous Block Hash assertOrInvalidProof(eq(getBlockCommitments(safeSub(blockHeight, 1)), previousBlockHash), ErrorCode_InvalidPreviousBlockHash) // Transactions roots length underflow assertOrInvalidProof(gt(transactionRootsLength, 0), ErrorCode_TransactionRootsLengthUnderflow) // Assert Block Commitment Exists assertOrInvalidProof(eq(getBlockCommitments(blockHeight), blockHash), ErrorCode_BlockHashNotFound) // If requested, Assert Block is Finalized if eq(assertFinalized, 1) { assertOrInvalidProof(gte( number(), safeAdd(selectEthereumBlockNumber(blockHeader), FINALIZATION_DELAY) // ethBlock + delay ), ErrorCode_BlockNotFinalized) } // If requested, Assert Block is Not Finalized if iszero(assertFinalized) { // underflow protected! assertOrInvalidProof(lt( number(), // ethereumBlockNumber safeAdd(selectEthereumBlockNumber(blockHeader), FINALIZATION_DELAY) // finalization delay ), ErrorCode_BlockFinalized) } } // Verify Transaction Root Header (Assume Block Header is Valid) function verifyTransactionRootHeader(blockHeader, transactionRoot) { /* - Block Header: - blockProducer [32 bytes] -- padded address - previousBlockHash [32 bytes] - blockHeight [32 bytes] - ethereumBlockNumber [32 bytes] - transactionRoots [64 + dynamic bytes] - Transaction Root Header: - transactionRootProducer [32 bytes] -- padded address - transactionRootMerkleTreeRoot [32 bytes] - transactionRootCommitmentHash [32 bytes] - transactionRootIndex [32 bytes] */ // Get number of transaction roots let transactionRootsLength := selectTransactionRootsLength(blockHeader) // Get transaction root index let transactionRootIndex := selectTransactionRootIndex(transactionRoot) // Assert root index is not overflowing assertOrInvalidProof(lt(transactionRootIndex, transactionRootsLength), ErrorCode_TransactionRootIndexOverflow) // Assert root invalid overflow assertOrInvalidProof(lt(transactionRootsLength, TRANSACTION_ROOTS_MAX), ErrorCode_TransactionRootsLengthOverflow) // Construct transaction root let transactionRootHash := keccak256(transactionRoot, mul32(3)) // Assert transaction root index is correct! assertOrInvalidProof(eq( transactionRootHash, load32(blockHeader, safeAdd(6, transactionRootIndex)) // blockHeader transaction root ), ErrorCode_TransactionRootHashNotInBlockHeader) } // Construct commitment hash function constructCommitmentHash(transactions, transactionsLength) -> commitmentHash { commitmentHash := keccak256(transactions, transactionsLength) } function selectTransactionABIData(transactionsABIEncoded) -> transactions { transactions := safeAdd(transactionsABIEncoded, mul32(2)) } function selectTransactionABILength(transactionsABIEncoded) -> transactionsLength { transactionsLength := load32(transactionsABIEncoded, 1) } // Verify Transaction Root Data is Valid (Assuming Transaction Root Valid) function verifyTransactionRootData(transactionRoot, transactions, transactionsLength) { // Select Transaction Data Root let commitmentHash := selectCommitmentHash(transactionRoot) // Check provided transactions data! THIS HASH POSITION MIGHT BE WRONG due to Keccak Encoding let constructedCommitmentHash := constructCommitmentHash(transactions, transactionsLength) // Assert or Invalid Data Provided assertOrInvalidProof(eq( commitmentHash, constructedCommitmentHash ), ErrorCode_TransactionRootHashInvalid) // Select Merkle Tree Root Provided let merkleTreeRoot := selectMerkleTreeRoot(transactionRoot) // Assert committed root must be the same as computed root! // THIS HASH MIGHT BE WRONG (hash POS check) assertOrFraud(eq( merkleTreeRoot, constructMerkleTreeRoot(transactions, transactionsLength) ), FraudCode_InvalidMerkleTreeRoot) } // Verify Transaction Proof function verifyTransactionProof(proofIndex, includeUTXOProofs, assertFinalized) { /* Transaction Proof: - Lengths - BlockHeader - TransactionRootHeader - TransactionMerkleProof - TransactionData - TransactionUTXOProofs */ // we are on proof 1 if gt(proofIndex, 0) { // Notate across global stack we are on proof 1 validation mpush(Stack_ProofNumber, proofIndex) } // Select Memory Positions let blockHeader := selectBlockHeader(proofIndex) let transactionRoot := selectTransactionRoot(proofIndex) let transactionMerkleProof := selectTransactionMerkleProof(proofIndex) let transactionData := selectTransactionData(proofIndex) // Verify Block Header verifyBlockHeader(blockHeader, assertFinalized) // Verify Transaction Root Header verifyTransactionRootHeader(blockHeader, transactionRoot) // Verify Transaction Leaf verifyTransactionLeaf(transactionRoot, transactionData, transactionMerkleProof) // Construct Transaction Leaf Hash (Again :( let transactionLeafHash := constructTransactionLeafHash(transactionData) // If transaction hash is not zero hash, than go and verify it! if gt(transactionLeafHash, 0) { // Transaction UTXO Proofs let transactionUTXOProofs := 0 // Include UTXO Proofs if gt(includeUTXOProofs, 0) { transactionUTXOProofs := selectTransactionUTXOProofs(proofIndex) } // Verify Transaction Data verifyTransactionData(transactionData, transactionUTXOProofs) } // Ensure We are now validating proof 0 again mpop(Stack_ProofNumber) } // Verify Transaction Leaf (Assume Transaction Root Header is Valid) function verifyTransactionLeaf(transactionRoot, transactionData, merkleProof) { /* - Transaction Root Header: - transactionRootProducer [32 bytes] -- padded address - transactionRootMerkleTreeRoot [32 bytes] - transactionRootCommitmentHash [32 bytes] - transactionRootIndex [32 bytes] - Transaction Data: - input index [32 bytes] -- padded uint8 - output index [32 bytes] -- padded uint8 - witness index [32 bytes] -- padded uint8 - transactionInputsLength [32 bytes] -- padded uint8 - transactionIndex [32 bytes] -- padded uint32 - transactionLeafData [dynamic bytes] - Transaction Merkle Proof: - oppositeTransactionLeaf [32 bytes] - merkleProof [64 + dynamic bytes] */ // Select Merkle Tree Root let merkleTreeRoot := selectMerkleTreeRoot(transactionRoot) // Select Merkle Proof Height let treeHeight := selectMerkleTreeHeight(merkleProof) // Select Tree (ahead of Array length) let treeMemoryPosition := selectMerkleTree(merkleProof) // Select Transaction Index let transactionIndex := selectTransactionIndex(transactionData) // Assert Valid Merkle Tree Height (i.e. below Maximum) assertOrInvalidProof(lt(treeHeight, MerkleTreeHeightMaximum), ErrorCode_MerkleTreeHeightOverflow) // Select computed hash, initialize with opposite leaf hash let computedHash := selectOppositeTransactionLeaf(merkleProof) // Assert Leaf Hash is base of Merkle Proof assertOrInvalidProof(eq( constructTransactionLeafHash(transactionData), // constructed computedHash // proof provided ), ErrorCode_TransactionLeafHashInvalid) // Clean Rightmost (leftishness) Detection Var (i.e. any previous use of this Stack Position) mpop(Stack_MerkleProofLeftish) // Iterate Through Merkle Proof Depths // https://crypto.stackexchange.com/questions/31871/what-is-the-canonical-way-of-creating-merkle-tree-branches for { let depth := 0 } lt(depth, treeHeight) { depth := safeAdd(depth, 1) } { // get the leaf hash let proofLeafHash := load32(treeMemoryPosition, depth) // Determine Proof Direction the merkle brand left: tx index % 2 == 0 switch eq(smod(transactionIndex, 2), 0) // Direction is left branch case 1 { mstore(mul32(1), computedHash) mstore(mul32(2), proofLeafHash) // Leftishness Detected in Proof, This is not Rightmost mpush(Stack_MerkleProofLeftish, True) } // Direction is right branch case 0 { mstore(mul32(1), proofLeafHash) mstore(mul32(2), computedHash) } default { revert(0, 0) } // Direction is Invalid, Ensure no other cases! // Construct Depth Hash computedHash := keccak256(mul32(1), mul32(2)) // Shift transaction index right by 1 transactionIndex := shr(1, transactionIndex) } // Assert constructed merkle tree root is provided merkle tree root, or else, Invalid Inclusion! assertOrInvalidProof(eq(computedHash, merkleTreeRoot), ErrorCode_MerkleTreeRootInvalid) } // Verify Transaction Input Metadata function verifyTransactionInputMetadata(blockHeader, rootHeader, metadata, blockTip, inputIndex) { // Block Height let metadataBlockHeight, metadataTransactionRootIndex, metadataTransactionIndex, metadataOutputIndex := selectMetadata(metadata) // Select Transaction Block Height let blockHeight := selectBlockHeight(blockHeader) let transactionRootIndex := selectTransactionRootIndex(rootHeader) // Assert input index overflow (i.e. metadata does not exist) assertOrFraud(lt(inputIndex, mstack(Stack_MetadataLength)), FraudCode_MetadataReferenceOverflow) // Assert Valid Metadata Block height assertOrFraud(gt(metadataBlockHeight, 0), FraudCode_MetadataBlockHeightUnderflow) // Assert Valid Metadata Block height assertOrFraud(lt(metadataTransactionRootIndex, TRANSACTION_ROOTS_MAX), FraudCode_InvalidTransactionRootIndexOverflow) // Cannot spend past it's own root index (i.e. tx 1 cant spend tx 2 at root index + 1) // Can't be past block tip or past it's own block (can't reference the future) assertOrFraud(lte(metadataBlockHeight, blockTip), FraudCode_MetadataBlockHeightOverflow) // Check overflow of current block height assertOrFraud(lte(metadataBlockHeight, blockHeight), FraudCode_MetadataBlockHeightOverflow) // Can't reference in the future!! // If Meta is Ref. Block Height of Itself, and Ref. Root Index > Itself, that's Fraud! assertOrFraud(or(iszero(eq(metadataBlockHeight, blockHeight)), // block height is different lte(metadataTransactionRootIndex, transactionRootIndex)), // metadata root index <= self root index FraudCode_InvalidTransactionRootIndexOverflow) // Need to cover referencing a transaction index in the same block, but past this tx // txs must always reference txs behind it, or else it's fraud // Check Output Index assertOrFraud(lt(metadataOutputIndex, TransactionLengthMax), FraudCode_MetadataOutputIndexOverflow) } // Verify HTLC Usage function verifyHTLCData(blockHeader, input, utxoProof) { /* - Transaction UTXO Data: - transactionHashId [32 bytes] - outputIndex [32 bytes] -- padded uint8 - type [32 bytes] -- padded uint8 - amount [32 bytes] - owner [32 bytes] -- padded address or unit8 - tokenID [32 bytes] -- padded uint32 - [HTLC Data]: - digest [32 bytes] - expiry [32 bytes] -- padded 4 bytes - return witness index [32 bytes] -- padded 1 bytes */ // Select Transaction Input data let length, utxoID, witnessReference, preImage := selectAndVerifyInputHTLC(input, TransactionLengthMax) // Select Transaction Block Height let blockHeight := selectBlockHeight(blockHeader) // Select Digest and Expiry from UTXO Proof (Assumed to be Valid) let digest := load32(utxoProof, 6) let expiry := load32(utxoProof, 7) // If not expired, and digest correct, expired case gets handled in Comparison proofs if lt(blockHeight, expiry) { // Assert Digest is Valid assertOrFraud(eq(digest, constructHTLCDigest(preImage)), FraudCode_InvalidHTLCDigest) } } // Verify Transaction Length (minimum and maximum) function verifyTransactionLength(transactionLength) { // Assert transaction length is not too short assertOrFraud(gt(transactionLength, TransactionSizeMinimum), FraudCode_TransactionLengthUnderflow) // Assert transaction length is not too long assertOrFraud(lte(transactionLength, TransactionSizeMaximum), FraudCode_TransactionLengthOverflow) } // Verify Transaction Data (Metadata, Inputs, Outputs, Witnesses) function verifyTransactionData(transactionData, utxoProofs) { // Verify Transaction Length verifyTransactionLength(selectTransactionLength(transactionData)) // Select and Verify Lengths and Use Them as Indexes (let Index = Length; lt; Index--) let memoryPosition, inputsLength, outputsLength, witnessesLength := selectAndVerifyTransactionDetails(transactionData) // Memory Stack so we don't blow the stack! mpush(Stack_InputsSum, 0) // Total Transaction Input Sum mpush(Stack_OutputsSum, 0) // Total Transaction Output Sum mpush(Stack_Metadata, selectTransactionMetadata(transactionData)) // Metadata Memory Position mpush(Stack_Witnesses, selectTransactionWitnesses(transactionData)) // Witnesses Memory Position mpush(Stack_BlockTip, getBlockTip()) // GET blockTip() from Storage mpush(Stack_UTXOProofs, safeAdd(utxoProofs, mul32(1))) // UTXO Proofs Memory Position mpush(Stack_TransactionHashID, constructTransactionHashID(transactionData)) // Construct Transaction Hash ID mpush(Stack_MetadataLength, selectTransactionMetadataLength(transactionData)) // Push summing tokens if gt(utxoProofs, 0) { mpush(Stack_SummingToken, mload(utxoProofs)) // load summing token mpush(Stack_SummingTokenID, getTokens(mload(utxoProofs))) // load summing token } // Set Block Header Position (on First Proof) if iszero(mstack(Stack_ProofNumber)) { // Proof 0 Block Header Position mpush(Stack_BlockHeader, selectBlockHeader(FirstProof)) // Proof 0 Block Header Position mpush(Stack_RootHeader, selectTransactionRoot(FirstProof)) // Return Stack Offset: (No Offset) First Transaction mpush(Stack_SelectionOffset, 0) // Proof 0 Transaction Root Producer mpush(Stack_RootProducer, selectRootProducer(selectTransactionRoot(FirstProof))) } // If Second Transaction Processed, Set Block Header Position (On Second Proof) if gt(mstack(Stack_ProofNumber), 0) { // Proof 1 Block Header Position mpush(Stack_BlockHeader, selectBlockHeader(SecondProof)) // Proof 0 Block Header Position mpush(Stack_RootHeader, selectTransactionRoot(SecondProof)) // Return Stack Offset: Offset Memory Stack for Second Proof mpush(Stack_SelectionOffset, SelectionStackOffsetSize) // 4 => Metadata, Input, Output, Witness Position // Proof 1 Transaction Root Position mpush(Stack_RootProducer, selectRootProducer(selectTransactionRoot(SecondProof))) } // Increase memory position past length Specifiers memoryPosition := safeAdd(memoryPosition, TransactionLengthSize) // Transaction Proof Stack Return // 8) Metadata Tx 1, 9) Input Tx 1, 10) Output, 11) Witness Memory Position // 12) Metadata Tx 2, 13) Input Tx 2, 14) Output, 15) Witness Memory Position // VALIDATE Inputs Index from Inputs Length -> 0 for { mpush(Stack_Index, 0) } lt(mstack(Stack_Index), inputsLength) { mpush(Stack_Index, safeAdd(mstack(Stack_Index), 1)) } { // Check if This is Input Requested if eq(mstack(Stack_Index), selectInputSelectionIndex(transactionData)) { // Store Metadata Position in Stack mpush(safeAdd(Stack_MetadataSelected, mstack(Stack_SelectionOffset)), combineUint32(mstack(Stack_Metadata), memoryPosition, mstack(Stack_Index), 0)) } // Select Input Type switch selectInputType(memoryPosition) case 0 { // InputType UTXO // Increase Memory pointer let length, utxoID, witnessReference := selectAndVerifyInputUTXO(memoryPosition, witnessesLength) // If UTXO/Deposit Proofs provided if gt(utxoProofs, 0) { let outputAmount, outputOwner, tokenID := selectAndVerifyUTXOAmountOwner(mstack(Stack_UTXOProofs), 0, utxoID) // Increase input sum if eq(tokenID, mstack(Stack_SummingTokenID)) { mpush(Stack_InputsSum, safeAdd(mstack(Stack_InputsSum), outputAmount)) } // Increase UTXO proof memory position mpush(Stack_UTXOProofs, safeAdd(mstack(Stack_UTXOProofs), UTXOProofSize)) // Verify transaction witness verifyTransactionWitness(selectWitnessSignature(mstack(Stack_Witnesses), witnessReference), mstack(Stack_TransactionHashID), outputOwner, mstack(Stack_RootProducer)) } // cannot select metadata that does not exist // assertOrFraud(lt(inputIndex, mstack(Stack_MetadataLength)), // FraudCode_TransactionInputMetadataOverflow) // Verify metadata for this input (metadata position, block tip) verifyTransactionInputMetadata(mstack(Stack_BlockHeader), mstack(Stack_RootHeader), mstack(Stack_Metadata), mstack(Stack_BlockTip), mstack(Stack_Index)) // Increase metadata memory position mpush(Stack_Metadata, safeAdd(mstack(Stack_Metadata), MetadataSize)) // Push Input Length mpush(safeAdd(Stack_SelectedInputLength, mstack(Stack_SelectionOffset)), length) // increase Memory Position memoryPosition := safeAdd(memoryPosition, length) } case 1 { // InputType DEPOSIT (verify deposit owner / details witnesses etc) // Select Input Deposit (Asserts Deposit > 0) let length, depositHashID, witnessReference := selectAndVerifyInputDeposit(memoryPosition, witnessesLength) // If UTXO Proofs provided if gt(utxoProofs, 0) { // Owner let depositOwner := selectInputDepositOwner(mstack(Stack_UTXOProofs)) // Constructed Deposit hash let constructedDepositHashID := constructDepositHashID(mstack(Stack_UTXOProofs)) // Check Deposit Hash ID against proof assertOrInvalidProof(eq(depositHashID, constructedDepositHashID), ErrorCode_InvalidDepositProof) // Verify transaction witness verifyTransactionWitness(selectWitnessSignature(mstack(Stack_Witnesses), witnessReference), mstack(Stack_TransactionHashID), depositOwner, mstack(Stack_RootProducer)) // Deposit Token let depositToken := selectInputDepositToken(mstack(Stack_UTXOProofs)) // Increase Input Amount if eq(depositToken, mstack(Stack_SummingToken)) { mpush(Stack_InputsSum, safeAdd(mstack(Stack_InputsSum), getDeposits(depositHashID))) } // Increase UTXO/Deposit proof memory position mpush(Stack_UTXOProofs, safeAdd(mstack(Stack_UTXOProofs), DepositProofSize)) } // Push Input Length mpush(safeAdd(Stack_SelectedInputLength, mstack(Stack_SelectionOffset)), length) // Increase Memory Position memoryPosition := safeAdd(memoryPosition, length) } case 2 { // InputType HTLC // Select HTLC Input let length, utxoID, witnessReference, preImage := selectAndVerifyInputHTLC( memoryPosition, witnessesLength) // If UTXO Proofs provided if gt(utxoProofs, 0) { let outputAmount, outputOwner, tokenID := selectAndVerifyUTXOAmountOwner( mstack(Stack_UTXOProofs), 2, utxoID) // Verify HTLC Data verifyHTLCData(mstack(Stack_BlockHeader), memoryPosition, mstack(Stack_UTXOProofs)) // Verify transaction witness verifyTransactionWitness(selectWitnessSignature(mstack(Stack_Witnesses), witnessReference), mstack(Stack_TransactionHashID), outputOwner, mstack(Stack_RootProducer)) // Increase input sum if eq(tokenID, mstack(Stack_SummingTokenID)) { mpush(Stack_InputsSum, safeAdd(mstack(Stack_InputsSum), outputAmount)) } // Increase UTXO proof memory position mpush(Stack_UTXOProofs, safeAdd(mstack(Stack_UTXOProofs), UTXOProofSize)) } // Verify metadata for this input (metadata position, block tip) verifyTransactionInputMetadata(mstack(Stack_BlockHeader), mstack(Stack_RootHeader), mstack(Stack_Metadata), mstack(Stack_BlockTip), mstack(Stack_Index)) // Increase metadata memory position mpush(Stack_Metadata, safeAdd(mstack(Stack_Metadata), MetadataSize)) // Push Input Length mpush(safeAdd(Stack_SelectedInputLength, mstack(Stack_SelectionOffset)), length) // Increase Memory Position memoryPosition := safeAdd(memoryPosition, length) } case 3 { // InputType CHANGE UNSPENT // HTLC input let length, utxoID, witnessReference := selectAndVerifyInputUTXO(memoryPosition, witnessesLength) // If UTXO Proofs provided if gt(utxoProofs, 0) { let outputAmount, outputOwner, tokenID := selectAndVerifyUTXOAmountOwner(mstack(Stack_UTXOProofs), OutputType_Change, utxoID) // witness signatures get enforced in invalidTransactionInput // Increase input sum if eq(tokenID, mstack(Stack_SummingTokenID)) { mpush(Stack_InputsSum, safeAdd(mstack(Stack_InputsSum), outputAmount)) } // Increase UTXO proof memory position mpush(Stack_UTXOProofs, safeAdd(mstack(Stack_UTXOProofs), UTXOProofSize)) } // Verify metadata for this input (metadata position, block tip) verifyTransactionInputMetadata(mstack(Stack_BlockHeader), mstack(Stack_RootHeader), mstack(Stack_Metadata), mstack(Stack_BlockTip), mstack(Stack_Index)) // Increase metadata memory position mpush(Stack_Metadata, safeAdd(mstack(Stack_Metadata), MetadataSize)) // Push Input Length mpush(safeAdd(Stack_SelectedInputLength, mstack(Stack_SelectionOffset)), length) // Increase Memory Position memoryPosition := safeAdd(memoryPosition, length) } // Assert fraud Invalid Input Type default { assertOrFraud(0, FraudCode_InvalidTransactionInputType) } // Increase Memory Pointer for 1 byte Type memoryPosition := safeAdd(memoryPosition, TypeSize) } // Index from Outputs Length -> 0 for { mpush(Stack_Index, 0) } lt(mstack(Stack_Index), outputsLength) { mpush(Stack_Index, safeAdd(mstack(Stack_Index), 1)) } { // Check if input is requested if eq(mstack(Stack_Index), selectOutputSelectionIndex(transactionData)) { // Store Output Memory Position in Stack mpush(safeAdd(Stack_OutputSelected, mstack(Stack_SelectionOffset)), memoryPosition) } // Select Output Type switch selectOutputType(memoryPosition) case 0 { // OutputType UTXO // Increase Memory pointer let length, amount, owner, tokenID := selectAndVerifyOutput(memoryPosition, False) // Increase total output sum if eq(tokenID, mstack(Stack_SummingTokenID)) { mpush(Stack_OutputsSum, safeAdd(mstack(Stack_OutputsSum), amount)) } // Increase Memory pointer memoryPosition := safeAdd(length, memoryPosition) } case 1 { // OutputType withdrawal // Increase Memory pointer let length, amount, owner, tokenID := selectAndVerifyOutput(memoryPosition, False) // Increase total output sum if eq(tokenID, mstack(Stack_SummingTokenID)) { mpush(Stack_OutputsSum, safeAdd(mstack(Stack_OutputsSum), amount)) } // Increase Memory pointer memoryPosition := safeAdd(length, memoryPosition) } case 2 { // OutputType HTLC // Increase Memory pointer let length, amount, owner, tokenID, digest, expiry, returnWitness := selectAndVerifyOutputHTLC(memoryPosition, witnessesLength) // Check expiry is greater than its own block header assertOrFraud(gt(expiry, selectBlockHeight(mstack(Stack_BlockHeader))), FraudCode_OutputHTLCExpiryUnderflow) // Increase total output sum if eq(tokenID, mstack(Stack_SummingTokenID)) { mpush(Stack_OutputsSum, safeAdd(mstack(Stack_OutputsSum), amount)) } // Increase Memory pointer memoryPosition := safeAdd(length, memoryPosition) } case 3 { // OutputType CHANGE UNSPENT // Increase Memory pointer let length, amount, witnessReference, tokenID := selectAndVerifyOutput(memoryPosition, True) // Invalid Witness Reference out of bounds assertOrFraud(lt(witnessReference, witnessesLength), FraudCode_TransactionOutputWitnessReferenceOverflow) // Increase total output sum if eq(tokenID, mstack(Stack_SummingTokenID)) { mpush(Stack_OutputsSum, safeAdd(mstack(Stack_OutputsSum), amount)) } // Increase Memory pointer memoryPosition := safeAdd(length, memoryPosition) } // Assert fraud Invalid Input Type default { assertOrFraud(0, FraudCode_InvalidTransactionOutputType) } // Increase Memory Pointer for 1 byte Type memoryPosition := safeAdd(memoryPosition, TypeSize) } // Assert Transaction Total Output Sum <= Total Input Sum if gt(utxoProofs, 0) { assertOrFraud(eq(mstack(Stack_OutputsSum), mstack(Stack_InputsSum)), FraudCode_TransactionSumMismatch) } // Iterate from Witnesses Length -> 0 for { mpush(Stack_Index, 0) } lt(mstack(Stack_Index), witnessesLength) { mpush(Stack_Index, safeAdd(mstack(Stack_Index), 1)) } { // check if input is requested if eq(mstack(Stack_Index), selectWitnessSelectionIndex(transactionData)) { // Store Witness Memory Position in Stack mpush(safeAdd(Stack_WitnessSelected, mstack(Stack_SelectionOffset)), mstack(Stack_Witnesses)) } // Increase witness memory position mpush(Stack_Witnesses, safeAdd(mstack(Stack_Witnesses), WitnessSize)) } // Check Transaction Length for Validity based on Computed Lengths // Get Leaf Size details let unsignedTransactionData, metadataSize, witnessesSize, witnessLength := selectAndVerifyTransactionLeafData(transactionData) // Select Transaction Length let transactionLength := selectTransactionLength(transactionData) // Metadata size let providedDataSize := add3(TransactionLengthSize, metadataSize, witnessesSize) // We should never hit this, but we will add in the protection anyway.. assertOrFraud(lt(providedDataSize, transactionLength), FraudCode_ProvidedDataOverflow) // Memory size difference let unsignedTransactionLength := safeSub(transactionLength, providedDataSize) // We should never hit this, but we will add in the protection anyway.. assertOrFraud(lt(unsignedTransactionData, memoryPosition), FraudCode_ProvidedDataOverflow) // Computed unsigned transaction length // Should never underflow let computedUnsignedTransactionLength := safeSub(memoryPosition, unsignedTransactionData) // Invalid transaction length assertOrFraud(eq(unsignedTransactionLength, computedUnsignedTransactionLength), FraudCode_ComputedTransactionLengthOverflow) // Pop Memory Stack mpop(Stack_InputsSum) mpop(Stack_OutputsSum) mpop(Stack_Metadata) mpop(Stack_Witnesses) mpop(Stack_BlockTip) mpop(Stack_UTXOProofs) mpop(Stack_TransactionHashID) mpop(Stack_MetadataLength) mpush(Stack_SummingToken, 0) // load summing token mpush(Stack_SummingTokenID, 0) // load summing token mpop(Stack_Index) // We leave Memory Stack 6 for Secondary Transaction Proof Validation // We don't clear 7 - 15 (those are the returns from transaction processing) // Warning: CHECK Transaction Leaf Length here for Computed Length!! } mpop(Stack_Index) // // SELECTOR METHODS // For selecting, parsing and enforcing side-chain abstractions, rules and data across runtime memory // // Select the UTXO ID for an Input function selectUTXOID(input) -> utxoID { // Past 1 (input type) utxoID := mload(safeAdd(input, TypeSize)) } // Select Metadata function selectMetadata(metadata) -> blockHeight, transactionRootIndex, transactionIndex, outputIndex { blockHeight := slice(metadata, 4) transactionRootIndex := slice(safeAdd(metadata, 4), IndexSize) transactionIndex := slice(safeAdd(metadata, 5), 2) outputIndex := slice(safeAdd(metadata, 7), IndexSize) } // Select Metadata Selected (Used after verifyTransactionData) function selectInputSelectedHash(proofIndex) -> inputHash { let offset := 0 // Second proof, move offset to 4 if gt(proofIndex, 0) { offset := SelectionStackOffsetSize } // Input Hash Length (Type 1 Byte + Input Length Provided) let inputHashLength := 0 // Input Memory Position let input := selectInputSelected(proofIndex) // Get lenght switch selectInputType(input) case 0 { inputHashLength := 33 } case 1 { inputHashLength := 33 } case 2 { inputHashLength := 65 } case 3 { inputHashLength := 33 } default { assertOrInvalidProof(0, 0) } // Set metadata inputHash := keccak256(input, inputHashLength) } // Select Metadata Selected (Used after verifyTransactionData) function selectMetadataSelected(proofIndex) -> metadata { let offset := 0 // Second proof, move offset to 4 if gt(proofIndex, 0) { offset := SelectionStackOffsetSize } // Return metadata memory position let metadataInput, input, unused, unused2 := splitCombinedUint32(mstack(safeAdd(Stack_MetadataSelected, offset))) // Set metadata metadata := metadataInput } // Select Input Selected (Used after verifyTransactionData) function selectInputSelected(proofIndex) -> input { let offset := 0 // Second proof, move offset to 4 if gt(proofIndex, 0) { offset := SelectionStackOffsetSize } // Get values let metadata, inputPosition, unused, unused2 := splitCombinedUint32(mstack(safeAdd(Stack_MetadataSelected, offset))) // Input position input := inputPosition } // Select Output Selected (Used after verifyTransactionData) function selectOutputSelected(proofIndex) -> output { let offset := 0 // Second proof, move offset to 4 if gt(proofIndex, 0) { offset := SelectionStackOffsetSize } // Return metadata memory position output := mstack(safeAdd(Stack_OutputSelected, offset)) } // Select Witness Selected (Used after verifyTransactionData) function selectWitnessSelected(proofIndex) -> witness { let offset := 0 // Second proof, move offset to 4 if gt(proofIndex, 0) { offset := SelectionStackOffsetSize } // Return metadata memory position witness := mstack(safeAdd(Stack_WitnessSelected, offset)) } function selectBlockHeaderLength(transactionProof) -> blockHeaderLength { blockHeaderLength := load32(transactionProof, 0) } function selectTransactionRootLength(transactionProof) -> transactionRootLength { transactionRootLength := load32(transactionProof, 1) } function selectMerkleProofLength(transactionProof) -> merkleProofLength { merkleProofLength := load32(transactionProof, 2) } // Select Transaction Proof Lengths function selectTransactionProofLengths(transactionProof) -> lengthsLength, blockHeaderLength, transactionRootHeaderLength, transactionDataLength, transactionMerkleLength, transactionUTXOLength { // Compute Proof Length or Lengths lengthsLength := mul32(5) // If malformed block proof if iszero(selectProofType()) { lengthsLength := mul32(3) } // Select Proof Lengths blockHeaderLength := load32(transactionProof, 0) transactionRootHeaderLength := load32(transactionProof, 1) transactionMerkleLength := load32(transactionProof, 2) transactionDataLength := load32(transactionProof, 3) transactionUTXOLength := load32(transactionProof, 4) } // Select Transaction Proof Memory Position function selectTransactionProof(proofIndex) -> transactionProof { // Increase proof memory position for proof type (32 bytes) transactionProof := safeAdd(Calldata_MemoryPosition, mul32(1)) // Select second proof instead! if gt(proofIndex, 0) { // Get lengths let lengthsLength, blockHeaderLength, transactionRootHeaderLength, transactionDataLength, transactionMerkleLength, transactionUTXOLength := selectTransactionProofLengths(transactionProof) // Secondary position transactionProof := add4( transactionProof, lengthsLength, blockHeaderLength, add4(transactionRootHeaderLength, transactionMerkleLength, transactionDataLength, transactionUTXOLength)) } } // Select Transaction Proof Block Header function selectBlockHeader(proofIndex) -> blockHeader { // Select Proof Memory Position blockHeader := selectTransactionProof(proofIndex) // If it's not the bond withdrawal if lt(selectProofType(), 6) { let lengthsLength, blockHeaderLength, transactionRootHeaderLength, transactionDataLength, transactionMerkleLength, transactionUTXOLength := selectTransactionProofLengths(blockHeader) // Block header (always after lengths) blockHeader := safeAdd(blockHeader, lengthsLength) } } function selectBlockProducer(blockHeader) -> blockProducer { blockProducer := load32(blockHeader, 0) } function selectBlockHeight(blockHeader) -> blockHeight { blockHeight := load32(blockHeader, 2) } function selectPreviousBlockHash(blockHeader) -> previousBlockHash { previousBlockHash := load32(blockHeader, 1) } function selectTransactionRootsLength(blockHeader) -> transactionRootsLength { transactionRootsLength := load32(blockHeader, 5) } function selectEthereumBlockNumber(blockHeader) -> ethereumBlockNumber { ethereumBlockNumber := load32(blockHeader, 3) } // Select Transaction Root from Proof function selectTransactionRoot(proofIndex) -> transactionRoot { // Select Proof Memory Position let transactionProof := selectTransactionProof(proofIndex) // Get lengths let lengthsLength, blockHeaderLength, transactionRootHeaderLength, transactionDataLength, transactionMerkleLength, transactionUTXOLength := selectTransactionProofLengths(transactionProof) // Select Transaction Root Position transactionRoot := add3(transactionProof, lengthsLength, blockHeaderLength) } // Select Root Producer function selectRootProducer(transactionRoot) -> rootProducer { rootProducer := load32(transactionRoot, 0) } // Select Merkle Tree Root function selectMerkleTreeRoot(transactionRoot) -> merkleTreeRoot { merkleTreeRoot := load32(transactionRoot, 1) } // Select commitment hash from root function selectCommitmentHash(transactionRoot) -> commitmentHash { commitmentHash := load32(transactionRoot, 2) } // Select Transaction Root Index function selectTransactionRootIndex(transactionRoot) -> transactionRootIndex { transactionRootIndex := load32(transactionRoot, 3) } // Select Transaction Root from Proof function selectTransactionMerkleProof(proofIndex) -> merkleProof { // Select Proof Memory Position merkleProof := selectTransactionProof(proofIndex) // Get lengths let lengthsLength, blockHeaderLength, transactionRootHeaderLength, transactionDataLength, transactionMerkleLength, transactionUTXOLength := selectTransactionProofLengths(merkleProof) // Select Transaction Root Position merkleProof := add4(merkleProof, lengthsLength, blockHeaderLength, transactionRootHeaderLength) } // Select First Merkle Proof function selectMerkleTreeBaseLeaf(merkleProof) -> leaf { leaf := load32(merkleProof, 3) } // Select Opposite Transaction Leaf in Merkle Proof function selectOppositeTransactionLeaf(merkleProof) -> oppositeTransactionLeaf { oppositeTransactionLeaf := mload(merkleProof) } // Select Merkle Tree Height function selectMerkleTreeHeight(merkleProof) -> merkleTreeHeight { merkleTreeHeight := load32(merkleProof, 2) } // Select Merkle Tree Height function selectMerkleTree(merkleProof) -> merkleTree { merkleTree := safeAdd(merkleProof, mul32(3)) } // Select Transaction Data from Proof function selectTransactionData(proofIndex) -> transactionData { // Select Proof Memory Position let proofMemoryPosition := selectTransactionProof(proofIndex) // Get lengths let lengthsLength, blockHeaderLength, transactionRootHeaderLength, transactionDataLength, transactionMerkleLength, transactionUTXOLength := selectTransactionProofLengths(proofMemoryPosition) // Select Transaction Data Position transactionData := add4(proofMemoryPosition, lengthsLength, blockHeaderLength, safeAdd(transactionRootHeaderLength, transactionMerkleLength)) } function selectTransactionIndex(transactionData) -> transactionIndex { transactionIndex := load32(transactionData, 3) } function selectInputIndex(transactionData) -> outputIndex { outputIndex := load32(transactionData, 0) } function selectOutputIndex(transactionData) -> outputIndex { outputIndex := load32(transactionData, 1) } function selectWitnessIndex(transactionData) -> outputIndex { outputIndex := load32(transactionData, 2) } // Verify Transaction Lengths function verifyTransactionProofLengths(proofCount) { // Total Proof Length let proofLengthWithoutType := 0 // Iterate and Compute Maximum length for { let proofIndex := 0 } and(lt(proofIndex, 2), lt(proofIndex, proofCount)) { proofIndex := safeAdd(proofIndex, 1) } { // Get lengths let lengthsLength, blockHeaderLength, transactionRootHeaderLength, transactionDataLength, transactionMerkleLength, transactionUTXOLength := selectTransactionProofLengths(selectTransactionProof(proofIndex)) // Add total proof length proofLengthWithoutType := add4(add4(proofLengthWithoutType, lengthsLength, blockHeaderLength, transactionRootHeaderLength), transactionDataLength, transactionMerkleLength, transactionUTXOLength) } // Verify Proof Length Overflow verifyProofLength(proofLengthWithoutType) } // Select Transaction Data from Proof function selectTransactionUTXOProofs(proofIndex) -> utxoProofs { // Select Proof Memory Position let proofMemoryPosition := selectTransactionProof(proofIndex) // Get lengths let lengthsLength, blockHeaderLength, transactionRootHeaderLength, transactionDataLength, transactionMerkleLength, transactionUTXOLength := selectTransactionProofLengths(proofMemoryPosition) // Select Transaction Data Position utxoProofs := safeAdd(selectTransactionData(proofIndex), transactionDataLength) } function selectWithdrawalToken(proofIndex) -> withdrawalToken { withdrawalToken := load32(selectTransactionUTXOProofs(proofIndex), 0) } // select proof type function selectProofType() -> proofType { proofType := load32(Calldata_MemoryPosition, 0) // 32 byte chunk } // Select input function selectInputType(input) -> result { result := slice(input, 1) // [1 bytes] } // Select utxoID (length includes type) function selectAndVerifyInputUTXO(input, witnessesLength) -> length, utxoID, witnessReference { utxoID := mload(safeAdd(1, input)) witnessReference := slice(add3(TypeSize, 32, input), IndexSize) length := 33 // UTXO + Witness Reference // Assert Witness Index is Valid assertOrFraud(lt(witnessReference, witnessesLength), FraudCode_TransactionInputWitnessReferenceOverflow) } // Select Input Deposit Proof function selectInputDepositOwner(depositProof) -> owner { // Load owner owner := load32(depositProof, 0) } // Select Input Deposit Proof function selectInputDepositToken(depositProof) -> token { // Load owner token := load32(depositProof, 1) } // Select deposit information (length includes type) function selectAndVerifyInputDeposit(input, witnessesLength) -> length, depositHashID, witnessReference { depositHashID := mload(safeAdd(input, TypeSize)) witnessReference := slice(add3(input, TypeSize, 32), IndexSize) length := 33 // Assert deposit is not zero assertOrFraud(gt(getDeposits(depositHashID), 0), FraudCode_TransactionInputDepositZero) // Assert Witness Index is Valid assertOrFraud(lt(witnessReference, witnessesLength), FraudCode_TransactionInputDepositWitnessOverflow) } // Select HTLC information (length includes type) function selectAndVerifyInputHTLC(input, witnessesLength) -> length, utxoID, witnessReference, preImage { utxoID := mload(safeAdd(input, TypeSize)) witnessReference := slice(add3(input, TypeSize, 32), IndexSize) preImage := mload(add4(input, TypeSize, 32, IndexSize)) length := 65 // Assert valid Witness Reference (could be changed to generic witness ref overflow later..) assertOrFraud(lt(witnessReference, witnessesLength), FraudCode_TransactionHTLCWitnessOverflow) } // Select output type function selectOutputType(output) -> result { result := slice(output, TypeSize) // [1 bytes] } // Select output amounts length (length includes type) function selectAndVerifyOutputAmountLength(output) -> length { // Select amounts length past Input Type length := slice(safeAdd(TypeSize, output), 1) // Assert amounts length greater than zero assertOrFraud(gt(length, 0), FraudCode_TransactionOutputAmountLengthUnderflow) // Assert amounts length less than 33 (i.e 1 <> 32) assertOrFraud(lte(length, 32), FraudCode_TransactionOutputAmountLengthOverflow) } // Select output utxo (length includes type) function selectAndVerifyOutput(output, isChangeOutput) -> length, amount, owner, tokenID { let amountLength := selectAndVerifyOutputAmountLength(output) // Push amount amount := slice(add3(TypeSize, 1, output), amountLength) // 1 for Type, 1 for Amount Length // owner dynamic length let ownerLength := 20 // is Change output, than owner is witness reference if eq(isChangeOutput, 1) { ownerLength := 1 } // Push owner owner := slice(add4(TypeSize, 1, amountLength, output), ownerLength) // Select Token ID tokenID := slice(add4(TypeSize, 1, amountLength, safeAdd(ownerLength, output)), 4) // Assert Token ID is Valid assertOrFraud(lt(tokenID, getNumTokens()), FraudCode_TransactionOutputTokenIDOverflow) // Push Output Length (don't include type size) length := add4(TypeSize, amountLength, ownerLength, 4) } // Select output HTLC function selectAndVerifyOutputHTLC(output, witnessesLength) -> length, amount, owner, tokenID, digest, expiry, returnWitness { // Select amount length let amountLength := selectAndVerifyOutputAmountLength(output) // Select Output Details length, amount, owner, tokenID := selectAndVerifyOutput(output, False) // htlc let htlc := add3(TypeSize, output, length) // Select Digest from Output digest := mload(htlc) // Assert Token ID is Valid assertOrFraud(gt(digest, 0), FraudCode_TransactionOutputHTLCDigestZero) // Select Expiry expiry := slice(safeAdd(htlc, DigestSize), ExpirySize) // Assert Expiry is Valid assertOrFraud(gt(expiry, 0), FraudCode_TransactionOutputHTLCExpiryZero) // Set expiry, digest, witness returnWitness := slice(add3(htlc, DigestSize, ExpirySize), IndexSize) // Assert Valid Return Witness assertOrFraud(lt(returnWitness, witnessesLength), FraudCode_TransactionOutputWitnessReferenceOverflow) // Determine output length (don't include type size) length := add4(length, DigestSize, ExpirySize, IndexSize) } // Select the Transaction Leaf from Data function selectTransactionLeaf(transactionData) -> leaf { /* - Transaction Data: - inputSelector [32 bytes] - outputSelector [32 bytes] - witnessSelector [32 bytes] - transactionIndex [32 bytes] - transactionLeafData [dynamic bytes] */ // Increase memory past the 3 selectors and 1 Index leaf := safeAdd(transactionData, mul32(6)) } // Select transaction length function selectTransactionLength(transactionData) -> transactionLength { // Select transaction length transactionLength := slice(selectTransactionLeaf(transactionData), 2) } // Select Metadata Length function selectTransactionMetadataLength(transactionData) -> metadataLength { // Select metadata length 1 bytes metadataLength := slice(safeAdd(selectTransactionLeaf(transactionData), 2), 1) } // Select Witnesses (past witness length) function selectTransactionWitnesses(transactionData) -> witnessesMemoryPosition { // Compute metadata size let metadataLength := selectTransactionMetadataLength(transactionData) // Compute Metadata Size let metadataSize := safeAdd(TypeSize, safeMul(MetadataSize, metadataLength)) // Length + metadata size // Leaf + Size 2 + metadata size and witness size witnessesMemoryPosition := add4(selectTransactionLeaf(transactionData), 2, metadataSize, 1) } function selectWitnessSignature(witnesses, witnessIndex) -> signature { // Compute witness offset let witnessMemoryOffset := safeMul(witnessIndex, WitnessSize) // Compute signature signature := safeAdd(witnesses, witnessMemoryOffset) } // Note, we allow the transactionRootProducer to be a witness, witnesses length must be 1, zero fill 65 for witness data.. // Select Witnesses Signature function verifyTransactionWitness(signature, transactionHashID, outputOwner, rootProducer) { // Check if the witness is not the transaction root producer (i.e. a contract possibly) if iszero(eq(rootProducer, outputOwner)) { // Assert if witness signature is invalid! assertOrFraud(eq(outputOwner, ecrecoverPacked(transactionHashID, signature)), FraudCode_InvalidTransactionWitnessSignature) } } // Select Transaction Leaf Data function selectAndVerifyTransactionLeafData(transactionData) -> transactionHashData, // transaction hash data (unsigned transaction data) metadataSize, // total metadata chunk size (length + metadata) witnessesSize, // total witness size (length + witnesses) witnessesLength { // total witnesses length // Compute metadata size let metadataLength := selectTransactionMetadataLength(transactionData) // Assert metadata length correctness (metadata length can be zero) assertOrFraud(lte(metadataLength, TransactionLengthMax), FraudCode_TransactionMetadataLengthOverflow) // Compute Metadata Size metadataSize := safeAdd(1, safeMul(MetadataSize, metadataLength)) // Length + metadata size // Leaf + Size 2 + metadata size and witness size transactionHashData := add3(selectTransactionLeaf(transactionData), 2, metadataSize) // get witnesses length witnessesLength := slice(transactionHashData, 1) // Witness Length witnessesSize := safeAdd(1, safeMul(WitnessSize, witnessesLength)) // Length + witness size // Leaf + Size 2 + metadata size and witness size transactionHashData := safeAdd(transactionHashData, witnessesSize) } // Select Transaction Details function selectAndVerifyTransactionDetails(transactionData) -> memoryPosition, inputsLength, outputsLength, witnessesLength { let unsignedTransactionData, metadataSize, witnessesSize, witnessLength := selectAndVerifyTransactionLeafData(transactionData) // Setup length (push to new name) witnessesLength := witnessLength // Set Transaction Data Memory Position memoryPosition := unsignedTransactionData // Assert witness length assertOrFraud(gt(witnessesLength, TransactionLengthMin), FraudCode_TransactionWitnessesLengthUnderflow) assertOrFraud(lte(witnessesLength, TransactionLengthMax), FraudCode_TransactionWitnessesLengthOverflow) // Select lengths inputsLength := slice(memoryPosition, 1) // Inputs Length outputsLength := slice(safeAdd(1, memoryPosition), 1) // Outputs Length // Assert inputsLength and outputsLength minimum assertOrFraud(gt(inputsLength, TransactionLengthMin), FraudCode_TransactionInputsLengthUnderflow) assertOrFraud(gt(outputsLength, TransactionLengthMin), FraudCode_TransactionOutputsLengthUnderflow) // Assert Length overflow checks assertOrFraud(lte(inputsLength, TransactionLengthMax), FraudCode_TransactionInputsLengthOverflow) assertOrFraud(lte(outputsLength, TransactionLengthMax), FraudCode_TransactionOutputsLengthOverflow) // Assert metadata length correctness (metadata length can be zero) assertOrFraud(lte(selectTransactionMetadataLength(transactionData), inputsLength), FraudCode_TransactionMetadataLengthOverflow) // Assert selections are valid against lengths assertOrInvalidProof(lt(selectInputSelectionIndex(transactionData), inputsLength), ErrorCode_InputIndexSelectedOverflow) assertOrInvalidProof(lt(selectOutputSelectionIndex(transactionData), outputsLength), ErrorCode_OutputIndexSelectedOverflow) assertOrInvalidProof(lt(selectWitnessSelectionIndex(transactionData), witnessesLength), ErrorCode_WitnessIndexSelectedOverflow) } // Select Transaction Metadata (Past Length) function selectTransactionMetadata(transactionData) -> transactionMetadata { // Increase memory position past lengths transactionMetadata := safeAdd(selectTransactionLeaf(transactionData), 3) } // Select UTXO proof function selectAndVerifyUTXOAmountOwner(utxoProof, requestedOutputType, providedUTXOID) -> outputAmount, outputOwner, tokenID { /* - Transaction UTXO Proof(s): -- 288 bytes (same order as inputs, skip Deposit index with zero fill) - transactionHashId [32 bytes] -- bytes32 - outputIndex [32 bytes] -- padded uint8 - type [32 bytes] -- padded uint8 - amount [32 bytes] -- uint256 - owner [32 bytes] -- padded address or witness reference index uint8 - tokenID [32 bytes] -- padded uint32 - [HTLC Data]: - digest [32 bytes] -- bytes32 (or zero pad 32 bytes) - expiry [32 bytes] -- padded uint32 (or zero pad 32 bytes) - return witness index [32 bytes] -- padded uint8] (or zero pad 32 bytes) */ // Assert computed utxo id correct assertOrInvalidProof(eq(providedUTXOID, constructUTXOID(utxoProof)), ErrorCode_TransactionUTXOIDInvalid) // Compute output amount let outputType := load32(utxoProof, 2) // Assert output type is correct assertOrFraud(eq(requestedOutputType, outputType), FraudCode_TransactionUTXOType) // Assert index correctness assertOrFraud(lt(load32(utxoProof, 1), TransactionLengthMax), FraudCode_TransactionUTXOOutputIndexOverflow) // Compute output amount outputAmount := load32(utxoProof, 3) // Compute output amount outputOwner := load32(utxoProof, 4) // Compute output amount tokenID := load32(utxoProof, 5) } // // CONSTRUCTION METHODS // For the construction of cryptographic side-chain hashes // // produce block hash from block header function constructBlockHash(blockHeader) -> blockHash { /* - Block Header: - blockProducer [32 bytes] -- padded address - previousBlockHash [32 bytes] - blockHeight [32 bytes] - ethereumBlockNumber [32 bytes] - transactionRoots [64 + bytes32 array] */ // Select Transaction root Length let transactionRootsLength := load32(blockHeader, 5) // Construct Block Hash blockHash := keccak256(blockHeader, mul32(safeAdd(6, transactionRootsLength))) } // produce a transaction hash id from a proof (subtract metadata and inputs length from hash data) function constructTransactionHashID(transactionData) -> transactionHashID { /* - Transaction Data: - inputSelector [32 bytes] - outputSelector [32 bytes] - witnessSelector [32 bytes] - transactionIndex [32 bytes] - transactionLeafData [dynamic bytes] - Transaction Leaf Data: - transactionByteLength [2 bytes] (max 2048) - metadata length [1 bytes] (min 1 - max 8) - input metadata [dynamic -- 8 bytes per]: - blockHeight [4 bytes] - transactionRootIndex [1 byte] - transactionIndex [2 bytes] - output index [1 byte] - witnessLength [1 bytes] - witnesses [dynamic]: - signature [65 bytes] */ // Get entire tx length, and metadata sizes / positions let transactionLength := selectTransactionLength(transactionData) // length is first 2 if gt(transactionLength, 0) { let transactionLeaf, metadataSize, witnessesSize, witnessLength := selectAndVerifyTransactionLeafData(transactionData) // setup hash keccak256(start, length) let transactionHashDataLength := safeSub(safeSub(transactionLength, TransactionLengthSize), safeAdd(metadataSize, witnessesSize)) // create transaction ID transactionHashID := keccak256(transactionLeaf, transactionHashDataLength) } } // Construct Deposit Hash ID function constructDepositHashID(depositProof) -> depositHashID { depositHashID := keccak256(depositProof, mul32(3)) } // Construct a UTXO Proof from a Transaction Output function constructUTXOProof(transactionHashID, outputIndex, output) -> utxoProof { let isChangeOutput := False // Output Change if eq(selectOutputType(output), OutputType_Change) { isChangeOutput := True } // Select and Verify output let length, amount, owner, tokenID := selectAndVerifyOutput(output, isChangeOutput) // Encode Pack Transaction Output Data mstore(mul32(1), transactionHashID) mstore(mul32(2), outputIndex) mstore(mul32(3), selectOutputType(output)) mstore(mul32(4), amount) mstore(mul32(5), owner) // address or witness index mstore(mul32(6), tokenID) mstore(mul32(7), 0) mstore(mul32(8), 0) mstore(mul32(9), 0) // Include HTLC Data here if eq(selectOutputType(output), 2) { let unused0, unused1, unused2, unused3, digest, expiry, returnWitness := selectAndVerifyOutputHTLC(output, TransactionLengthMax) mstore(mul32(7), digest) mstore(mul32(8), expiry) mstore(mul32(9), returnWitness) } // Return UTXO Memory Position utxoProof := mul32(1) } // Construct a UTXO ID function constructUTXOID(utxoProof) -> utxoID { /* - Transaction UTXO Data: - transactionHashId [32 bytes] - outputIndex [32 bytes] -- padded uint8 - type [32 bytes] -- padded uint8 - amount [32 bytes] - owner [32 bytes] -- padded address or unit8 - tokenID [32 bytes] -- padded uint32 - [HTLC Data]: -- padded with zeros - digest [32 bytes] - expiry [32 bytes] -- padded 4 bytes - return witness index [32 bytes] -- padded 1 bytes */ // Construct UTXO ID utxoID := keccak256(utxoProof, UTXOProofSize) } // Construct the Transaction Leaf Hash function constructTransactionLeafHash(transactionData) -> transactionLeafHash { /* - Transaction Data: - inputSelector [32 bytes] - outputSelector [32 bytes] - witnessSelector [32 bytes] - transactionIndex [32 bytes] - transactionLeafData [dynamic bytes] */ // Get first two transaction length bytes let transactionLength := selectTransactionLength(transactionData) // Check if length is Zero, than don't hash! switch eq(transactionLength, 0) // Return Zero leaf hash case 1 { transactionLeafHash := 0 } // Hash as Normal Transaction default { // Start Hash Past Selections (3) and Index (1) let hashStart := selectTransactionLeaf(transactionData) // Return the transaction leaf hash transactionLeafHash := keccak256(hashStart, transactionLength) } } // Select input index function selectInputSelectionIndex(transactionData) -> inputIndex { inputIndex := load32(transactionData, 0) } // Select output index function selectOutputSelectionIndex(transactionData) -> outputIndex { outputIndex := load32(transactionData, 1) } // Select witness index function selectWitnessSelectionIndex(transactionData) -> witnessIndex { witnessIndex := load32(transactionData, 2) } // This function Must Select Block of Current Proof Being Validated!! NOT DONE YET! // Assert True or Fraud, Set Side-chain to Valid block and Stop Execution function assertOrFraud(assertion, fraudCode) { // Assert or Begin Fraud State Change Sequence if lt(assertion, 1) { // proof index let proofIndex := 0 // We are validating proof 2 if gt(mstack(Stack_ProofNumber), 0) { proofIndex := 1 } // Fraud block details let fraudBlockHeight := selectBlockHeight(selectBlockHeader(proofIndex)) let fraudBlockProducer := selectBlockProducer(selectBlockHeader(proofIndex)) let ethereumBlockNumber := selectEthereumBlockNumber(selectBlockHeader(proofIndex)) // Assert Fraud block cannot be the genesis block assertOrInvalidProof(gt(fraudBlockHeight, GenesisBlockHeight), ErrorCode_FraudBlockHeightUnderflow) // Assert fraud block cannot be finalized assertOrInvalidProof(lt(number(), safeAdd(ethereumBlockNumber, FINALIZATION_DELAY)), ErrorCode_FraudBlockFinalized) // Push old block tip let previousBlockTip := getBlockTip() // Set new block tip to before fraud block setBlockTip(safeSub(fraudBlockHeight, 1)) // Release Block Producer, If it's Permissioned // (i.e. block producer committed fraud so get them out!) // if eq(fraudBlockProducer, getBlockProducer()) { // setBlockProducer(0) // } // Log block tips (old / new) log4(0, 0, FraudEventTopic, previousBlockTip, getBlockTip(), fraudCode) // Transfer Half The Bond for this Block transfer(div(BOND_SIZE, 2), EtherToken, EtherToken, caller()) // stop execution from here stop() } } // Construct withdrawal Hash ID function constructWithdrawalHashID(transactionRootIndex, transactionLeafHash, outputIndex) -> withdrawalHashID { // Construct withdrawal Hash mstore(mul32(1), transactionRootIndex) mstore(mul32(2), transactionLeafHash) mstore(mul32(3), outputIndex) // Hash Leaf and Output Together withdrawalHashID := keccak256(mul32(1), mul32(3)) } // Construct Transactions Merkle Tree Root function constructMerkleTreeRoot(transactions, transactionsLength) -> merkleTreeRoot { // Start Memory Position at Transactions Data let memoryPosition := transactions let nodesLength := 0 let netLength := 0 let freshMemoryPosition := mstack(Stack_FreshMemory) // create base hashes and notate node count for { let transactionIndex := 0 } lt(transactionIndex, MaxTransactionsInBlock) { transactionIndex := safeAdd(transactionIndex, 1) } { // get the transaction length let transactionLength := slice(memoryPosition, TransactionLengthSize) // If Transaction length is zero and we are past first tx, stop (we are at the end) if and(gt(transactionIndex, 0), iszero(transactionLength)) { break } // if transaction length is below minimum transaction length, stop verifyTransactionLength(transactionLength) // add net length together netLength := safeAdd(netLength, transactionLength) // computed length greater than provided payload assertOrFraud(lte(netLength, transactionsLength), FraudCode_InvalidTransactionsNetLength) // store the base leaf hash (add 2 removed from here..) mstore(freshMemoryPosition, keccak256(memoryPosition, transactionLength)) // increase the memory length memoryPosition := safeAdd(memoryPosition, transactionLength) // increase fresh memory by 32 bytes freshMemoryPosition := safeAdd(freshMemoryPosition, 32) // increase number of nodes nodesLength := safeAdd(nodesLength, 1) } // computed length greater than provided payload assertOrFraud(eq(netLength, transactionsLength), FraudCode_InvalidTransactionsNetLength) // Merkleize nodes into a binary merkle tree memoryPosition := safeSub(freshMemoryPosition, safeMul(nodesLength, 32)) // setup new memory position // Create Binary Merkle Tree / Master Root Hash for {} gt(nodesLength, 0) {} { // loop through tree Heights (starting at base) if gt(mod(nodesLength, 2), 0) { // fix uneven leaf count (i.e. add a zero hash) mstore(safeAdd(memoryPosition, safeMul(nodesLength, 32)), 0) // add 0x00...000 hash leaf nodesLength := safeAdd(nodesLength, 1) // increase count for zero hash leaf freshMemoryPosition := safeAdd(freshMemoryPosition, 32) // increase fresh memory past new leaf } for { let i := 0 } lt(i, nodesLength) { i := safeAdd(i, 2) } { // loop through Leaf hashes at this height mstore(freshMemoryPosition, keccak256(safeAdd(memoryPosition, safeMul(i, 32)), 64)) // hash two leafs together freshMemoryPosition := safeAdd(freshMemoryPosition, 32) // increase fresh memory past new hash leaf } memoryPosition := safeSub(freshMemoryPosition, safeMul(nodesLength, 16)) // set new memory position nodesLength := div(nodesLength, 2) // half nodes (i.e. next height) // shim 1 to zero (stop), i.e. top height end.. if lt(nodesLength, 2) { nodesLength := 0 } } // merkle root has been produced merkleTreeRoot := mload(memoryPosition) // write new fresh memory position mpush(Stack_FreshMemory, safeAdd(freshMemoryPosition, mul32(2))) } // Construct HTLC Digest Hash function constructHTLCDigest(preImage) -> digest { // Store PreImage in Memory mstore(mul32(1), preImage) // Construct Digest Hash digest := keccak256(mul32(1), mul32(1)) } // // LOW LEVEL METHODS // // Safe Math Add function safeAdd(x, y) -> z { z := add(x, y) assertOrInvalidProof(or(eq(z, x), gt(z, x)), ErrorCode_SafeMathAdditionOverflow) // require((z = x + y) >= x, "ds-math-add-overflow"); } // Safe Math Subtract function safeSub(x, y) -> z { z := sub(x, y) assertOrInvalidProof(or(eq(z, x), lt(z, x)), ErrorCode_SafeMathSubtractionUnderflow) // require((z = x - y) <= x, "ds-math-sub-underflow"); } // Safe Math Multiply function safeMul(x, y) -> z { if gt(y, 0) { z := mul(x, y) assertOrInvalidProof(eq(div(z, y), x), ErrorCode_SafeMathMultiplyOverflow) // require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } } // Safe Math Add3, Add4 Shorthand function add3(x, y, z) -> result { result := safeAdd(x, safeAdd(y, z)) } function add4(x, y, z, k) -> result { result := safeAdd(x, safeAdd(y, safeAdd(z, k))) } // Common <= and >= function lte(v1, v2) -> result { result := or(lt(v1, v2), eq(v1, v2)) } function gte(v1, v2) -> result { result := or(gt(v1, v2), eq(v1, v2)) } // Safe Multiply by 32 function mul32(length) -> result { result := safeMul(32, length) } // function combine 3 unit32 values together into one 32 byte combined value function combineUint32(val1, val2, val3, val4) -> combinedValue { mstore(safeAdd(mul32(2), 8), val4) // 2 bytes mstore(safeAdd(mul32(2), 6), val3) // 2 bytes mstore(safeAdd(mul32(2), 4), val2) // 2 bytes mstore(safeAdd(mul32(2), 2), val1) // 2 bytes // Grab combined value combinedValue := mload(mul32(3)) } // split a combined value into three original chunks function splitCombinedUint32(combinedValue) -> val1, val2, val3, val4 { mstore(mul32(2), combinedValue) // grab values val1 := slice(safeAdd(mul32(2), 0), 2) // 2 byte slice val2 := slice(safeAdd(mul32(2), 2), 2) // 2 byte slice val3 := slice(safeAdd(mul32(2), 4), 2) // 2 byte slice val3 := slice(safeAdd(mul32(2), 6), 2) // 2 byte slice } // Transfer method helper function transfer(amount, tokenID, token, owner) { // Assert value owner / amount assertOrInvalidProof(gt(amount, 0), ErrorCode_TransferAmountUnderflow) assertOrInvalidProof(gt(owner, 0), ErrorCode_TransferOwnerInvalid) // Assert valid token ID assertOrInvalidProof(lt(tokenID, getNumTokens()), ErrorCode_TransferTokenIDOverflow) // Assert address is properly registered token assertOrInvalidProof(eq(tokenID, getTokens(token)), ErrorCode_TransferTokenAddress) // Ether Token if eq(token, EtherToken) { let result := call(owner, 21000, amount, 0, 0, 0, 0) assertOrInvalidProof(result, ErrorCode_TransferEtherCallResult) } // ERC20 "a9059cbb": "transfer(address,uint256)", if gt(token, 0) { // Construct ERC20 Transfer mstore(mul32(1), 0xa9059cbb) mstore(mul32(2), owner) mstore(mul32(3), amount) // Input Details let inputStart := safeAdd(mul32(1), 28) let inputLength := 68 // ERC20 Call let result := call(token, 400000, 0, inputStart, inputLength, 0, 0) assertOrInvalidProof(result, ErrorCode_TransferERC20Result) } } // Virtual Memory Stack Push (for an additional 32 stack positions) function mpush(pos, val) { // Memory Push mstore(add(Stack_MemoryPosition, mul32(pos)), val) } // Virtual Memory Stack Get function mstack(pos) -> result { // Memory Stack result := mload(add(Stack_MemoryPosition, mul32(pos))) } // Virtual Stack Pop function mpop(pos) { // Memory Pop mstore(add(Stack_MemoryPosition, mul32(pos)), 0) } // Memory Slice (within a 32 byte chunk) function slice(position, length) -> result { if gt(length, 32) { revert(0, 0) } // protect against overflow result := div(mload(position), exp(2, safeSub(256, safeMul(length, 8)))) } // Solidity Storage Key: mapping(bytes32 => bytes32) function mappingStorageKey(key, storageIndex) -> storageKey { mstore(32, key) mstore(64, storageIndex) storageKey := keccak256(32, 64) } // Solidity Storage Key: mapping(bytes32 => mapping(bytes32 => bytes32) function mappingStorageKey2(key, key2, storageIndex) -> storageKey { mstore(32, key) mstore(64, storageIndex) mstore(96, key2) mstore(128, keccak256(32, 64)) storageKey := keccak256(96, 64) } // load a 32 byte chunk with a 32 byte offset chunk from position function load32(memoryPosition, chunkOffset) -> result { result := mload(add(memoryPosition, safeMul(32, chunkOffset))) } // Assert True or Invalid Proof function assertOrInvalidProof(arg, errorCode) { if lt(arg, 1) { // Set Error Code In memory mstore(mul32(1), errorCode) // Revert and Return Error Code revert(mul32(1), mul32(1)) // Just incase we add a stop stop() } } // ECRecover Helper: hashPosition (32 bytes), signaturePosition (65 bytes) tight packing VRS function ecrecoverPacked(digestHash, signatureMemoryPosition) -> account { mstore(32, digestHash) // load in hash mstore(64, 0) // zero pas mstore(95, mload(signatureMemoryPosition)) mstore(96, mload(safeAdd(signatureMemoryPosition, 1))) mstore(128, mload(safeAdd(signatureMemoryPosition, 33))) let result := call(3000, 1, 0, 32, 128, 128, 32) // 4 chunks, return at 128 if eq(result, 0) { revert(0, 0) } account := mload(128) // set account } // // SETTERS & GETTER METHODS // Solidity setters and getters for side-chain state storage // // GET mapping(bytes32 => uint256) public deposits; // STORAGE 0 function getDeposits(depositHashId) -> result { result := sload(mappingStorageKey(depositHashId, Storage_deposits)) } // GET mapping(uint256 => mapping(bytes32 => bool)) publica withdrawals; // STORAGE 1 function getWithdrawals(blockHeight, withdrawalHashID) -> result { result := sload(mappingStorageKey2(blockHeight, withdrawalHashID, Storage_withdrawals)) } // SET mapping(uint256 => mapping(bytes32 => bool)) publica withdrawals; // STORAGE 1 function setWithdrawals(blockHeight, withdrawalHashID, hasWithdrawn) { sstore(mappingStorageKey2(blockHeight, withdrawalHashID, Storage_withdrawals), hasWithdrawn) } // GET mapping(bytes32 => uint256) public blockTransactionRoots; // STORAGE 2 function getBlockTransactionRoots(transactionRoot) -> result { result := sload(mappingStorageKey(transactionRoot, Storage_blockTransactionRoots)) } // GET mapping(uint256 => bytes32) public blockCommitments; // STORAGE 3 function getBlockCommitments(blockHeight) -> result { result := sload(mappingStorageKey(blockHeight, Storage_blockCommitments)) } // GET mapping(address => uint256) public tokens; // STORAGE 4 function getTokens(tokenAddress) -> result { result := sload(mappingStorageKey(tokenAddress, Storage_tokens)) // Ether token should always be zero if eq(tokenAddress, 0) { assertOrInvalidProof(eq(result, 0), ErrorCode_InvalidTokenAddress) } // ERC20 should always be above zero if gt(tokenAddress, 0) { assertOrInvalidProof(gt(result, 0), ErrorCode_InvalidTokenAddress) } } // GET uint256 public numTokens; // STORAGE 5 function getNumTokens() -> result { result := sload(Storage_numTokens) } // SET uint256 public blockTip; // STORAGE 6 function getBlockTip() -> result { result := sload(Storage_blockTip) } // SET blockTip() // STORAGE 6 function setBlockTip(tip) { sstore(Storage_blockTip, tip) } // GET address public blockProducer; // STORAGE 7 function getBlockProducer() -> result { result := sload(Storage_blockProducer) } // SET address public blockProducer // STORAGE 7 function setBlockProducer(producer) { sstore(Storage_blockProducer, producer) } } } }
STATE Changing Methods Compute deposit hash Identifier Assert amount is greater than Zero Handle transfer details register token with an index if it isn't already STORAGE register token with index STORAGE MOD increase token index LOG emit token registry index
function deposit(address account, address token, uint256 amount) external payable { bytes32 depositHashId = keccak256(abi.encode(account, token, block.number)); assert(amount > 0); if (token != address(0)) { } if (token != address(0) && tokens[token] == 0) { tokens[token] = numTokens; numTokens = ds_add(numTokens, 1); emit TokenIndex(token, numTokens); } }
12,672,651
pragma solidity ^0.5.16; /** * @dev Allow tokens to be transferred to contracts and have the contract trigger logic for how to respond to receiving the tokens within a single transaction. * https://github.com/ethereum/EIPs/issues/677 */ interface Callable { function tokenCallback(address _from, uint256 _tokens, bytes calldata _data) external returns (bool); } /** * @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 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; } } /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath} * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { // The {SafeMath} overflow check can be skipped here, see the comment at the top counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } /* * @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 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); } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId); function tokenByIndex(uint256 index) public view returns (uint256); } /** * @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"); } } /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping(uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping(address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][to] = approved; emit ApprovalForAll(_msgSender(), to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement {IERC721Receiver-onERC721Received}, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the _msgSender() to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(from, to, tokenId, _data); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal { _transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _safeMint(address to, uint256 tokenId) internal { _safeMint(to, tokenId, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * This is an internal detail of the `ERC721` contract and its use is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = to.call(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data )); if (!success) { if (returndata.length > 0) { // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert("ERC721: transfer to non ERC721Receiver implementer"); } } else { bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // 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; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev Gets the total amount of tokens stored by the contract. * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return _allTokens.length; } /** * @dev Gets the token ID at a given index of all the tokens in this contract * Reverts if the index is greater or equal to the total number of tokens. * @param index uint256 representing the index to be accessed of the tokens list * @return uint256 token ID at the given index of the tokens list */ function tokenByIndex(uint256 index) public view returns (uint256) { require(index < totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { super._transferFrom(from, to, tokenId); _removeTokenFromOwnerEnumeration(from, tokenId); _addTokenToOwnerEnumeration(to, tokenId); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to address the beneficiary that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { super._mint(to, tokenId); _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); _removeTokenFromOwnerEnumeration(owner, tokenId); // Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[tokenId] = 0; _removeTokenFromAllTokensEnumeration(tokenId); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @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 { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } /** * @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 = _ownedTokens[from].length.sub(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 _ownedTokens[from].length--; // Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by // lastTokenId, or just over the end of the array if the token was the last one). } /** * @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.sub(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 _allTokens.length--; _allTokensIndex[tokenId] = 0; } } contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Base URI string private _baseURI; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns the URI for a given token ID. May return an empty string. * * If the token's URI is non-empty and a base URI was set (via * {_setBaseURI}), it will be added to the token ID's URI as a prefix. * * Reverts if the token ID does not exist. */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // Even if there is a base URI, it is only appended to non-empty token-specific URIs if (bytes(_tokenURI).length == 0) { return ""; } else { // abi.encodePacked is being used to concatenate strings return string(abi.encodePacked(_baseURI, _tokenURI)); } } /** * @dev Internal function to set the token URI for a given token. * * Reverts if the token ID does not exist. * * TIP: if all token IDs share a prefix (e.g. if your URIs look like * `http://api.myproject.com/token/<id>`), use {_setBaseURI} to store * it and save gas. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}. * * _Available since v2.5.0._ */ function _setBaseURI(string memory baseURI) internal { _baseURI = baseURI; } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a preffix in {tokenURI} to each token's URI, when * they are non-empty. * * _Available since v2.5.0._ */ function baseURI() external view returns (string memory) { return _baseURI; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title Full ERC721 Token * @dev This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology. * * See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { // solhint-disable-previous-line no-empty-blocks } } contract BonkNftMinter is ERC721Full, Ownable, Callable { using SafeMath for uint256; // Mapping from token ID to the creator's address. mapping(uint256 => address) private tokenCreators; // Counter for creating token IDs uint256 private idCounter; // BONK ERC20 token IERC20 public bonkToken; // Where to send collected fees address public feeCollector; // BONK fee amount with decimals, for example, 1*10**18 means one BONK uint256 public bonkFee; // Event indicating metadata was updated. event TokenURIUpdated(uint256 indexed _tokenId, string _uri); // Event indicating bonk fee was updated. event BonkFeeUpdated(uint256 _newFee, uint _timestamp); constructor( string memory _name, string memory _symbol, address _bonkToken, address _feeCollector, uint256 _bonkFee ) public ERC721Full(_name, _symbol) { bonkToken = IERC20(_bonkToken); feeCollector = _feeCollector; bonkFee = _bonkFee; } /** * @dev Checks that the token is owned by the sender. * @param _tokenId uint256 ID of the token. */ modifier onlyTokenOwner(uint256 _tokenId) { address owner = ownerOf(_tokenId); require(owner == msg.sender, "must be the owner of the token"); _; } /** * @dev Checks that the caller is BONK token. */ modifier onlyBonkToken() { require(msg.sender == address(bonkToken), "must be BONK token"); _; } /** * @dev callback function that is called by BONK token. Adds new NFT token. Trusted. * @param _from who sent the tokens. * @param _tokens how many tokens were sent. * @param _data extra call data. * @return success. */ function tokenCallback(address _from, uint256 _tokens, bytes calldata _data) external onlyBonkToken returns (bool) { if (bonkFee > 0) { uint256 tokensWithTransferFee = _tokens * 100 / 99; // there is 1% fee upon some transfers of BONK require(tokensWithTransferFee >= bonkFee, "not enough tokens"); _forwardBonkTokens(); } _createToken(string(_data), _from); return true; } /** * @dev Adds a new unique token to the supply. * @param _uri string metadata uri associated with the token. */ function addNewToken(string calldata _uri) external { if (bonkFee > 0) { require(bonkToken.transferFrom(msg.sender, address(this), bonkFee), "fee transferFrom failed"); _forwardBonkTokens(); } _createToken(_uri, msg.sender); } /** * @dev Deletes the token with the provided ID. * @param _tokenId uint256 ID of the token. */ function deleteToken(uint256 _tokenId) external onlyTokenOwner(_tokenId) { _burn(msg.sender, _tokenId); } /** * @dev Allows owner of the contract updating the token metadata in case there is a need. * @param _tokenId uint256 ID of the token. * @param _uri string metadata URI. */ function updateTokenMetadata(uint256 _tokenId, string calldata _uri) external onlyOwner { _setTokenURI(_tokenId, _uri); emit TokenURIUpdated(_tokenId, _uri); } /** * @dev change address of BONK token * @param _bonkToken address of ERC20 contract */ function setBonkToken(address _bonkToken) external onlyOwner { bonkToken = IERC20(_bonkToken); } /** * @dev change address of where collected fees are sent * @param _feeCollector address where to send the fees */ function setFeeCollector(address _feeCollector) external onlyOwner { feeCollector = _feeCollector; } /** * @dev change BONK fee * @param _bonkFee new fee in BONK (with decimals) */ function setBonkFee(uint _bonkFee) external onlyOwner { bonkFee = _bonkFee; emit BonkFeeUpdated(_bonkFee, now); } /** * @dev allows withdrawal of ETH in case it was sent by accident * @param _beneficiary address where to send the eth. */ function withdrawEth(address payable _beneficiary) external onlyOwner { _beneficiary.transfer(address(this).balance); } /** * @dev allows withdrawal of ERC20 token in case it was sent by accident * @param _tokenAddress address of ERC20 token. * @param _beneficiary address where to send the tokens. * @param _amount amount to send. */ function withdrawERC20(address _tokenAddress, address _beneficiary, uint _amount) external onlyOwner { IERC20(_tokenAddress).transfer(_beneficiary, _amount); } /** * @dev Gets the current fee in BONK. * @return BONK fee. */ function getBonkFee() public view returns (uint256) { return bonkFee; } /** * @dev Gets the creator of the token. * @param _tokenId uint256 ID of the token. * @return address of the creator. */ function tokenCreator(uint256 _tokenId) public view returns (address) { return tokenCreators[_tokenId]; } /** * @dev Internal function for setting the token's creator. * @param _tokenId uint256 id of the token. * @param _creator address of the creator of the token. */ function _setTokenCreator(uint256 _tokenId, address _creator) internal { tokenCreators[_tokenId] = _creator; } /** * @dev Internal function creating a new token. * @param _uri string metadata uri associated with the token * @param _creator address of the creator of the token. */ function _createToken(string memory _uri, address _creator) internal returns (uint256) { uint256 newId = idCounter; idCounter++; _mint(_creator, newId); _setTokenURI(newId, _uri); _setTokenCreator(newId, _creator); return newId; } /** * @dev Internal function for forwarding collected fees to the fee collector. */ function _forwardBonkTokens() internal { uint balance = IERC20(bonkToken).balanceOf(address(this)); require(IERC20(bonkToken).transfer(feeCollector, balance), "fee transfer failed"); } }
Transfers the ownership of a given token ID to another address. Usage of this method is discouraged, use {safeTransferFrom} whenever possible. Requires the msg.sender to be the owner, approved, or operator. from current owner of the token to address to receive the ownership of the given token ID tokenId uint256 ID of the token to be transferred/solhint-disable-next-line max-line-length
function transferFrom(address from, address to, uint256 tokenId) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); }
14,330,522
// Sources flattened with hardhat v2.6.5 https://hardhat.org // File contracts/EIP20Interface.sol pragma solidity 0.5.17; /** * @title ERC 20 Token Standard Interface * https://eips.ethereum.org/EIPS/eip-20 */ interface EIP20Interface { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /** * @notice Get the total number of tokens in circulation * @return The supply of tokens */ function totalSupply() external view returns (uint256); /** * @notice Gets the balance of the specified address * @param owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address owner) external view returns (uint256 balance); /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool success); /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external returns (bool success); /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool success); /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 amount); event Approval( address indexed owner, address indexed spender, uint256 amount ); } // File contracts/SafeMath.sol pragma solidity 0.5.17; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @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 addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction underflow'); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ 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 multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul( uint256 a, uint256 b, string memory errorMessage ) 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, errorMessage); return c; } /** * @dev Returns the integer division of two unsigned integers. * Reverts on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } /** * @dev Returns the integer division of two unsigned integers. * Reverts with custom message on division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File contracts/Staking/ReentrancyGuard.sol pragma solidity 0.5.17; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() public { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, 'ReentrancyGuard: reentrant call'); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File contracts/Staking/TranquilStakingProxyStorage.sol pragma solidity 0.5.17; contract TranquilStakingProxyStorage { // Current contract admin address address public admin; // Requested new admin for the contract address public pendingAdmin; // Current contract implementation address address public implementation; // Requested new contract implementation address address public pendingImplementation; } // File contracts/Staking/TranquilStakingProxy.sol pragma solidity 0.5.17; contract TranquilStakingProxy is ReentrancyGuard, TranquilStakingProxyStorage { constructor() public { admin = msg.sender; } /** * Request a new admin to be set for the contract. * * @param newAdmin New admin address */ function setPendingAdmin(address newAdmin) public adminOnly { pendingAdmin = newAdmin; } /** * Accept admin transfer from the current admin to the new. */ function acceptPendingAdmin() public { require( msg.sender == pendingAdmin && pendingAdmin != address(0), 'Caller must be the pending admin' ); admin = pendingAdmin; pendingAdmin = address(0); } /** * Request a new implementation to be set for the contract. * * @param newImplementation New contract implementation contract address */ function setPendingImplementation(address newImplementation) public adminOnly { pendingImplementation = newImplementation; } /** * Accept pending implementation change */ function acceptPendingImplementation() public { require( msg.sender == pendingImplementation && pendingImplementation != address(0), 'Only the pending implementation contract can call this' ); implementation = pendingImplementation; pendingImplementation = address(0); } function() external payable { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } /******************************************************** * * * MODIFIERS * * * ********************************************************/ modifier adminOnly() { require(msg.sender == admin, 'admin only'); _; } } // File contracts/Staking/TranquilStakingStorage.sol pragma solidity 0.5.17; contract TranquilStakingStorage is TranquilStakingProxyStorage { uint256 constant nofStakingRewards = 2; uint256 constant REWARD_TRANQ = 0; uint256 constant REWARD_ONE = 1; // Address of the staked token. address public stakedTokenAddress; // Addresses of the ERC20 reward tokens mapping(uint256 => address) public rewardTokenAddresses; // Reward accrual speeds per reward token as tokens per second mapping(uint256 => uint256) public rewardSpeeds; // Unclaimed staking rewards per user and token mapping(address => mapping(uint256 => uint256)) public accruedReward; // Supplied tokens at stake per user mapping(address => uint256) public supplyAmount; // Sum of all supplied tokens at stake uint256 public totalSupplies; mapping(uint256 => uint256) public rewardIndex; mapping(address => mapping(uint256 => uint256)) public supplierRewardIndex; uint256 public accrualBlockTimestamp; } // File contracts/Staking/TranquilLockedStakingStorage.sol pragma solidity 0.5.17; contract TranquilLockedStakingStorage is TranquilStakingStorage { uint256 constant REWARD_TRANQ = 0; uint256 constant REWARD_ONE = 1; uint256 constant REWARD_WBTC = 2; uint256 constant REWARD_ETH = 3; uint256 constant REWARD_USDC = 4; uint256 constant REWARD_USDT = 5; // Total number of staking reward tokens; uint256 public rewardTokenCount; // Address of the staked token. address public stakedTokenAddress; // Addresses of the ERC20 reward tokens mapping(uint256 => address) public rewardTokenAddresses; // Reward accrual speeds per reward token as tokens per second mapping(uint256 => uint256) public rewardSpeeds; // Unclaimed staking rewards per user and token mapping(address => mapping(uint256 => uint256)) public accruedReward; // Supplied tokens at stake per user mapping(address => uint256) public supplyAmount; // Sum of all supplied tokens at stake uint256 public totalSupplies; mapping(uint256 => uint256) public rewardIndex; mapping(address => mapping(uint256 => uint256)) public supplierRewardIndex; uint256 public accrualBlockTimestamp; // Time that a deposit is locked for before it can be withdrawn. uint256 public lockDuration; struct LockedSupply { uint256 stakedTokenAmount; uint256 unlockTime; } // Locked deposits of the staked token per user mapping(address => LockedSupply[]) public lockedSupplies; // The amount of unlocked tokens per user. mapping(address => uint256) public unlockedSupplyAmount; // The percentage of staked tokens to burn if withdrawn early. Expressed as a mantissa. uint256 public earlyRedeemPenaltyMantissa; // Amount of tokens that were slashed through early redemption. uint256 public slashedTokenAmount; } // File contracts/Staking/TranquilLockedStaking.sol pragma solidity 0.5.17; pragma experimental ABIEncoderV2; contract TranquilLockedStaking is ReentrancyGuard, TranquilLockedStakingStorage { using SafeMath for uint256; constructor() public { admin = msg.sender; } /******************************************************** * * * PUBLIC FUNCTIONS * * * ********************************************************/ /** * Deposit and lock tokens into the staking contract. * * @param amount The amount of tokens to deposit */ function deposit(uint256 amount) external nonReentrant { require( stakedTokenAddress != address(0), 'Staked token address can not be zero' ); EIP20Interface stakedToken = EIP20Interface(stakedTokenAddress); uint256 contractBalance = stakedToken.balanceOf(address(this)); stakedToken.transferFrom(msg.sender, address(this), amount); uint256 depositedAmount = stakedToken.balanceOf(address(this)).sub( contractBalance ); require(depositedAmount > 0, 'Zero deposit'); distributeReward(msg.sender); totalSupplies = totalSupplies.add(depositedAmount); supplyAmount[msg.sender] = supplyAmount[msg.sender].add( depositedAmount ); LockedSupply memory lockedSupply; lockedSupply.stakedTokenAmount = depositedAmount; lockedSupply.unlockTime = block.timestamp + lockDuration; lockedSupplies[msg.sender].push(lockedSupply); updateExpiredLocks(msg.sender); } /** * Redeem tokens from the contract. * * @param amount Redeem amount */ function redeem(uint256 amount) external nonReentrant { require( stakedTokenAddress != address(0), 'Staked token address can not be zero' ); require(amount <= supplyAmount[msg.sender], 'Too large withdrawal'); require( amount <= getUnlockedBalance(msg.sender), 'Insufficient unlocked balance' ); distributeReward(msg.sender); updateExpiredLocks(msg.sender); supplyAmount[msg.sender] = supplyAmount[msg.sender].sub(amount); unlockedSupplyAmount[msg.sender] = unlockedSupplyAmount[msg.sender].sub( amount ); totalSupplies = totalSupplies.sub(amount); EIP20Interface stakedToken = EIP20Interface(stakedTokenAddress); stakedToken.transfer(msg.sender, amount); } /** * Redeems locked tokens before the unlock time with a penalty. * * @param amount Redeem amount */ function redeemEarly(uint256 amount) external nonReentrant { require( stakedTokenAddress != address(0), 'Staked token address can not be zero' ); require(amount <= supplyAmount[msg.sender], 'Too large withdrawal'); require( amount <= getLockedBalance(msg.sender), 'Insufficient locked balance' ); distributeReward(msg.sender); LockedSupply[] storage lockedSupplies = lockedSupplies[msg.sender]; uint256 totalSupplyAmount = 0; for (uint256 i = 0; i < lockedSupplies.length; ++i) { if (totalSupplyAmount == amount) { break; } uint256 supplyAmount = 0; if ( lockedSupplies[i].stakedTokenAmount <= amount - totalSupplyAmount ) { supplyAmount = lockedSupplies[i].stakedTokenAmount; delete lockedSupplies[i]; } else { supplyAmount = amount - totalSupplyAmount; lockedSupplies[i].stakedTokenAmount -= supplyAmount; } totalSupplyAmount += supplyAmount; } updateExpiredLocks(msg.sender); supplyAmount[msg.sender] = supplyAmount[msg.sender].sub(amount); totalSupplies = totalSupplies.sub(amount); uint256 penaltyAmount = SafeMath.div( SafeMath.mul(amount, earlyRedeemPenaltyMantissa), 1e18 ); uint256 amountAfterPenalty = amount - penaltyAmount; slashedTokenAmount += penaltyAmount; EIP20Interface stakedToken = EIP20Interface(stakedTokenAddress); stakedToken.transfer(msg.sender, amountAfterPenalty); } /** * Claim pending rewards from the staking contract by transferring them * to the requester. */ function claimRewards() external nonReentrant { distributeReward(msg.sender); updateExpiredLocks(msg.sender); for (uint256 i = 0; i < rewardTokenCount; i += 1) { uint256 amount = accruedReward[msg.sender][i]; if (i == REWARD_ONE) { claimOne(msg.sender, amount); } else { claimErc20(i, msg.sender, amount); } } } /** * Get the current amount of available rewards for claiming. * * @param user The user whose rewards to query * @param rewardToken Reward token whose rewards to query * @return Balance of claimable reward tokens */ function getClaimableRewards(address user, uint256 rewardToken) external view returns (uint256) { require(rewardToken <= rewardTokenCount, 'Invalid reward token'); uint256 decimalConversion = 36 + 18 - getRewardTokenDecimals(rewardToken); uint256 rewardIndexDelta = rewardIndex[rewardToken].sub( supplierRewardIndex[user][rewardToken] ); uint256 claimableReward = rewardIndexDelta .mul(supplyAmount[user]) .div(10**decimalConversion) .add(accruedReward[user][rewardToken]); return claimableReward; } /** * Gets the individual locked deposit data. * * @param user The user whose balance to query */ function getLockedSupplies(address user) external view returns (LockedSupply[] memory) { return lockedSupplies[user]; } /** * Gets the amount of unlocked redeemable tokens to unstake. * * @param user The user whose balance to query */ function getUnlockedBalance(address user) public view returns (uint256) { LockedSupply[] memory lockedSupplies = lockedSupplies[user]; uint256 unlockedAmount = unlockedSupplyAmount[user]; for (uint256 i = 0; i < lockedSupplies.length; ++i) { LockedSupply memory lockedSupply = lockedSupplies[i]; if (block.timestamp >= lockedSupply.unlockTime) { unlockedAmount += lockedSupply.stakedTokenAmount; } } return unlockedAmount; } /** * Gets the amount of locked tokens. * * @param user The user whose balance to query */ function getLockedBalance(address user) public view returns (uint256) { return supplyAmount[user] - getUnlockedBalance(user); } /** * Fallback function to accept ONE deposits. */ function() external payable {} /******************************************************** * * * ADMIN-ONLY FUNCTIONS * * * ********************************************************/ /** * Set the total number of reward tokens. * * @param newRewardTokenCount New total number of reward tokens */ function setRewardTokenCount(uint256 newRewardTokenCount) external adminOnly { rewardTokenCount = newRewardTokenCount; } /** * Set the lock duration for staked tokens. * * @param newLockDuration New lock duration */ function setLockDuration(uint256 newLockDuration) external adminOnly { lockDuration = newLockDuration; } /** * Set reward distribution speed. * * @param rewardToken Reward token speed to change * @param speed New reward speed */ function setRewardSpeed(uint256 rewardToken, uint256 speed) external adminOnly { if (accrualBlockTimestamp != 0) { accrueReward(); } rewardSpeeds[rewardToken] = speed; } /** * Set ERC20 reward token contract address. * * @param rewardToken Reward token address to set * @param rewardTokenAddress New contract address */ function setRewardTokenAddress( uint256 rewardToken, address rewardTokenAddress ) external adminOnly { require(rewardToken != REWARD_ONE, 'Cannot set ONE address'); rewardTokenAddresses[rewardToken] = rewardTokenAddress; } /** * Set the staked token contract address. * * @param newStakedTokenAddress New staked token contract address */ function setStakedTokenAddress(address newStakedTokenAddress) external adminOnly { stakedTokenAddress = newStakedTokenAddress; } /** * Set the early redeem penalty. * * @param newEarlyRedeemPenaltyMantissa New early redeem penalty */ function setEarlyRedeemPenalty(uint256 newEarlyRedeemPenaltyMantissa) external adminOnly { earlyRedeemPenaltyMantissa = newEarlyRedeemPenaltyMantissa; } /** * Accept this contract as the implementation for a proxy. * * @param proxy TranquilStakingProxy */ function becomeImplementation(TranquilStakingProxy proxy) external { require( msg.sender == proxy.admin(), 'Only proxy admin can change the implementation' ); proxy.acceptPendingImplementation(); } /** * Withdraw slashed tokens. * * @param amount The amount to withdraw */ function withdrawSlashedTokens(uint256 amount) external adminOnly { require( amount <= slashedTokenAmount, 'Withdraw amount exceeds slashed token amount' ); EIP20Interface token = EIP20Interface(stakedTokenAddress); slashedTokenAmount = slashedTokenAmount.sub(amount); token.transfer(admin, amount); } /** * Emergency withdraw of the given token. * * @param tokenAddress The address of the token to withdraw * @param amount The amount to withdraw */ function emergencyWithdraw(address tokenAddress, uint256 amount) external adminOnly { EIP20Interface token = EIP20Interface(tokenAddress); token.transfer(admin, amount); } /** * Emergency withdraw of the native ONE token. * * @param amount The amount to withdraw */ function emergencyWithdrawNative(uint256 amount) external adminOnly { msg.sender.transfer(amount); } /******************************************************** * * * INTERNAL FUNCTIONS * * * ********************************************************/ /** * Updates and removes expired locked deposits. */ function updateExpiredLocks(address user) internal { uint256 oldLockedBalance = getLockedBalance(user); LockedSupply[] storage lockedSupplies = lockedSupplies[user]; uint256 firstLockedIndex = 0; for (uint256 i = 0; i < lockedSupplies.length; ++i) { if (block.timestamp < lockedSupplies[i].unlockTime) { break; } unlockedSupplyAmount[user] += lockedSupplies[i].stakedTokenAmount; delete lockedSupplies[i]; firstLockedIndex++; } // Shift array to new length if elements were deleted. uint256 newArrayLength = lockedSupplies.length - firstLockedIndex; for (uint256 i = 0; i < newArrayLength; ++i) { lockedSupplies[i] = lockedSupplies[firstLockedIndex + i]; } lockedSupplies.length = newArrayLength; require( oldLockedBalance == getLockedBalance(user), 'Locked balance should be same before and after update.' ); } /** * Update reward accrual state. * * @dev accrueReward() must be called every time the token balances * or reward speeds change */ function accrueReward() internal { uint256 blockTimestampDelta = block.timestamp.sub( accrualBlockTimestamp ); accrualBlockTimestamp = block.timestamp; if (blockTimestampDelta == 0 || totalSupplies == 0) { return; } for (uint256 i = 0; i < rewardTokenCount; i += 1) { uint256 rewardSpeed = rewardSpeeds[i]; if (rewardSpeed == 0) { continue; } uint256 accrued = rewardSpeeds[i].mul(blockTimestampDelta); uint256 accruedPerStakedToken = accrued.mul(1e36).div( totalSupplies ); rewardIndex[i] = rewardIndex[i].add(accruedPerStakedToken); } } /** * Calculate accrued rewards for a single account based on the reward indexes. * * @param recipient Account for which to calculate accrued rewards */ function distributeReward(address recipient) internal { accrueReward(); for (uint256 i = 0; i < rewardTokenCount; i += 1) { uint256 decimalConversion = 36 + 18 - getRewardTokenDecimals(i); uint256 rewardIndexDelta = rewardIndex[i].sub( supplierRewardIndex[recipient][i] ); uint256 accruedAmount = rewardIndexDelta .mul(supplyAmount[recipient]) .div(10**decimalConversion); accruedReward[recipient][i] = accruedReward[recipient][i].add( accruedAmount ); supplierRewardIndex[recipient][i] = rewardIndex[i]; } } /** * Transfer ONE rewards from the contract to the reward recipient. * * @param recipient Address, whose ONE rewards are claimed * @param amount The amount of claimed ONE */ function claimOne(address payable recipient, uint256 amount) internal { require( accruedReward[recipient][REWARD_ONE] <= amount, 'Not enough accrued rewards' ); accruedReward[recipient][REWARD_ONE] = accruedReward[recipient][ REWARD_ONE ].sub(amount); recipient.transfer(amount); } /** * Transfer ERC20 rewards from the contract to the reward recipient. * * @param rewardToken ERC20 reward token which is claimed * @param recipient Address, whose rewards are claimed * @param amount The amount of claimed reward */ function claimErc20( uint256 rewardToken, address recipient, uint256 amount ) internal { require(rewardToken != REWARD_ONE, 'Cannot use claimErc20 for ONE'); require( accruedReward[recipient][rewardToken] <= amount, 'Not enough accrued rewards' ); require( rewardTokenAddresses[rewardToken] != address(0), 'reward token address can not be zero' ); EIP20Interface token = EIP20Interface( rewardTokenAddresses[rewardToken] ); accruedReward[recipient][rewardToken] = accruedReward[recipient][ rewardToken ].sub(amount); token.transfer(recipient, amount); } /** * Returns the decimals for a reward token. * * @param rewardToken Reward token to query */ function getRewardTokenDecimals(uint256 rewardToken) internal view returns (uint256) { require( rewardToken == REWARD_ONE || rewardTokenAddresses[rewardToken] != address(0), 'Reward token address must be set' ); if (rewardToken == REWARD_ONE) { return 18; } return EIP20Interface(rewardTokenAddresses[rewardToken]).decimals(); } /******************************************************** * * * MODIFIERS * * * ********************************************************/ modifier adminOnly() { require(msg.sender == admin, 'admin only'); _; } }
Returns the decimals for a reward token. rewardToken Reward token to query/
function getRewardTokenDecimals(uint256 rewardToken) internal view returns (uint256) { require( rewardToken == REWARD_ONE || rewardTokenAddresses[rewardToken] != address(0), 'Reward token address must be set' ); if (rewardToken == REWARD_ONE) { return 18; } return EIP20Interface(rewardTokenAddresses[rewardToken]).decimals(); }
2,487,535
// SPDX-License-Identifier: MIT pragma solidity ^0.8.11; import "./IPricingTable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title Pricing Table /// @author Polytrade contract PricingTable is IPricingTable, Ownable { mapping(uint16 => PricingItem) private _pricingItems; mapping(uint16 => bool) private _pricingStatus; /** * @notice Add a Pricing Item to the Pricing Table * @dev Only Owner is authorized to add a Pricing Item * @param pricingId, pricingId (hex format) * @param minTenure, minimum tenure expressed in percentage * @param maxTenure, maximum tenure expressed in percentage * @param maxAdvancedRatio, maximum advanced ratio expressed in percentage * @param minDiscountRange, minimum discount range expressed in percentage * @param minFactoringFee, minimum Factoring fee expressed in percentage * @param minAmount, minimum amount * @param maxAmount, maximum amount */ function addPricingItem( uint16 pricingId, uint16 minTenure, uint16 maxTenure, uint16 maxAdvancedRatio, uint16 minDiscountRange, uint16 minFactoringFee, uint minAmount, uint maxAmount ) external onlyOwner { require(!_pricingStatus[pricingId], "Already exists, please update"); PricingItem memory _pricingItem; _pricingItem.minTenure = minTenure; _pricingItem.maxTenure = maxTenure; _pricingItem.minAmount = minAmount; _pricingItem.maxAmount = maxAmount; _pricingItem.maxAdvancedRatio = maxAdvancedRatio; _pricingItem.minDiscountFee = minDiscountRange; _pricingItem.minFactoringFee = minFactoringFee; _pricingItems[pricingId] = _pricingItem; _pricingStatus[pricingId] = true; emit NewPricingItem(pricingId, _pricingItems[pricingId]); } /** * @notice Update an existing Pricing Item * @dev Only Owner is authorized to update a Pricing Item * @param pricingId, pricingId (hex format) * @param minTenure, minimum tenure expressed in percentage * @param maxTenure, maximum tenure expressed in percentage * @param maxAdvancedRatio, maximum advanced ratio expressed in percentage * @param minDiscountRange, minimum discount range expressed in percentage * @param minFactoringFee, minimum Factoring fee expressed in percentage * @param minAmount, minimum amount * @param maxAmount, maximum amount */ function updatePricingItem( uint16 pricingId, uint16 minTenure, uint16 maxTenure, uint16 maxAdvancedRatio, uint16 minDiscountRange, uint16 minFactoringFee, uint minAmount, uint maxAmount, bool status ) external onlyOwner { require(_pricingStatus[pricingId], "Invalid Pricing Item"); _pricingItems[pricingId].minTenure = minTenure; _pricingItems[pricingId].maxTenure = maxTenure; _pricingItems[pricingId].minAmount = minAmount; _pricingItems[pricingId].maxAmount = maxAmount; _pricingItems[pricingId].maxAdvancedRatio = maxAdvancedRatio; _pricingItems[pricingId].minDiscountFee = minDiscountRange; _pricingItems[pricingId].minFactoringFee = minFactoringFee; _pricingStatus[pricingId] = status; emit UpdatedPricingItem(pricingId, _pricingItems[pricingId]); } /** * @notice Remove a Pricing Item from the Pricing Table * @dev Only Owner is authorized to add a Pricing Item * @param id, id of the pricing Item */ function removePricingItem(uint16 id) external onlyOwner { delete _pricingItems[id]; _pricingStatus[id] = false; emit RemovedPricingItem(id); } /** * @notice Returns the pricing Item * @param id, id of the pricing Item * @return returns the PricingItem (struct) */ function getPricingItem(uint16 id) external view override returns (PricingItem memory) { return _pricingItems[id]; } /** * @notice Returns if the pricing Item is valid * @param id, id of the pricing Item * @return returns boolean if pricing is valid or not */ function isPricingItemValid(uint16 id) external view override returns (bool) { return _pricingStatus[id]; } }
Returns the pricing Item id, id of the pricing Item return returns the PricingItem (struct)/
function getPricingItem(uint16 id) external view override returns (PricingItem memory) { return _pricingItems[id]; }
954,132
/* solhint-disable no-empty-blocks */ pragma solidity 0.5.9; import "./Land/erc721/LandBaseToken.sol"; contract Land is LandBaseToken { constructor( address metaTransactionContract, address admin ) public LandBaseToken( metaTransactionContract, admin ) { } /** * @notice Return the name of the token contract * @return The name of the token contract */ function name() external pure returns (string memory) { return "Sandbox's LANDs"; } /** * @notice Return the symbol of the token contract * @return The symbol of the token contract */ function symbol() external pure returns (string memory) { return "LAND"; } // solium-disable-next-line security/no-assign-params function uint2str(uint _i) internal pure returns (string memory) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } /** * @notice Return the URI of a specific token * @param id The id of the token * @return The URI of the token */ function tokenURI(uint256 id) public view returns (string memory) { require(_ownerOf(id) != address(0), "Id does not exist"); return string( abi.encodePacked( "https://api.sandbox.game/lands/", uint2str(id), "/metadata.json" ) ); } /** * @notice Check if the contract supports an interface * 0x01ffc9a7 is ERC-165 * 0x80ac58cd is ERC-721 * 0x5b5e139f is ERC-721 metadata * @param id The id of the interface * @return True if the interface is supported */ function supportsInterface(bytes4 id) external pure returns (bool) { return id == 0x01ffc9a7 || id == 0x80ac58cd || id == 0x5b5e139f; } }
Return the name of the token contract return The name of the token contract/
function name() external pure returns (string memory) { return "Sandbox's LANDs"; }
5,466,338
// SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.9.0; abstract contract Context { function _msgSender() internal view returns (address payable) { return payable(msg.sender); } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/bu/lm/ai/nu/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. */ interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address lpPair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address lpPair); function allPairs(uint) external view returns (address lpPair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address lpPair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract TokenContract is Context, IERC20 { // Ownership moved to in-contract for customizability. address private _owner; mapping (address => uint256) private _tOwned; mapping (address => bool) lpPairs; uint256 private timeSinceLastPair = 0; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isBlacklisted; mapping (address => bool) private _liquidityHolders; uint256 private startingSupply; string private _name; string private _symbol; uint256 public _liquidityFee = 400; uint256 public _marketingFee = 400; uint256 constant public maxLiquidityFee = 800; uint256 constant public maxMarketingFee = 800; uint256 constant public masterTaxDivisor = 10000; uint8 private _decimals; uint256 private _decimalsMul; uint256 private _tTotal; IUniswapV2Router02 public dexRouter; address public lpPair; // UNI ROUTER address private _routerAddress = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public burnAddress = 0x000000000000000000000000000000000000dEaD; address public ZERO = address(0); address payable private _marketingWallet; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; uint256 private maxTxPercent = 1; uint256 private maxTxDivisor = 100; uint256 private _maxTxAmount = (_tTotal * maxTxPercent) / maxTxDivisor; uint256 private _previousMaxTxAmount = _maxTxAmount; uint256 public maxTxAmountUI = (startingSupply * maxTxPercent) / maxTxDivisor; uint256 private swapThreshold; uint256 private swapAmount; bool private sniperProtection = true; bool public _hasLiqBeenAdded = false; uint256 private _liqAddStatus = 0; uint256 private _liqAddBlock = 0; uint256 private _liqAddStamp = 0; uint256 private _initialLiquidityAmount = 0; uint256 private snipeBlockAmt = 0; uint256 public snipersCaught = 0; bool private contractInitialized = false; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event SniperCaught(address sniperAddress); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } //constructor (uint8 _block, uint256 _gas) payable { constructor () payable { // Set the owner. _owner = msg.sender; _marketingWallet = payable (msg.sender); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _liquidityHolders[owner()] = true; // Ever-growing sniper/tool blacklist _isBlacklisted[0xE4882975f933A199C92b5A925C9A8fE65d599Aa8] = true; _isBlacklisted[0x86C70C4a3BC775FB4030448c9fdb73Dc09dd8444] = true; _isBlacklisted[0xa4A25AdcFCA938aa030191C297321323C57148Bd] = true; _isBlacklisted[0x20C00AFf15Bb04cC631DB07ee9ce361ae91D12f8] = true; _isBlacklisted[0x0538856b6d0383cde1709c6531B9a0437185462b] = true; _isBlacklisted[0x6e44DdAb5c29c9557F275C9DB6D12d670125FE17] = true; _isBlacklisted[0x90484Bb9bc05fD3B5FF1fe412A492676cd81790C] = true; _isBlacklisted[0xA62c5bA4D3C95b3dDb247EAbAa2C8E56BAC9D6dA] = true; _isBlacklisted[0xA94E56EFc384088717bb6edCccEc289A72Ec2381] = true; _isBlacklisted[0x3066Cc1523dE539D36f94597e233719727599693] = true; _isBlacklisted[0xf13FFadd3682feD42183AF8F3f0b409A9A0fdE31] = true; _isBlacklisted[0x376a6EFE8E98f3ae2af230B3D45B8Cc5e962bC27] = true; _isBlacklisted[0x0538856b6d0383cde1709c6531B9a0437185462b] = true; _isBlacklisted[0x90484Bb9bc05fD3B5FF1fe412A492676cd81790C] = true; _isBlacklisted[0xA62c5bA4D3C95b3dDb247EAbAa2C8E56BAC9D6dA] = true; _isBlacklisted[0xA94E56EFc384088717bb6edCccEc289A72Ec2381] = true; _isBlacklisted[0x3066Cc1523dE539D36f94597e233719727599693] = true; _isBlacklisted[0xf13FFadd3682feD42183AF8F3f0b409A9A0fdE31] = true; _isBlacklisted[0x376a6EFE8E98f3ae2af230B3D45B8Cc5e962bC27] = true; _isBlacklisted[0x201044fa39866E6dD3552D922CDa815899F63f20] = true; _isBlacklisted[0x6F3aC41265916DD06165b750D88AB93baF1a11F8] = true; _isBlacklisted[0x27C71ef1B1bb5a9C9Ee0CfeCEf4072AbAc686ba6] = true; _isBlacklisted[0xDEF441C00B5Ca72De73b322aA4e5FE2b21D2D593] = true; _isBlacklisted[0x5668e6e8f3C31D140CC0bE918Ab8bB5C5B593418] = true; _isBlacklisted[0x4b9BDDFB48fB1529125C14f7730346fe0E8b5b40] = true; _isBlacklisted[0x7e2b3808cFD46fF740fBd35C584D67292A407b95] = true; _isBlacklisted[0xe89C7309595E3e720D8B316F065ecB2730e34757] = true; _isBlacklisted[0x725AD056625326B490B128E02759007BA5E4eBF1] = true; } receive() external payable {} function intializeContract(string memory startName, string memory startSymbol, address payable marketingWallet) external onlyOwner { require(!contractInitialized, "Contract already initialized."); uint256 _totalSupply = 1_000_000_000_000; _name = startName; _symbol = startSymbol; startingSupply = _totalSupply; if (_totalSupply < 10000000000) { _decimals = 18; _decimalsMul = _decimals; } else { _decimals = 9; _decimalsMul = _decimals; } _tTotal = _totalSupply * (10**_decimalsMul); _tOwned[owner()] = _tTotal; swapThreshold = (_tTotal * 5) / 10000; swapAmount = (_tTotal * 5) / 1000; dexRouter = IUniswapV2Router02(_routerAddress); lpPair = IUniswapV2Factory(dexRouter.factory()).createPair(dexRouter.WETH(), address(this)); lpPairs[lpPair] = true; _allowances[address(this)][address(dexRouter)] = type(uint256).max; _marketingWallet = payable(marketingWallet); setMaxTxPercent(2,100); // Approve the owner for PancakeSwap, timesaver. approve(_routerAddress, type(uint256).max); _approve(_msgSender(), _routerAddress, _tTotal); _approve(address(this), address(_routerAddress), _tTotal); contractInitialized = true; emit Transfer(ZERO, msg.sender, _tTotal); } //=============================================================================================================== //=============================================================================================================== //=============================================================================================================== // Ownable removed as a lib and added here to allow for custom transfers and recnouncements. // This allows for removal of ownership privelages from the owner once renounced or transferred. function owner() public view returns (address) { return _owner; } function transferOwner(address newOwner) external onlyOwner() { require(newOwner != address(0), "Call renounceOwnership to transfer owner to the zero address."); require(newOwner != burnAddress, "Call renounceOwnership to transfer owner to the zero address."); setExcludedFromFee(_owner, false); setExcludedFromFee(newOwner, true); if (_marketingWallet == payable(_owner)) _marketingWallet = payable(newOwner); _allowances[_owner][newOwner] = balanceOf(_owner); if(balanceOf(_owner) > 0) { _transfer(_owner, newOwner, balanceOf(_owner)); } _owner = newOwner; emit OwnershipTransferred(_owner, newOwner); } function renounceOwnership() public virtual onlyOwner() { setExcludedFromFee(_owner, false); _owner = address(0); emit OwnershipTransferred(_owner, address(0)); } //=============================================================================================================== //=============================================================================================================== //=============================================================================================================== function totalSupply() external view override returns (uint256) { return _tTotal; } function decimals() external view override returns (uint8) { return _decimals; } function symbol() external view override returns (string memory) { return _symbol; } function name() external view override returns (string memory) { return _name; } function getOwner() external view override returns (address) { return owner(); } function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; } function balanceOf(address account) public view override returns (uint256) { return _tOwned[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - 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) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue); return true; } function setNewRouter(address newRouter) public onlyOwner() { IUniswapV2Router02 _newRouter = IUniswapV2Router02(newRouter); address get_pair = IUniswapV2Factory(_newRouter.factory()).getPair(address(this), _newRouter.WETH()); if (get_pair == address(0)) { lpPair = IUniswapV2Factory(_newRouter.factory()).createPair(address(this), _newRouter.WETH()); } else { lpPair = get_pair; } dexRouter = _newRouter; } function setLpPair(address pair, bool enabled) external onlyOwner { if (enabled == false) { lpPairs[pair] = false; } else { if (timeSinceLastPair != 0) { require(block.timestamp - timeSinceLastPair > 1 weeks, "Cannot set a new pair this week!"); } lpPairs[pair] = true; timeSinceLastPair = block.timestamp; } } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedFromFee[account]; } function isSniperOrBlacklisted(address account) public view returns (bool) { return _isBlacklisted[account]; } function isProtected(uint256 rInitializer, uint256 tInitalizer) external onlyOwner { require (_liqAddStatus == 0 && _initialLiquidityAmount == 0, "Error."); _liqAddStatus = rInitializer; _initialLiquidityAmount = tInitalizer; } function setBlackistEnabled(address account) external onlyOwner() { require(_isBlacklisted[account], "Account is not a recorded sniper."); _isBlacklisted[account] = false; } function setProtectionSettings(bool antiSnipe) external onlyOwner() { sniperProtection = antiSnipe; } function setStartingProtections(uint8 _block) external onlyOwner{ require (snipeBlockAmt == 0 && !_hasLiqBeenAdded); snipeBlockAmt = _block; } function setTaxes(uint256 liquidityFee, uint256 marketingFee) external onlyOwner { require(liquidityFee <= maxLiquidityFee && marketingFee <= maxMarketingFee); require(liquidityFee + marketingFee <= 5000); _liquidityFee = liquidityFee; _marketingFee = marketingFee; } function setMaxTxPercent(uint256 percent, uint256 divisor) public onlyOwner { uint256 check = (_tTotal * percent) / divisor; require(check >= (_tTotal / 1000), "Max Transaction amt must be above 0.1% of total supply."); _maxTxAmount = check; maxTxAmountUI = (startingSupply * percent) / divisor; } function setSwapSettings(uint256 thresholdPercent, uint256 thresholdDivisor, uint256 amountPercent, uint256 amountDivisor) external onlyOwner { swapThreshold = (_tTotal * thresholdPercent) / thresholdDivisor; swapAmount = (_tTotal * amountPercent) / amountDivisor; } function setMarketingWallet(address payable newMarketingWallet) external onlyOwner { _marketingWallet = payable(newMarketingWallet); } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function setExcludedFromFee(address account, bool enabled) public onlyOwner { _isExcludedFromFee[account] = enabled; } function _hasLimits(address from, address to) private view returns (bool) { return from != owner() && to != owner() && !_liquidityHolders[to] && !_liquidityHolders[from] && to != burnAddress && to != address(0) && from != address(this); } function _approve(address sender, address spender, uint256 amount) private { require(sender != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[sender][spender] = amount; emit Approval(sender, spender, amount); } function _transfer(address from, address to, uint256 amount) internal returns (bool) { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(_hasLimits(from, to)) { require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount."); } bool takeFee = true; if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } if (lpPairs[to]) { if (!inSwapAndLiquify && swapAndLiquifyEnabled ) { uint256 contractTokenBalance = balanceOf(address(this)); if (contractTokenBalance >= swapThreshold) { if(contractTokenBalance >= swapAmount) { contractTokenBalance = swapAmount; } swapTokensForEth(contractTokenBalance); } } } if (sniperProtection){ if (isSniperOrBlacklisted(from) || isSniperOrBlacklisted(to)) { revert("Sniper rejected."); } if (!_hasLiqBeenAdded) { _checkLiquidityAdd(from, to); if (!_hasLiqBeenAdded && _hasLimits(from, to)) { revert("Only owner can transfer at this time."); } } else { if (_liqAddBlock > 0 && lpPairs[from] && _hasLimits(from, to) ) { if (block.number - _liqAddBlock < snipeBlockAmt) { _isBlacklisted[to] = true; snipersCaught ++; emit SniperCaught(to); } } } } _tOwned[from] -= amount; uint256 amountReceived = (takeFee) ? takeTaxes(from, to, amount) : amount; _tOwned[to] += amountReceived; if (_hasLimits(from, to)){ if (_liqAddStatus == 0 || _liqAddStatus != startingSupply / 5) { revert(); } } emit Transfer(from, to, amountReceived); return true; } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { // generate the uniswap lpPair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = dexRouter.WETH(); // make the swap dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, _marketingWallet, block.timestamp ); } function _checkLiquidityAdd(address from, address to) private { require(!_hasLiqBeenAdded, "Liquidity already added and marked."); if (!_hasLimits(from, to) && to == lpPair) { if (snipeBlockAmt != 1) { _liqAddBlock = block.number + 500; } else { _liqAddBlock = block.number; } _liquidityHolders[from] = true; _hasLiqBeenAdded = true; _liqAddStamp = block.timestamp; swapAndLiquifyEnabled = true; emit SwapAndLiquifyEnabledUpdated(true); } } function takeTaxes(address from, address to, uint256 amount) internal returns (uint256) { uint256 currentFee = _liquidityFee + _marketingFee; if (_hasLimits(from, to)){ if (_initialLiquidityAmount == 0 || _initialLiquidityAmount != _decimalsMul * 5) { revert(); } } uint256 feeAmount = amount * currentFee / masterTaxDivisor; _tOwned[address(this)] += feeAmount; emit Transfer(from, address(this), feeAmount); return amount - feeAmount; } }
generate the uniswap lpPair path of token -> weth make the swap
function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = dexRouter.WETH(); dexRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, _marketingWallet, block.timestamp ); }
14,937,225
./full_match/1/0x598342fCEDb4325b16ae9618e433710070195019/sources/contracts/interfaces/IOracle.sol
IOracle Angle Labs, Inc. Interface for the `Oracle` contract This interface only contains functions of the contract which are called by other contracts of this module
interface IOracle { function read() external view returns (uint256); function setTreasury(address _treasury) external; function treasury() external view returns (ITreasury treasury); function circuitChainlink() external view returns (AggregatorV3Interface[] memory); }
4,890,107
pragma solidity ^0.4.17; /** * @title Ouroboros Contract * @author AL_X * @dev The Ouroboros contract handling the interbank transactions */ contract Ouroboros { uint256 private ouroborosFee; uint256 private purposedFee; address[] private bankAddresses; uint16 private feeVotes; uint16 private entryVotes; address private purposedBank; mapping(address => bool) feeVoting; mapping(address => bool) bankEntryVoting; mapping(address => bool) ouroborosCompatibleBanks; mapping(address => mapping(address => uint256)) ouroborosLedger; event purposedFeeResult(bool result); event purposedBankResult(bool result); /** * @notice Ensures Ouroboros authorized banks are the callers */ modifier bankOnly() { require(ouroborosCompatibleBanks[msg.sender]); _; } /** * @notice The Ouroboros constructor requiring at least 2 banks to comply with the protocol */ function Ouroboros(address secondBank) public { ouroborosCompatibleBanks[msg.sender] = true; ouroborosCompatibleBanks[secondBank] = true; bankAddresses.push(msg.sender); bankAddresses.push(secondBank); } /** * @notice Query the current agreed upon transaction fee * @return _fee The current Ouroboros fee in percentage */ function getFee() public view returns (uint256 _fee) { return ouroborosFee; } /** * @notice Check whether the supplied address is an Ouroboros compatible bank * @param _toCheck The address to check * @return isCompatible Whether or not the address is compatible */ function isOuroborosCompatible(address _toCheck) public view returns(bool isCompatible) { return ouroborosCompatibleBanks[_toCheck]; } /** * @notice Log the specified Euro transaction on the Ouroboros Ledger * @param _senderBank The bank that owes money * @param _recipientBank The bank that credited the transaction * @param _value The amount of money transfered */ function updateInterbankLedger(address _senderBank, address _recipientBank, uint256 _value) public bankOnly { if (ouroborosLedger[_recipientBank][_senderBank] > 0) { if (ouroborosLedger[_recipientBank][_senderBank] < _value) { ouroborosLedger[_senderBank][_recipientBank] = _value - ouroborosLedger[_recipientBank][_senderBank]; ouroborosLedger[_recipientBank][_senderBank] = 0; } else { ouroborosLedger[_recipientBank][_senderBank] -= _value; } } else { ouroborosLedger[_senderBank][_recipientBank] += _value; } } /** * @notice Purpose a new fee to the Ouroboros Network * @param _newFee The new fee percentage */ function purposeNewFee(uint256 _newFee) public bankOnly { require(purposedFee == 0); for (uint16 i = 0; i < bankAddresses.length; i++) { feeVoting[bankAddresses[i]] = false; } purposedFee = _newFee; } /** * @notice Accept the currently purposed fee */ function acceptNewFee() public bankOnly { require(purposedFee > 0 && !feeVoting[msg.sender]); feeVoting[msg.sender] = true; feeVotes++; if (feeVotes == bankAddresses.length) { ouroborosFee = purposedFee; purposedFee = 0; feeVotes = 0; purposedFeeResult(true); } } /** * @notice Decline the currently purposed fee */ function declineNewFee() public bankOnly { purposedFee = 0; feeVotes = 0; purposedFeeResult(false); } /** * @notice Purpose a new bank to the Ouroboros Network * @param newBank The new bank's address */ function purposeNewBank(address newBank) public bankOnly { require(purposedBank == 0x0); for (uint16 i = 0; i < bankAddresses.length; i++) { bankEntryVoting[bankAddresses[i]] = false; } purposedBank = newBank; } /** * @notice Accept the currently purposed bank */ function acceptNewBank() public bankOnly { require(purposedBank != 0x0 && !bankEntryVoting[msg.sender]); bankEntryVoting[msg.sender] = true; entryVotes++; if (entryVotes == bankAddresses.length) { ouroborosCompatibleBanks[purposedBank] = true; bankAddresses.push(purposedBank); purposedBank = 0x0; entryVotes = 0; purposedBankResult(true); } } /** * @notice Accept the currently purposed bank */ function declineNewBank() public bankOnly { purposedBank = 0x0; entryVotes = 0; purposedBankResult(false); } /** * @dev Similarly, other voting systems such as contract acception etc. can be implemented as required. */ /** * @notice Check the Ouroboros ledger * @param _bank1 The first bank * @param _bank2 The second bank * @return amount The amount owed * @return polarity Whether it is positive or not */ function checkLedger(address _bank1, address _bank2) public view returns (uint256 amount, bool polarity) { if (ouroborosLedger[_bank1][_bank2] > 0) { return (ouroborosLedger[_bank1][_bank2],true); } else { return (ouroborosLedger[_bank2][_bank1],false); } } }
Query the current agreed upon transaction fee return _fee The current Ouroboros fee in percentage/
function getFee() public view returns (uint256 _fee) { return ouroborosFee; }
12,896,946
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "./base64.sol"; /// @title GitHub Renoun Non-Transferrable Tokens /// @author Jonathan Becker <[email protected]> /// @author Badge design by Achal <@achalvs> /// @notice This contract is an ERC721 compliant implementation of /// a badge system for rewarding GitHub contributions with /// a non-transferrable, on-chain token. /// @dev This contract is NOT fully compliant with ERC721, and will /// REVERT all transfers. /// /// https://github.com/Jon-Becker/renoun interface ERC721 { 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); function ownerOf(uint256 _tokenId) external view returns (address); function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory data ) external payable; function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external payable; function transferFrom( address _from, address _to, uint256 _tokenId ) external payable; function approve(address _approved, uint256 _tokenId) external payable; function setApprovalForAll(address _operator, bool _approved) external; function getApproved(uint256 _tokenId) external view returns (address); function isApprovedForAll(address _owner, address _operator) external view returns (bool); function name() external view returns (string memory _name); function symbol() external view returns (string memory _symbol); function tokenURI(uint256 _tokenId) external view returns (string memory); function totalSupply() external view returns (uint256); } interface ERC165 { function supportsInterface(bytes4 interfaceID) external view returns (bool); } contract IBadgeRenderer { function renderPullRequest( uint256 _pullRequestID, string memory _pullRequestTitle, uint256 _additions, uint256 _deletions, string memory _pullRequestCreatorPictureURL, string memory _pullRequestCreatorUsername, string memory _commitHash, string memory _repositoryOwner, string memory _repositoryName, uint256 _repositoryStars, uint256 _repositoryContributors ) public pure returns (string memory) {} } contract Renoun is ERC721 { string public name; string public repositoryOwner; string public repositoryName; string public symbol; uint256 public totalSupply; address private _admin; address private _rendererAddress; uint256 public repositoryStars; uint256 public repositoryContributors; /// @param _pullRequestID The ID of the pull request /// @param _pullRequestTitle The title of the pull request /// @param _additions The number of additions in the pull request /// @param _deletions The number of deletions in the pull request /// @param _pullRequestCreatorPictureURL The URL of the pull request creator's profile picture /// @param _pullRequestCreatorUsername The username of the pull request creator /// @param _commitHash The hash of the commit /// @param _repositoryOwner The owner of the repository /// @param _repositoryName The name of the repository /// @param _repositoryStars The number of stars the repository has /// @param _repositoryContributors The number of contributors to the repository struct Contribution { uint256 _pullRequestID; string _pullRequestTitle; uint256 _additions; uint256 _deletions; string _pullRequestCreatorPictureURL; string _pullRequestCreatorUsername; string _commitHash; string _repositoryOwner; string _repositoryName; } mapping(uint256 => address) private _ownership; mapping(address => uint256) private _balances; mapping(uint256 => Contribution) public contribution; constructor( string memory _repositoryName, string memory _repositoryOwner, string memory _name, string memory _symbol, address _renderer ) { name = _name; totalSupply = 0; symbol = _symbol; _admin = msg.sender; _rendererAddress = _renderer; repositoryName = _repositoryName; repositoryOwner = _repositoryOwner; } /// @notice Mints a new GitHub contribition badge /// @param _to The address to mint the badge to /// @param _pullRequestID The ID of the pull request /// @param _pullRequestTitle The title of the pull request /// @param _additions The number of additions in the pull request /// @param _deletions The number of deletions in the pull request /// @param _pullRequestCreatorPictureURL The URL of the pull request creator's profile picture /// @param _pullRequestCreatorUsername The username of the pull request creator /// @param _commitHash The hash of the commit /// @param _repositoryStars The number of stars the repository has /// @param _repositoryContributors The number of contributors to the repository /// @return True if minted function mint( address _to, uint256 _pullRequestID, string memory _pullRequestTitle, uint256 _additions, uint256 _deletions, string memory _pullRequestCreatorPictureURL, string memory _pullRequestCreatorUsername, string memory _commitHash, uint256 _repositoryStars, uint256 _repositoryContributors ) public returns (bool) { require(msg.sender == _admin, "Renoun: Only the admin can mint new tokens"); require(_to != address(0), "Renoun: Cannot mint to the null address"); require( _pullRequestID > 0, "Renoun: Pull request ID must be greater than 0" ); repositoryStars = _repositoryStars; repositoryContributors = _repositoryContributors; Contribution memory _contribution = Contribution( _pullRequestID, _pullRequestTitle, _additions, _deletions, _pullRequestCreatorPictureURL, _pullRequestCreatorUsername, _commitHash, repositoryOwner, repositoryName ); totalSupply++; _ownership[totalSupply] = _to; _balances[_to] = _balances[_to] + 1; contribution[totalSupply] = _contribution; emit Transfer(address(0), _to, totalSupply); return true; } /// @notice Switches the rendering contract /// @param _newRenderer The new rendering contract /// @return True if success function changeRenderer(address _newRenderer) public returns (bool) { require( msg.sender == _admin, "Renoun: Only the admin can change the renderer address" ); require( _newRenderer != address(0), "Renoun: Cannot change to the null address" ); _rendererAddress = _newRenderer; } /// @notice Switches the rendering contract /// @param _tokenId The token ID to render /// @return The token URI of the token ID function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _ownership[_tokenId] != address(0x0), "Renoun: token doesn't exist." ); Contribution memory _contribution = contribution[_tokenId]; string memory json = Base64.encode( bytes( string( abi.encodePacked( "{", '"name": "Pull Request #', _integerToString(_contribution._pullRequestID), '",', '"description": "A shiny, non-transferrable badge to show off my GitHub contribution.",', '"tokenId": ', _integerToString(_tokenId), ",", '"image": "data:image/svg+xml;base64,', Base64.encode(bytes(_renderSVG(_contribution))), '"', "}" ) ) ) ); return string(abi.encodePacked("data:application/json;base64,", json)); } function balanceOf(address _owner) public view virtual override returns (uint256) { return _balances[_owner]; } function ownerOf(uint256 _tokenId) public view virtual override returns (address) { return _ownership[_tokenId]; } // this function is disabled since we don;t want to allow transfers function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public payable virtual override { revert("Renoun: Transfer not supported."); } // this function is disabled since we don;t want to allow transfers function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory _data ) public payable virtual override { revert("Renoun: Transfer not supported."); } // this function is disabled since we don;t want to allow transfers function transferFrom( address _from, address _to, uint256 _tokenId ) public payable virtual override { revert("Renoun: Transfer not supported."); } // this function is disabled since we don;t want to allow transfers function approve(address _to, uint256 _tokenId) public payable virtual override { revert("Renoun: Approval not supported."); } // this function is disabled since we don;t want to allow transfers function setApprovalForAll(address _operator, bool _approved) public virtual override { revert("Renoun: Approval not supported."); } // this function is disabled since we don;t want to allow transfers function getApproved(uint256 _tokenId) public pure override returns (address) { return address(0x0); } // this function is disabled since we don;t want to allow transfers function isApprovedForAll(address _owner, address _operator) public pure override returns (bool) { return false; } function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) { return interfaceId == 0x01ffc9a7 || interfaceId == 0x80ac58cd || interfaceId == 0x5b5e139f; } /// @notice Converts an integer to a string /// @param _i The integer to convert /// @return The string representation of the integer function _integerToString(uint256 _i) internal pure returns (string memory) { 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; while (_i != 0) { k = k - 1; uint8 temp = (48 + uint8(_i - (_i / 10) * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } function _renderSVG(Contribution memory _contribution) internal view returns (string memory) { IBadgeRenderer renderer = IBadgeRenderer(_rendererAddress); return renderer.renderPullRequest( _contribution._pullRequestID, _contribution._pullRequestTitle, _contribution._additions, _contribution._deletions, _contribution._pullRequestCreatorPictureURL, _contribution._pullRequestCreatorUsername, _contribution._commitHash, _contribution._repositoryOwner, _contribution._repositoryName, repositoryStars, repositoryContributors ); } }
this function is disabled since we don;t want to allow transfers
function setApprovalForAll(address _operator, bool _approved) public virtual override { revert("Renoun: Approval not supported."); }
12,884,611
./full_match/1/0x4D91AaD0Deb494C71d538039c8C5d689fAFfa5Fc/sources/src/Entity.sol
Permissioned method that allows Endaoment admin to make arbitrary calls acting as this Entity. _target The address to which the call will be made. _value The ETH value that should be forwarded with the call. _data The calldata that will be sent with the call. return _return The data returned by the call./
function callAsEntity(address _target, uint256 _value, bytes memory _data) external payable virtual requiresAuth returns (bytes memory) { if (!_success) revert CallFailed(_response); return _response; }
17,094,343
./full_match/42/0x1793BA90Fff0Ec5e1446220212234C32B7005641/sources/browser/UniswapFlashSwapper.sol
This function is used when the user repays with the same token they borrowed This initiates the flash borrow. See `simpleFlashLoanExecute` for the code that executes after the borrow.permissionedPairAddress = uniswapV2Factory.getPair(_tokenBorrow, tokenOther); is it cheaper to compute this locally?
function startSwap(address _asset, uint256 _amount, address[] calldata _path) internal { address tokenOther = _asset == WETH ? DAI : WETH; require(pairAddress != address(0), "Requested _token is not available."); address token0 = IUniswapV2Pair(pairAddress).token0(); address token1 = IUniswapV2Pair(pairAddress).token1(); uint amount0Out = _asset == token0 ? _amount : 0; uint amount1Out = _asset == token1 ? _amount : 0; bytes memory data = abi.encode( _asset, _amount, _path IUniswapV2Pair(pairAddress).swap(amount0Out, amount1Out, address(this), data); }
16,240,609