file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
pragma solidity 0.5.11; pragma experimental "ABIEncoderV2"; import "../libs/LibStateChannelApp.sol"; contract MChallengeRegistryCore { // A mapping of appIdentityHash to AppChallenge structs which represents // the current on-chain status of some particular application's state. mapping (bytes32 => LibStateChannelApp.AppChallenge) public appChallenges; // A mapping of appIdentityHash to outcomes mapping (bytes32 => bytes) public appOutcomes; /// @notice Compute a unique hash for a single instance of an App /// @param appIdentity An `AppIdentity` struct that encodes all unique info for an App /// @return A bytes32 hash of the AppIdentity function appIdentityToHash( LibStateChannelApp.AppIdentity memory appIdentity ) internal pure returns (bytes32) { return keccak256( abi.encode(appIdentity.channelNonce, appIdentity.participants) ); } /// @notice Compute a unique hash for the state of a channelized app instance /// @param identityHash The unique hash of an `AppIdentity` /// @param appStateHash The hash of the app state to be signed /// @param versionNumber The versionNumber corresponding to the version of the state /// @param timeout A dynamic timeout value representing the timeout for this state /// @return A bytes32 hash of the RLP encoded arguments function computeAppChallengeHash( bytes32 identityHash, bytes32 appStateHash, uint256 versionNumber, uint256 timeout ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( byte(0x19), identityHash, versionNumber, timeout, appStateHash ) ); } /// @notice Compute a unique hash for an action used in this channel application /// @param turnTaker The address of the user taking the action /// @param previousState The hash of a state this action is being taken on /// @param action The ABI encoded version of the action being taken /// @param versionNumber The versionNumber of the state this action is being taken on /// @return A bytes32 hash of the arguments function computeActionHash( address turnTaker, bytes32 previousState, bytes memory action, uint256 versionNumber ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( byte(0x19), turnTaker, previousState, action, versionNumber ) ); } }
@notice Compute a unique hash for an action used in this channel application @param turnTaker The address of the user taking the action @param previousState The hash of a state this action is being taken on @param action The ABI encoded version of the action being taken @param versionNumber The versionNumber of the state this action is being taken on @return A bytes32 hash of the arguments
function computeActionHash( address turnTaker, bytes32 previousState, bytes memory action, uint256 versionNumber ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( byte(0x19), turnTaker, previousState, action, versionNumber ) ); }
14,073,457
[ 1, 7018, 279, 3089, 1651, 364, 392, 1301, 1399, 316, 333, 1904, 2521, 225, 7005, 56, 6388, 1021, 1758, 434, 326, 729, 13763, 326, 1301, 225, 2416, 1119, 1021, 1651, 434, 279, 919, 333, 1301, 353, 3832, 9830, 603, 225, 1301, 1021, 10336, 45, 3749, 1177, 434, 326, 1301, 3832, 9830, 225, 1177, 1854, 1021, 1177, 1854, 434, 326, 919, 333, 1301, 353, 3832, 9830, 603, 327, 432, 1731, 1578, 1651, 434, 326, 1775, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 3671, 1803, 2310, 12, 203, 565, 1758, 7005, 56, 6388, 16, 203, 565, 1731, 1578, 2416, 1119, 16, 203, 565, 1731, 3778, 1301, 16, 203, 565, 2254, 5034, 1177, 1854, 203, 225, 262, 203, 565, 2713, 203, 565, 16618, 203, 565, 1135, 261, 3890, 1578, 13, 203, 225, 288, 203, 565, 327, 417, 24410, 581, 5034, 12, 203, 1377, 24126, 18, 3015, 4420, 329, 12, 203, 3639, 1160, 12, 20, 92, 3657, 3631, 203, 3639, 7005, 56, 6388, 16, 203, 3639, 2416, 1119, 16, 203, 3639, 1301, 16, 203, 3639, 1177, 1854, 203, 1377, 262, 203, 565, 11272, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x67bC2461000cfbe67e9b623EC8B460168BdEC5F0/sources/MainStorage.sol
NOLINT: uninitialized-state.
mapping(uint256 => uint256) assetTypeToQuantum;
2,863,643
[ 1, 50, 1741, 3217, 30, 640, 13227, 17, 2019, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3310, 559, 774, 19471, 379, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/71402/0x2066CAe939E14599f6ED79036b30541328B4C9B6/sources/_balancer-labs/v2-interfaces/contracts/pool-linear/IUnbuttonToken.sol
Balancer only supports ERC20 tokens, so we use this intermediate interface to enforce ERC20-ness of UnbuttonTokens. solhint-disable-previous-line no-empty-blocks
interface IUnbuttonToken is IButtonWrapper, IERC20 { }
7,092,738
[ 1, 6444, 1338, 6146, 4232, 39, 3462, 2430, 16, 1427, 732, 999, 333, 12110, 1560, 358, 12980, 4232, 39, 3462, 17, 4496, 434, 1351, 5391, 5157, 18, 3704, 11317, 17, 8394, 17, 11515, 17, 1369, 1158, 17, 5531, 17, 7996, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 984, 5391, 1345, 353, 467, 3616, 3611, 16, 467, 654, 39, 3462, 288, 203, 203, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 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; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract MultiOwnable { mapping (address => bool) public isOwner; address[] public ownerHistory; uint8 public ownerCount; event OwnerAddedEvent(address indexed _newOwner); event OwnerRemovedEvent(address indexed _oldOwner); function MultiOwnable() public { // Add default owner address owner = msg.sender; ownerHistory.push(owner); isOwner[owner] = true; ownerCount++; } modifier onlyOwner() { require(isOwner[msg.sender]); _; } function ownerHistoryCount() public view returns (uint) { return ownerHistory.length; } /** Add extra owner. */ function addOwner(address owner) onlyOwner public { require(owner != address(0)); require(!isOwner[owner]); ownerHistory.push(owner); isOwner[owner] = true; ownerCount++; OwnerAddedEvent(owner); } /** Remove extra owner. */ function removeOwner(address owner) onlyOwner public { // This check is neccessary to prevent a situation where all owners // are accidentally removed, because we do not want an ownable contract // to become an orphan. require(ownerCount > 1); require(isOwner[owner]); isOwner[owner] = false; ownerCount--; OwnerRemovedEvent(owner); } } contract Pausable is Ownable { bool public paused; modifier ifNotPaused { require(!paused); _; } modifier ifPaused { require(paused); _; } // Called by the owner on emergency, triggers paused state function pause() external onlyOwner ifNotPaused { paused = true; } // Called by the owner on end of emergency, returns to normal state function resume() external onlyOwner ifPaused { paused = false; } } contract ERC20 { uint256 public totalSupply; function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is ERC20 { using SafeMath for uint; mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); 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. function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); 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. function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; 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. function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract CommonToken is StandardToken, MultiOwnable { string public constant name = 'White Rabbit Token'; string public constant symbol = 'WRT'; uint8 public constant decimals = 18; // The main account that holds all tokens from the time token created and during all tokensales. address public seller; // saleLimit (e18) Maximum amount of tokens for sale across all tokensales. // Reserved tokens formula: 16% Team + 6% Partners + 5% Advisory Board + 15% WR reserve 1 = 42% // For sale formula: 40% for sale + 1.5% Bounty + 16.5% WR reserve 2 = 58% uint256 public constant saleLimit = 110200000 ether; // Next fields are for stats: uint256 public tokensSold; // (e18) Number of tokens sold through all tiers or tokensales. uint256 public totalSales; // Total number of sales (including external sales) made through all tiers or tokensales. // Lock the transfer functions during tokensales to prevent price speculations. bool public locked = true; event SellEvent(address indexed _seller, address indexed _buyer, uint256 _value); event ChangeSellerEvent(address indexed _oldSeller, address indexed _newSeller); event Burn(address indexed _burner, uint256 _value); event Unlock(); function CommonToken( address _seller ) MultiOwnable() public { require(_seller != 0); seller = _seller; totalSupply = 190000000 ether; balances[seller] = totalSupply; Transfer(0x0, seller, totalSupply); } modifier ifUnlocked() { require(isOwner[msg.sender] || !locked); _; } /** * An address can become a new seller only in case it has no tokens. * This is required to prevent stealing of tokens from newSeller via * 2 calls of this function. */ function changeSeller(address newSeller) onlyOwner public returns (bool) { require(newSeller != address(0)); require(seller != newSeller); // To prevent stealing of tokens from newSeller via 2 calls of changeSeller: require(balances[newSeller] == 0); address oldSeller = seller; uint256 unsoldTokens = balances[oldSeller]; balances[oldSeller] = 0; balances[newSeller] = unsoldTokens; Transfer(oldSeller, newSeller, unsoldTokens); seller = newSeller; ChangeSellerEvent(oldSeller, newSeller); return true; } /** * User-friendly alternative to sell() function. */ function sellNoDecimals(address _to, uint256 _value) public returns (bool) { return sell(_to, _value * 1e18); } function sell(address _to, uint256 _value) onlyOwner public returns (bool) { // Check that we are not out of limit and still can sell tokens: if (saleLimit > 0) require(tokensSold.add(_value) <= saleLimit); require(_to != address(0)); require(_value > 0); require(_value <= balances[seller]); balances[seller] = balances[seller].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(seller, _to, _value); totalSales++; tokensSold = tokensSold.add(_value); SellEvent(seller, _to, _value); return true; } function transfer(address _to, uint256 _value) ifUnlocked public returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) ifUnlocked public returns (bool) { return super.transferFrom(_from, _to, _value); } function burn(uint256 _value) public returns (bool) { require(_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Transfer(msg.sender, 0x0, _value); Burn(msg.sender, _value); return true; } /** Can be called once by super owner. */ function unlock() onlyOwner public { require(locked); locked = false; Unlock(); } } // TODO finish whitelist contract CommonWhitelist is MultiOwnable { mapping(address => bool) public isAllowed; // Historical array of wallet that have bben added to whitelist, // even if some addresses have been removed later such wallet still remaining // in the history. This is Solidity optimization for work with large arrays. address[] public history; event AddedEvent(address indexed wallet); event RemovedEvent(address indexed wallet); function CommonWhitelist() MultiOwnable() public {} function historyCount() public view returns (uint) { return history.length; } function add(address _wallet) internal { require(_wallet != address(0)); require(!isAllowed[_wallet]); history.push(_wallet); isAllowed[_wallet] = true; AddedEvent(_wallet); } function addMany(address[] _wallets) public onlyOwner { for (uint i = 0; i < _wallets.length; i++) { add(_wallets[i]); } } function remove(address _wallet) internal { require(isAllowed[_wallet]); isAllowed[_wallet] = false; RemovedEvent(_wallet); } function removeMany(address[] _wallets) public onlyOwner { for (uint i = 0; i < _wallets.length; i++) { remove(_wallets[i]); } } } //--------------------------------------------------------------- // Wings contracts: Start // DO NOT CHANGE the next contracts. They were copied from Wings // and left unformated. contract HasManager { address public manager; modifier onlyManager { require(msg.sender == manager); _; } function transferManager(address _newManager) public onlyManager() { require(_newManager != address(0)); manager = _newManager; } } // Crowdsale contracts interface contract ICrowdsaleProcessor is Ownable, HasManager { modifier whenCrowdsaleAlive() { require(isActive()); _; } modifier whenCrowdsaleFailed() { require(isFailed()); _; } modifier whenCrowdsaleSuccessful() { require(isSuccessful()); _; } modifier hasntStopped() { require(!stopped); _; } modifier hasBeenStopped() { require(stopped); _; } modifier hasntStarted() { require(!started); _; } modifier hasBeenStarted() { require(started); _; } // Minimal acceptable hard cap uint256 constant public MIN_HARD_CAP = 1 ether; // Minimal acceptable duration of crowdsale uint256 constant public MIN_CROWDSALE_TIME = 3 days; // Maximal acceptable duration of crowdsale uint256 constant public MAX_CROWDSALE_TIME = 50 days; // Becomes true when timeframe is assigned bool public started; // Becomes true if cancelled by owner bool public stopped; // Total collected Ethereum: must be updated every time tokens has been sold uint256 public totalCollected; // Total amount of project's token sold: must be updated every time tokens has been sold uint256 public totalSold; // Crowdsale minimal goal, must be greater or equal to Forecasting min amount uint256 public minimalGoal; // Crowdsale hard cap, must be less or equal to Forecasting max amount uint256 public hardCap; // Crowdsale duration in seconds. // Accepted range is MIN_CROWDSALE_TIME..MAX_CROWDSALE_TIME. uint256 public duration; // Start timestamp of crowdsale, absolute UTC time uint256 public startTimestamp; // End timestamp of crowdsale, absolute UTC time uint256 public endTimestamp; // Allows to transfer some ETH into the contract without selling tokens function deposit() public payable {} // Returns address of crowdsale token, must be ERC20 compilant function getToken() public returns(address); // Transfers ETH rewards amount (if ETH rewards is configured) to Forecasting contract function mintETHRewards(address _contract, uint256 _amount) public onlyManager(); // Mints token Rewards to Forecasting contract function mintTokenRewards(address _contract, uint256 _amount) public onlyManager(); // Releases tokens (transfers crowdsale token from mintable to transferrable state) function releaseTokens() public onlyManager() hasntStopped() whenCrowdsaleSuccessful(); // Stops crowdsale. Called by CrowdsaleController, the latter is called by owner. // Crowdsale may be stopped any time before it finishes. function stop() public onlyManager() hasntStopped(); // Validates parameters and starts crowdsale function start(uint256 _startTimestamp, uint256 _endTimestamp, address _fundingAddress) public onlyManager() hasntStarted() hasntStopped(); // Is crowdsale failed (completed, but minimal goal wasn't reached) function isFailed() public constant returns (bool); // Is crowdsale active (i.e. the token can be sold) function isActive() public constant returns (bool); // Is crowdsale completed successfully function isSuccessful() public constant returns (bool); } // Basic crowdsale implementation both for regualt and 3rdparty Crowdsale contracts contract BasicCrowdsale is ICrowdsaleProcessor { event CROWDSALE_START(uint256 startTimestamp, uint256 endTimestamp, address fundingAddress); // Where to transfer collected ETH address public fundingAddress; // Ctor. function BasicCrowdsale( address _owner, address _manager ) public { owner = _owner; manager = _manager; } // called by CrowdsaleController to transfer reward part of ETH // collected by successful crowdsale to Forecasting contract. // This call is made upon closing successful crowdfunding process // iff agreed ETH reward part is not zero function mintETHRewards( address _contract, // Forecasting contract uint256 _amount // agreed part of totalCollected which is intended for rewards ) public onlyManager() // manager is CrowdsaleController instance { require(_contract.call.value(_amount)()); } // cancels crowdsale function stop() public onlyManager() hasntStopped() { // we can stop only not started and not completed crowdsale if (started) { require(!isFailed()); require(!isSuccessful()); } stopped = true; } // called by CrowdsaleController to setup start and end time of crowdfunding process // as well as funding address (where to transfer ETH upon successful crowdsale) function start( uint256 _startTimestamp, uint256 _endTimestamp, address _fundingAddress ) public onlyManager() // manager is CrowdsaleController instance hasntStarted() // not yet started hasntStopped() // crowdsale wasn't cancelled { require(_fundingAddress != address(0)); // start time must not be earlier than current time require(_startTimestamp >= block.timestamp); // range must be sane require(_endTimestamp > _startTimestamp); duration = _endTimestamp - _startTimestamp; // duration must fit constraints require(duration >= MIN_CROWDSALE_TIME && duration <= MAX_CROWDSALE_TIME); startTimestamp = _startTimestamp; endTimestamp = _endTimestamp; fundingAddress = _fundingAddress; // now crowdsale is considered started, even if the current time is before startTimestamp started = true; CROWDSALE_START(_startTimestamp, _endTimestamp, _fundingAddress); } // must return true if crowdsale is over, but it failed function isFailed() public constant returns(bool) { return ( // it was started started && // crowdsale period has finished block.timestamp >= endTimestamp && // but collected ETH is below the required minimum totalCollected < minimalGoal ); } // must return true if crowdsale is active (i.e. the token can be bought) function isActive() public constant returns(bool) { return ( // it was started started && // hard cap wasn't reached yet totalCollected < hardCap && // and current time is within the crowdfunding period block.timestamp >= startTimestamp && block.timestamp < endTimestamp ); } // must return true if crowdsale completed successfully function isSuccessful() public constant returns(bool) { return ( // either the hard cap is collected totalCollected >= hardCap || // ...or the crowdfunding period is over, but the minimum has been reached (block.timestamp >= endTimestamp && totalCollected >= minimalGoal) ); } } // Minimal crowdsale token for custom contracts contract IWingsController { uint256 public ethRewardPart; uint256 public tokenRewardPart; } /* Implements custom crowdsale as bridge */ contract Bridge is BasicCrowdsale { using SafeMath for uint256; modifier onlyCrowdsale() { require(msg.sender == crowdsaleAddress); _; } // Crowdsale token StandardToken token; // Address of crowdsale address public crowdsaleAddress; // is crowdsale completed bool public completed; // Ctor. In this example, minimalGoal, hardCap, and price are not changeable. // In more complex cases, those parameters may be changed until start() is called. function Bridge( uint256 _minimalGoal, uint256 _hardCap, address _token, address _crowdsaleAddress ) public // simplest case where manager==owner. See onlyOwner() and onlyManager() modifiers // before functions to figure out the cases in which those addresses should differ BasicCrowdsale(msg.sender, msg.sender) { // just setup them once... minimalGoal = _minimalGoal; hardCap = _hardCap; crowdsaleAddress = _crowdsaleAddress; token = StandardToken(_token); } // Here goes ICrowdsaleProcessor implementation // returns address of crowdsale token. The token must be ERC20-compliant function getToken() public returns(address) { return address(token); } // called by CrowdsaleController to transfer reward part of // tokens sold by successful crowdsale to Forecasting contract. // This call is made upon closing successful crowdfunding process. function mintTokenRewards( address _contract, // Forecasting contract uint256 _amount // agreed part of totalSold which is intended for rewards ) public onlyManager() // manager is CrowdsaleController instance { // crowdsale token is mintable in this example, tokens are created here token.transfer(_contract, _amount); } // transfers crowdsale token from mintable to transferrable state function releaseTokens() public onlyManager() // manager is CrowdsaleController instance hasntStopped() // crowdsale wasn't cancelled whenCrowdsaleSuccessful() // crowdsale was successful { // empty for bridge } // Here go crowdsale process itself and token manipulations // default function allows for ETH transfers to the contract function () payable public { } function notifySale(uint256 _ethAmount, uint256 _tokensAmount) public hasBeenStarted() // crowdsale started hasntStopped() // wasn't cancelled by owner whenCrowdsaleAlive() // in active state onlyCrowdsale() // can do only crowdsale { totalCollected = totalCollected.add(_ethAmount); totalSold = totalSold.add(_tokensAmount); } // finish collecting data function finish() public hasntStopped() hasBeenStarted() whenCrowdsaleAlive() onlyCrowdsale() { completed = true; } // project's owner withdraws ETH funds to the funding address upon successful crowdsale function withdraw( uint256 _amount // can be done partially ) public onlyOwner() // project's owner hasntStopped() // crowdsale wasn't cancelled whenCrowdsaleSuccessful() // crowdsale completed successfully { // nothing to withdraw } // backers refund their ETH if the crowdsale was cancelled or has failed function refund() public { // nothing to refund } // called by CrowdsaleController to setup start and end time of crowdfunding process // as well as funding address (where to transfer ETH upon successful crowdsale) // Removed by RPE because it overrides and is not complete. // function start( // uint256 _startTimestamp, // uint256 _endTimestamp, // address _fundingAddress // ) // public // onlyManager() // manager is CrowdsaleController instance // hasntStarted() // not yet started // hasntStopped() // crowdsale wasn't cancelled // { // // just start crowdsale // started = true; // // CROWDSALE_START(_startTimestamp, _endTimestamp, _fundingAddress); // } // must return true if crowdsale is over, but it failed function isFailed() public constant returns(bool) { return ( false ); } // must return true if crowdsale is active (i.e. the token can be bought) function isActive() public constant returns(bool) { return ( // we remove timelines started && !completed ); } // must return true if crowdsale completed successfully function isSuccessful() public constant returns(bool) { return ( completed ); } function calculateRewards() public view returns(uint256,uint256) { uint256 tokenRewardPart = IWingsController(manager).tokenRewardPart(); uint256 ethRewardPart = IWingsController(manager).ethRewardPart(); uint256 tokenReward = totalSold.mul(tokenRewardPart) / 1000000; bool hasEthReward = (ethRewardPart != 0); uint256 ethReward = 0; if (hasEthReward) { ethReward = totalCollected.mul(ethRewardPart) / 1000000; } return (ethReward, tokenReward); } } contract Connector is Ownable { modifier bridgeInitialized() { require(address(bridge) != address(0x0)); _; } Bridge public bridge; function changeBridge(address _bridge) public onlyOwner { require(_bridge != address(0x0)); bridge = Bridge(_bridge); } function notifySale(uint256 _ethAmount, uint256 _tokenAmount) internal bridgeInitialized { bridge.notifySale(_ethAmount, _tokenAmount); } function closeBridge() internal bridgeInitialized { bridge.finish(); } } // Wings contracts: End //--------------------------------------------------------------- contract CommonTokensale is Connector, Pausable { using SafeMath for uint; CommonToken public token; // Token contract reference. CommonWhitelist public whitelist; // Whitelist contract reference. address public beneficiary; // Address that will receive ETH raised during this presale. address public bsWallet = 0x8D5bd2aBa04A07Bfa0cc976C73eD45B23cC6D6a2; bool public whitelistEnabled = true; uint public minPaymentWei; uint public defaultTokensPerWei; uint public minCapWei; uint public maxCapWei; uint public startTime; uint public endTime; // Stats for current tokensale: uint public totalTokensSold; // Total amount of tokens sold during this tokensale. uint public totalWeiReceived; // Total amount of wei received during this tokensale. // This mapping stores info on how many ETH (wei) have been sent to this tokensale from specific address. mapping (address => uint256) public buyerToSentWei; mapping (bytes32 => bool) public calledOnce; event ChangeBeneficiaryEvent(address indexed _oldAddress, address indexed _newAddress); event ChangeWhitelistEvent(address indexed _oldAddress, address indexed _newAddress); event ReceiveEthEvent(address indexed _buyer, uint256 _amountWei); function CommonTokensale( address _token, address _whitelist, address _beneficiary ) public Connector() { require(_token != 0); require(_whitelist != 0); require(_beneficiary != 0); token = CommonToken(_token); whitelist = CommonWhitelist(_whitelist); beneficiary = _beneficiary; } modifier canBeCalledOnce(bytes32 _flag) { require(!calledOnce[_flag]); calledOnce[_flag] = true; _; } /** NOTE: _newValue should be in ETH. */ function updateMinCapEthOnce(uint _newValue) public onlyOwner canBeCalledOnce("updateMinCapEth") { minCapWei = _newValue * 1e18; } /** NOTE: _newValue should be in ETH. */ function updateMaxCapEthOnce(uint _newValue) public onlyOwner canBeCalledOnce("updateMaxCapEth") { maxCapWei = _newValue * 1e18; } function updateTokensPerEthOnce(uint _newValue) public onlyOwner canBeCalledOnce("updateTokensPerEth") { defaultTokensPerWei = _newValue; recalcBonuses(); } function setBeneficiary(address _beneficiary) public onlyOwner { require(_beneficiary != 0); ChangeBeneficiaryEvent(beneficiary, _beneficiary); beneficiary = _beneficiary; } function setWhitelist(address _whitelist) public onlyOwner { require(_whitelist != 0); ChangeWhitelistEvent(whitelist, _whitelist); whitelist = CommonWhitelist(_whitelist); } function setWhitelistEnabled(bool _enabled) public onlyOwner { whitelistEnabled = _enabled; } /** The fallback function corresponds to a donation in ETH. */ function() public payable { sellTokensForEth(msg.sender, msg.value); } function sellTokensForEth( address _buyer, uint256 _amountWei ) ifNotPaused internal { // Check that buyer is in whitelist onlist if whitelist check is enabled. if (whitelistEnabled) require(whitelist.isAllowed(_buyer)); require(startTime <= now && now <= endTime); require(_amountWei >= minPaymentWei); require(totalWeiReceived < maxCapWei); uint256 newTotalReceived = totalWeiReceived.add(_amountWei); // Don't sell anything above the hard cap if (newTotalReceived > maxCapWei) { uint refundWei = newTotalReceived.sub(maxCapWei); // Send the ETH part which exceeds the hard cap back to the buyer: _buyer.transfer(refundWei); _amountWei = _amountWei.sub(refundWei); } uint tokensE18 = weiToTokens(_amountWei); // Transfer tokens to buyer. token.sell(_buyer, tokensE18); // Update total stats: totalTokensSold = totalTokensSold.add(tokensE18); totalWeiReceived = totalWeiReceived.add(_amountWei); buyerToSentWei[_buyer] = buyerToSentWei[_buyer].add(_amountWei); ReceiveEthEvent(_buyer, _amountWei); // 0.75% of sold tokens go to BS account. uint bsTokens = totalTokensSold.mul(75).div(10000); token.sell(bsWallet, bsTokens); // Notify Wings about successful sale of tokens: notifySale(_amountWei, tokensE18); } function amountPercentage(uint _amount, uint _per) public pure returns (uint) { return _amount.mul(_per).div(100); } function tokensPerWeiPlusBonus(uint _per) public view returns (uint) { return defaultTokensPerWei.add( amountPercentage(defaultTokensPerWei, _per) ); } /** Calc how much tokens you can buy at current time. */ function weiToTokens(uint _amountWei) public view returns (uint) { return _amountWei.mul(tokensPerWei(_amountWei)); } function recalcBonuses() internal; function tokensPerWei(uint _amountWei) public view returns (uint256); function isFinishedSuccessfully() public view returns (bool) { return now >= endTime && totalWeiReceived >= minCapWei; } function canWithdraw() public view returns (bool); /** * This method allows to withdraw to any arbitrary ETH address. * This approach gives more flexibility. */ function withdraw(address _to, uint256 _amount) public { require(canWithdraw()); require(msg.sender == beneficiary); require(_amount <= this.balance); _to.transfer(_amount); } function withdraw(address _to) public { withdraw(_to, this.balance); } /** If there is ETH rewards and all ETH already withdrawn. */ function deposit() public payable { require(isFinishedSuccessfully()); } /** * This function should be called only once only after * successfully finished tokensale. Once - because Wings bridge * will be closed at the end of this function call. */ function sendWingsRewardsOnce() public onlyOwner canBeCalledOnce("sendWingsRewards") { require(isFinishedSuccessfully()); uint256 ethReward = 0; uint256 tokenReward = 0; (ethReward, tokenReward) = bridge.calculateRewards(); if (ethReward > 0) { bridge.transfer(ethReward); } if (tokenReward > 0) { token.sell(bridge, tokenReward); } // Close Wings bridge closeBridge(); } } contract Presale is CommonTokensale { uint public tokensPerWei10; uint public tokensPerWei15; uint public tokensPerWei20; function Presale( address _token, address _whitelist, address _beneficiary ) CommonTokensale( _token, _whitelist, _beneficiary ) public { minCapWei = 0 ether; // No min cap at presale. maxCapWei = 8000 ether; // TODO 5m USD. To be determined based on ETH to USD price at the date of presale. // https://www.epochconverter.com/ startTime = 1525701600; // May 7, 2018 4:00:00 PM GMT+02:00 endTime = 1526306400; // May 14, 2018 4:00:00 PM GMT+02:00 minPaymentWei = 5 ether; // Hint: Set to lower amount (ex. 0.001 ETH) for tests. defaultTokensPerWei = 4808; // TODO To be determined based on ETH to USD price at the date of sale. recalcBonuses(); } function recalcBonuses() internal { tokensPerWei10 = tokensPerWeiPlusBonus(10); tokensPerWei15 = tokensPerWeiPlusBonus(15); tokensPerWei20 = tokensPerWeiPlusBonus(20); } function tokensPerWei(uint _amountWei) public view returns (uint256) { if (5 ether <= _amountWei && _amountWei < 10 ether) return tokensPerWei10; if (_amountWei < 20 ether) return tokensPerWei15; if (20 ether <= _amountWei) return tokensPerWei20; return defaultTokensPerWei; } /** * During presale it is possible to withdraw at any time. */ function canWithdraw() public view returns (bool) { return true; } } // Main sale contract. contract PublicSale is CommonTokensale { uint public tokensPerWei5; uint public tokensPerWei7; uint public tokensPerWei10; // In case min (soft) cap is not reached, token buyers will be able to // refund their contributions during one month after sale is finished. uint public refundDeadlineTime; // Total amount of wei refunded if min (soft) cap is not reached. uint public totalWeiRefunded; event RefundEthEvent(address indexed _buyer, uint256 _amountWei); function PublicSale( address _token, address _whitelist, address _beneficiary ) CommonTokensale( _token, _whitelist, _beneficiary ) public { minCapWei = 3200 ether; // TODO 2m USD. Recalculate based on ETH to USD price at the date of presale. maxCapWei = 16000 ether; // TODO 10m USD. Recalculate based on ETH to USD price at the date of presale. startTime = 1526392800; // 2018-05-15T14:00:00Z endTime = 1528639200; // 2018-06-10T14:00:00Z refundDeadlineTime = endTime + 30 days; minPaymentWei = 0.05 ether; // Hint: Set to lower amount (ex. 0.001 ETH) for tests. defaultTokensPerWei = 4808; // TODO To be determined based on ETH to USD price at the date of sale. recalcBonuses(); } function recalcBonuses() internal { tokensPerWei5 = tokensPerWeiPlusBonus(5); tokensPerWei7 = tokensPerWeiPlusBonus(7); tokensPerWei10 = tokensPerWeiPlusBonus(10); } function tokensPerWei(uint _amountWei) public view returns (uint256) { if (0.05 ether <= _amountWei && _amountWei < 10 ether) return tokensPerWei5; if (_amountWei < 20 ether) return tokensPerWei7; if (20 ether <= _amountWei) return tokensPerWei10; return defaultTokensPerWei; } /** * During presale it will be possible to withdraw only in two cases: * min cap reached OR refund period expired. */ function canWithdraw() public view returns (bool) { return totalWeiReceived >= minCapWei || now > refundDeadlineTime; } /** * It will be possible to refund only if min (soft) cap is not reached and * refund requested during 3 months after presale finished. */ function canRefund() public view returns (bool) { return totalWeiReceived < minCapWei && endTime < now && now <= refundDeadlineTime; } // TODO function refund() public { require(canRefund()); address buyer = msg.sender; uint amount = buyerToSentWei[buyer]; require(amount > 0); RefundEthEvent(buyer, amount); buyerToSentWei[buyer] = 0; totalWeiRefunded = totalWeiRefunded.add(amount); buyer.transfer(amount); } } // >> Start: // >> EXAMPLE: How to deploy Token, Whitelist and Presale. // token = new CommonToken( // 0x123 // TODO Set seller address // ); // whitelist = new CommonWhitelist(); // presale = new Presale( // token, // whitelist, // 0x123 // TODO Set beneficiary address // ); // token.addOwner(presale); // << EXAMPLE: How to deploy Token, Whitelist and Presale. // << End // Should be deployed after Presale capmaign successfully ended. // TODO After PublicSale deployed, call token.addOwner(address_of_deployed_public_sale) contract ProdPublicSale is PublicSale { function ProdPublicSale() PublicSale( 0x123, // TODO Set token address 0x123, // TODO Set whitelist address 0x123 // TODO Set beneficiary address ) public {} }
TODO 5m USD. To be determined based on ETH to USD price at the date of presale.
maxCapWei = 8000 ether;
245,585
[ 1, 6241, 1381, 81, 587, 9903, 18, 2974, 506, 11383, 2511, 603, 512, 2455, 358, 587, 9903, 6205, 622, 326, 1509, 434, 4075, 5349, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 943, 4664, 3218, 77, 273, 1725, 3784, 225, 2437, 31, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "../../fixins/FixinERC1155Spender.sol"; import "../../storage/LibCommonNftOrdersStorage.sol"; import "../../storage/LibERC1155OrdersStorage.sol"; import "../interfaces/IERC1155OrdersFeature.sol"; import "../libs/LibNFTOrder.sol"; import "../libs/LibSignature.sol"; import "./NFTOrders.sol"; /// @dev Feature for interacting with ERC1155 orders. contract ERC1155OrdersFeature is IERC1155OrdersFeature, FixinERC1155Spender, NFTOrders { using LibNFTOrder for LibNFTOrder.ERC1155SellOrder; using LibNFTOrder for LibNFTOrder.ERC1155BuyOrder; using LibNFTOrder for LibNFTOrder.NFTSellOrder; using LibNFTOrder for LibNFTOrder.NFTBuyOrder; /// @dev The magic return value indicating the success of a `onERC1155Received`. bytes4 private constant ERC1155_RECEIVED_MAGIC_BYTES = this.onERC1155Received.selector; constructor(IEtherToken weth) NFTOrders(weth) { } /// @dev Sells an ERC1155 asset to fill the given order. /// @param buyOrder The ERC1155 buy order. /// @param signature The order signature from the maker. /// @param erc1155TokenId The ID of the ERC1155 asset being /// sold. If the given order specifies properties, /// the asset must satisfy those properties. Otherwise, /// it must equal the tokenId in the order. /// @param erc1155SellAmount The amount of the ERC1155 asset /// to sell. /// @param unwrapNativeToken If this parameter is true and the /// ERC20 token of the order is e.g. WETH, unwraps the /// token before transferring it to the taker. /// @param callbackData If this parameter is non-zero, invokes /// `zeroExERC1155OrderCallback` on `msg.sender` after /// the ERC20 tokens have been transferred to `msg.sender` /// but before transferring the ERC1155 asset to the buyer. function sellERC1155( LibNFTOrder.ERC1155BuyOrder memory buyOrder, LibSignature.Signature memory signature, uint256 erc1155TokenId, uint128 erc1155SellAmount, bool unwrapNativeToken, bytes memory callbackData ) public override { _sellERC1155( buyOrder, signature, SellParams( erc1155SellAmount, erc1155TokenId, unwrapNativeToken, msg.sender, // taker msg.sender, // owner callbackData ) ); } /// @dev Buys an ERC1155 asset by filling the given order. /// @param sellOrder The ERC1155 sell order. /// @param signature The order signature. /// @param erc1155BuyAmount The amount of the ERC1155 asset /// to buy. function buyERC1155( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, uint128 erc1155BuyAmount ) public override payable { uint256 ethBalanceBefore = address(this).balance - msg.value; _buyERC1155(sellOrder, signature, erc1155BuyAmount); if (address(this).balance != ethBalanceBefore) { // Refund _transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore); } } function buyERC1155Ex( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, address taker, uint128 erc1155BuyAmount, bytes memory callbackData ) public override payable { uint256 ethBalanceBefore = address(this).balance - msg.value; _buyERC1155Ex( sellOrder, signature, BuyParams( erc1155BuyAmount, msg.value, taker, callbackData ) ); if (address(this).balance != ethBalanceBefore) { // Refund _transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore); } } /// @dev Cancel a single ERC1155 order by its nonce. The caller /// should be the maker of the order. Silently succeeds if /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonce The order nonce. function cancelERC1155Order(uint256 orderNonce) public override { // The bitvector is indexed by the lower 8 bits of the nonce. uint256 flag = 1 << (orderNonce & 255); // Update order cancellation bit vector to indicate that the order // has been cancelled/filled by setting the designated bit to 1. LibERC1155OrdersStorage.getStorage().orderCancellationByMaker [msg.sender][uint248(orderNonce >> 8)] |= flag; emit ERC1155OrderCancelled(msg.sender, orderNonce); } /// @dev Cancel multiple ERC1155 orders by their nonces. The caller /// should be the maker of the orders. Silently succeeds if /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonces The order nonces. function batchCancelERC1155Orders(uint256[] calldata orderNonces) external override { for (uint256 i = 0; i < orderNonces.length; i++) { cancelERC1155Order(orderNonces[i]); } } /// @dev Buys multiple ERC1155 assets by filling the /// given orders. /// @param sellOrders The ERC1155 sell orders. /// @param signatures The order signatures. /// @param erc1155FillAmounts The amounts of the ERC1155 assets /// to buy for each order. /// @param revertIfIncomplete If true, reverts if this /// function fails to fill any individual order. /// @return successes An array of booleans corresponding to whether /// each order in `orders` was successfully filled. function batchBuyERC1155s( LibNFTOrder.ERC1155SellOrder[] memory sellOrders, LibSignature.Signature[] memory signatures, uint128[] calldata erc1155FillAmounts, bool revertIfIncomplete ) public override payable returns (bool[] memory successes) { uint256 length = sellOrders.length; require( length == signatures.length && length == erc1155FillAmounts.length, "ERC1155OrdersFeature::batchBuyERC1155s/ARRAY_LENGTH_MISMATCH" ); successes = new bool[](length); uint256 ethBalanceBefore = address(this).balance - msg.value; if (revertIfIncomplete) { for (uint256 i = 0; i < length; i++) { // Will revert if _buyERC1155 reverts. _buyERC1155(sellOrders[i], signatures[i], erc1155FillAmounts[i]); successes[i] = true; } } else { for (uint256 i = 0; i < length; i++) { // Delegatecall `buyERC1155FromProxy` to catch swallow reverts while // preserving execution context. (successes[i], ) = _implementation.delegatecall( abi.encodeWithSelector( this.buyERC1155FromProxy.selector, sellOrders[i], signatures[i], erc1155FillAmounts[i] ) ); } } // Refund _transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore); } function batchBuyERC1155sEx( LibNFTOrder.ERC1155SellOrder[] memory sellOrders, LibSignature.Signature[] memory signatures, address[] calldata takers, uint128[] calldata erc1155FillAmounts, bytes[] memory callbackData, bool revertIfIncomplete ) public override payable returns (bool[] memory successes) { uint256 length = sellOrders.length; require( length == signatures.length && length == takers.length && length == erc1155FillAmounts.length && length == callbackData.length, "ARRAY_LENGTH_MISMATCH" ); successes = new bool[](length); uint256 ethBalanceBefore = address(this).balance - msg.value; if (revertIfIncomplete) { for (uint256 i = 0; i < length; i++) { // Will revert if _buyERC1155Ex reverts. _buyERC1155Ex( sellOrders[i], signatures[i], BuyParams( erc1155FillAmounts[i], address(this).balance - ethBalanceBefore, // Remaining ETH available takers[i], callbackData[i] ) ); successes[i] = true; } } else { for (uint256 i = 0; i < length; i++) { // Delegatecall `buyERC1155ExFromProxy` to catch swallow reverts while // preserving execution context. (successes[i], ) = _implementation.delegatecall( abi.encodeWithSelector( this.buyERC1155ExFromProxy.selector, sellOrders[i], signatures[i], BuyParams( erc1155FillAmounts[i], address(this).balance - ethBalanceBefore, // Remaining ETH available takers[i], callbackData[i] ) ) ); } } // Refund _transferEth(payable(msg.sender), address(this).balance - ethBalanceBefore); } // @Note `buyERC1155FromProxy` is a external function, must call from an external Exchange Proxy, // but should not be registered in the Exchange Proxy. function buyERC1155FromProxy( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, uint128 buyAmount ) external payable { require(_implementation != address(this), "MUST_CALL_FROM_PROXY"); _buyERC1155(sellOrder, signature, buyAmount); } // @Note `buyERC1155ExFromProxy` is a external function, must call from an external Exchange Proxy, // but should not be registered in the Exchange Proxy. function buyERC1155ExFromProxy( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, BuyParams memory params ) external payable { require(_implementation != address(this), "MUST_CALL_FROM_PROXY"); _buyERC1155Ex(sellOrder, signature, params); } /// @dev Callback for the ERC1155 `safeTransferFrom` function. /// This callback can be used to sell an ERC1155 asset if /// a valid ERC1155 order, signature and `unwrapNativeToken` /// are encoded in `data`. This allows takers to sell their /// ERC1155 asset without first calling `setApprovalForAll`. /// @param operator The address which called `safeTransferFrom`. /// @param tokenId The ID of the asset being transferred. /// @param value The amount being transferred. /// @param data Additional data with no specified format. If a /// valid ERC1155 order, signature and `unwrapNativeToken` /// are encoded in `data`, this function will try to fill /// the order using the received asset. /// @return success The selector of this function (0xf23a6e61), /// indicating that the callback succeeded. function onERC1155Received( address operator, address /* from */, uint256 tokenId, uint256 value, bytes calldata data ) external override returns (bytes4 success) { // Decode the order, signature, and `unwrapNativeToken` from // `data`. If `data` does not encode such parameters, this // will throw. ( LibNFTOrder.ERC1155BuyOrder memory buyOrder, LibSignature.Signature memory signature, bool unwrapNativeToken ) = abi.decode( data, (LibNFTOrder.ERC1155BuyOrder, LibSignature.Signature, bool) ); // `onERC1155Received` is called by the ERC1155 token contract. // Check that it matches the ERC1155 token in the order. if (msg.sender != buyOrder.erc1155Token) { revert("ERC1155_TOKEN_MISMATCH"); } require(value <= type(uint128).max); _sellERC1155( buyOrder, signature, SellParams( uint128(value), tokenId, unwrapNativeToken, operator, // taker address(this), // owner (we hold the NFT currently) new bytes(0) // No taker callback ) ); return ERC1155_RECEIVED_MAGIC_BYTES; } /// @dev Approves an ERC1155 sell order on-chain. After pre-signing /// the order, the `PRESIGNED` signature type will become /// valid for that order and signer. /// @param order An ERC1155 sell order. function preSignERC1155SellOrder(LibNFTOrder.ERC1155SellOrder memory order) public override { require(order.maker == msg.sender, "ONLY_MAKER"); uint256 hashNonce = LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker]; require(hashNonce < type(uint128).max); bytes32 orderHash = getERC1155SellOrderHash(order); LibERC1155OrdersStorage.getStorage().orderState[orderHash].preSigned = uint128(hashNonce + 1); emit ERC1155SellOrderPreSigned( order.maker, order.taker, order.expiry, order.nonce, order.erc20Token, order.erc20TokenAmount, order.fees, order.erc1155Token, order.erc1155TokenId, order.erc1155TokenAmount ); } /// @dev Approves an ERC1155 buy order on-chain. After pre-signing /// the order, the `PRESIGNED` signature type will become /// valid for that order and signer. /// @param order An ERC1155 buy order. function preSignERC1155BuyOrder(LibNFTOrder.ERC1155BuyOrder memory order) public override { require(order.maker == msg.sender, "ONLY_MAKER"); uint256 hashNonce = LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker]; require(hashNonce < type(uint128).max, "HASH_NONCE_OUTSIDE"); bytes32 orderHash = getERC1155BuyOrderHash(order); LibERC1155OrdersStorage.getStorage().orderState[orderHash].preSigned = uint128(hashNonce + 1); emit ERC1155BuyOrderPreSigned( order.maker, order.taker, order.expiry, order.nonce, order.erc20Token, order.erc20TokenAmount, order.fees, order.erc1155Token, order.erc1155TokenId, order.erc1155TokenProperties, order.erc1155TokenAmount ); } // Core settlement logic for selling an ERC1155 asset. // Used by `sellERC1155` and `onERC1155Received`. function _sellERC1155( LibNFTOrder.ERC1155BuyOrder memory buyOrder, LibSignature.Signature memory signature, SellParams memory params ) private { (uint256 erc20FillAmount, bytes32 orderHash) = _sellNFT( buyOrder.asNFTBuyOrder(), signature, params ); emit ERC1155BuyOrderFilled( buyOrder.maker, params.taker, (erc20FillAmount << 160) | uint160(address(buyOrder.erc20Token)), (params.tokenId << 160) | uint160(buyOrder.erc1155Token), params.sellAmount, orderHash ); } // Core settlement logic for buying an ERC1155 asset. // Used by `buyERC1155` and `batchBuyERC1155s`. function _buyERC1155( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, uint128 buyAmount ) internal { (uint256 erc20FillAmount, bytes32 orderHash) = _buyNFT( sellOrder.asNFTSellOrder(), signature, buyAmount ); emit ERC1155SellOrderFilled( sellOrder.maker, msg.sender, (erc20FillAmount << 160) | uint160(address(sellOrder.erc20Token)), (sellOrder.erc1155TokenId << 160) | uint160(sellOrder.erc1155Token), buyAmount, orderHash ); } function _buyERC1155Ex( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibSignature.Signature memory signature, BuyParams memory params ) internal { if (params.taker == address(0)) { params.taker = msg.sender; } else { require(params.taker != address(this), "_buy1155Ex/TAKER_CANNOT_SELF"); } (uint256 erc20FillAmount, bytes32 orderHash) = _buyNFTEx( sellOrder.asNFTSellOrder(), signature, params ); emit ERC1155SellOrderFilled( sellOrder.maker, params.taker, (erc20FillAmount << 160) | uint160(address(sellOrder.erc20Token)), (sellOrder.erc1155TokenId << 160) | uint160(sellOrder.erc1155Token), params.buyAmount, orderHash ); } /// @dev Checks whether the given signature is valid for the /// the given ERC1155 sell order. Reverts if not. /// @param order The ERC1155 sell order. /// @param signature The signature to validate. function validateERC1155SellOrderSignature( LibNFTOrder.ERC1155SellOrder memory order, LibSignature.Signature memory signature ) public override view { bytes32 orderHash = getERC1155SellOrderHash(order); _validateOrderSignature(orderHash, signature, order.maker); } /// @dev Checks whether the given signature is valid for the /// the given ERC1155 buy order. Reverts if not. /// @param order The ERC1155 buy order. /// @param signature The signature to validate. function validateERC1155BuyOrderSignature( LibNFTOrder.ERC1155BuyOrder memory order, LibSignature.Signature memory signature ) public override view { bytes32 orderHash = getERC1155BuyOrderHash(order); _validateOrderSignature(orderHash, signature, order.maker); } /// @dev Validates that the given signature is valid for the /// given maker and order hash. Reverts if the signature /// is not valid. /// @param orderHash The hash of the order that was signed. /// @param signature The signature to check. /// @param maker The maker of the order. function _validateOrderSignature( bytes32 orderHash, LibSignature.Signature memory signature, address maker ) internal override view { if (signature.signatureType == LibSignature.SignatureType.PRESIGNED) { require( LibERC1155OrdersStorage.getStorage().orderState[orderHash].preSigned == LibCommonNftOrdersStorage.getStorage().hashNonces[maker] + 1, "PRESIGNED_INVALID_SIGNER" ); } else { require( maker != address(0) && maker == ecrecover(orderHash, signature.v, signature.r, signature.s), "INVALID_SIGNER_ERROR" ); } } /// @dev Transfers an NFT asset. /// @param token The address of the NFT contract. /// @param from The address currently holding the asset. /// @param to The address to transfer the asset to. /// @param tokenId The ID of the asset to transfer. /// @param amount The amount of the asset to transfer. function _transferNFTAssetFrom( address token, address from, address to, uint256 tokenId, uint256 amount ) internal override { _transferERC1155AssetFrom(token, from, to, tokenId, amount); } /// @dev Updates storage to indicate that the given order /// has been filled by the given amount. /// @param orderHash The hash of `order`. /// @param fillAmount The amount (denominated in the NFT asset) /// that the order has been filled by. function _updateOrderState( LibNFTOrder.NFTSellOrder memory /* order */, bytes32 orderHash, uint128 fillAmount ) internal override { LibERC1155OrdersStorage.Storage storage stor = LibERC1155OrdersStorage.getStorage(); uint128 filledAmount = stor.orderState[orderHash].filledAmount; // Filled amount should never overflow 128 bits require(filledAmount + fillAmount > filledAmount); stor.orderState[orderHash].filledAmount = filledAmount + fillAmount; } /// @dev Get the order info for an ERC1155 sell order. /// @param order The ERC1155 sell order. /// @return orderInfo Infor about the order. function getERC1155SellOrderInfo(LibNFTOrder.ERC1155SellOrder memory order) public override view returns (LibNFTOrder.OrderInfo memory orderInfo) { orderInfo.orderAmount = order.erc1155TokenAmount; orderInfo.orderHash = getERC1155SellOrderHash(order); // Check for listingTime. // Gas Optimize, listingTime only used in rare cases. if (order.expiry & 0xffffffff00000000 > 0) { if ((order.expiry >> 32) & 0xffffffff > block.timestamp) { orderInfo.status = LibNFTOrder.OrderStatus.INVALID; return orderInfo; } } // Check for expiryTime. if (order.expiry & 0xffffffff <= block.timestamp) { orderInfo.status = LibNFTOrder.OrderStatus.EXPIRED; return orderInfo; } { LibERC1155OrdersStorage.Storage storage stor = LibERC1155OrdersStorage.getStorage(); LibERC1155OrdersStorage.OrderState storage orderState = stor.orderState[orderInfo.orderHash]; orderInfo.remainingAmount = order.erc1155TokenAmount - orderState.filledAmount; // `orderCancellationByMaker` is indexed by maker and nonce. uint256 orderCancellationBitVector = stor.orderCancellationByMaker[order.maker][uint248(order.nonce >> 8)]; // The bitvector is indexed by the lower 8 bits of the nonce. uint256 flag = 1 << (order.nonce & 255); if (orderInfo.remainingAmount == 0 || orderCancellationBitVector & flag != 0) { orderInfo.status = LibNFTOrder.OrderStatus.UNFILLABLE; return orderInfo; } } // Otherwise, the order is fillable. orderInfo.status = LibNFTOrder.OrderStatus.FILLABLE; return orderInfo; } /// @dev Get the order info for an ERC1155 buy order. /// @param order The ERC1155 buy order. /// @return orderInfo Infor about the order. function getERC1155BuyOrderInfo(LibNFTOrder.ERC1155BuyOrder memory order) public override view returns (LibNFTOrder.OrderInfo memory orderInfo) { orderInfo.orderAmount = order.erc1155TokenAmount; orderInfo.orderHash = getERC1155BuyOrderHash(order); // Only buy orders with `erc1155TokenId` == 0 can be property // orders. if (order.erc1155TokenId != 0 && order.erc1155TokenProperties.length > 0) { orderInfo.status = LibNFTOrder.OrderStatus.INVALID; return orderInfo; } // Buy orders cannot use ETH as the ERC20 token, since ETH cannot be // transferred from the buyer by a contract. if (address(order.erc20Token) == NATIVE_TOKEN_ADDRESS) { orderInfo.status = LibNFTOrder.OrderStatus.INVALID; return orderInfo; } // Check for listingTime. // Gas Optimize, listingTime only used in rare cases. if (order.expiry & 0xffffffff00000000 > 0) { if ((order.expiry >> 32) & 0xffffffff > block.timestamp) { orderInfo.status = LibNFTOrder.OrderStatus.INVALID; return orderInfo; } } // Check for expiryTime. if (order.expiry & 0xffffffff <= block.timestamp) { orderInfo.status = LibNFTOrder.OrderStatus.EXPIRED; return orderInfo; } { LibERC1155OrdersStorage.Storage storage stor = LibERC1155OrdersStorage.getStorage(); LibERC1155OrdersStorage.OrderState storage orderState = stor.orderState[orderInfo.orderHash]; orderInfo.remainingAmount = order.erc1155TokenAmount - orderState.filledAmount; // `orderCancellationByMaker` is indexed by maker and nonce. uint256 orderCancellationBitVector = stor.orderCancellationByMaker[order.maker][uint248(order.nonce >> 8)]; // The bitvector is indexed by the lower 8 bits of the nonce. uint256 flag = 1 << (order.nonce & 255); if (orderInfo.remainingAmount == 0 || orderCancellationBitVector & flag != 0) { orderInfo.status = LibNFTOrder.OrderStatus.UNFILLABLE; return orderInfo; } } // Otherwise, the order is fillable. orderInfo.status = LibNFTOrder.OrderStatus.FILLABLE; return orderInfo; } /// @dev Get the EIP-712 hash of an ERC1155 sell order. /// @param order The ERC1155 sell order. /// @return orderHash The order hash. function getERC1155SellOrderHash(LibNFTOrder.ERC1155SellOrder memory order) public override view returns (bytes32 orderHash) { return _getEIP712Hash( LibNFTOrder.getERC1155SellOrderStructHash( order, LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker] ) ); } /// @dev Get the EIP-712 hash of an ERC1155 buy order. /// @param order The ERC1155 buy order. /// @return orderHash The order hash. function getERC1155BuyOrderHash(LibNFTOrder.ERC1155BuyOrder memory order) public override view returns (bytes32 orderHash) { return _getEIP712Hash( LibNFTOrder.getERC1155BuyOrderStructHash( order, LibCommonNftOrdersStorage.getStorage().hashNonces[order.maker] ) ); } /// @dev Get the order nonce status bit vector for the given /// maker address and nonce range. /// @param maker The maker of the order. /// @param nonceRange Order status bit vectors are indexed /// by maker address and the upper 248 bits of the /// order nonce. We define `nonceRange` to be these /// 248 bits. /// @return bitVector The order status bit vector for the /// given maker and nonce range. function getERC1155OrderNonceStatusBitVector(address maker, uint248 nonceRange) external override view returns (uint256) { return LibERC1155OrdersStorage.getStorage().orderCancellationByMaker[maker][nonceRange]; } /// @dev Get the order info for an NFT sell order. /// @param nftSellOrder The NFT sell order. /// @return orderInfo Info about the order. function _getOrderInfo(LibNFTOrder.NFTSellOrder memory nftSellOrder) internal override view returns (LibNFTOrder.OrderInfo memory orderInfo) { return getERC1155SellOrderInfo(nftSellOrder.asERC1155SellOrder()); } /// @dev Get the order info for an NFT buy order. /// @param nftBuyOrder The NFT buy order. /// @return orderInfo Info about the order. function _getOrderInfo(LibNFTOrder.NFTBuyOrder memory nftBuyOrder) internal override view returns (LibNFTOrder.OrderInfo memory orderInfo) { return getERC1155BuyOrderInfo(nftBuyOrder.asERC1155BuyOrder()); } /// @dev Matches a pair of complementary orders that have /// a non-negative spread. Each order is filled at /// their respective price, and the matcher receives /// a profit denominated in the ERC20 token. /// @param sellOrder Order selling an ERC1155 asset. /// @param buyOrder Order buying an ERC1155 asset. /// @param sellOrderSignature Signature for the sell order. /// @param buyOrderSignature Signature for the buy order. /// @return profit The amount of profit earned by the caller /// of this function (denominated in the ERC20 token /// of the matched orders). function matchERC1155Orders( LibNFTOrder.ERC1155SellOrder memory sellOrder, LibNFTOrder.ERC1155BuyOrder memory buyOrder, LibSignature.Signature memory sellOrderSignature, LibSignature.Signature memory buyOrderSignature ) public override returns (uint256 profit) { // The ERC1155 tokens must match if (sellOrder.erc1155Token != buyOrder.erc1155Token) { revert("ERC1155_TOKEN_MISMATCH_ERROR"); } LibNFTOrder.NFTSellOrder memory sellNFTOrder = sellOrder.asNFTSellOrder(); LibNFTOrder.NFTBuyOrder memory buyNFTOrder = buyOrder.asNFTBuyOrder(); LibNFTOrder.OrderInfo memory sellOrderInfo = getERC1155SellOrderInfo(sellOrder); LibNFTOrder.OrderInfo memory buyOrderInfo = getERC1155BuyOrderInfo(buyOrder); bool isEnglishAuction = (sellOrder.expiry >> 252 == 2); if (isEnglishAuction) { require( sellOrderInfo.orderAmount == sellOrderInfo.remainingAmount && sellOrderInfo.orderAmount == buyOrderInfo.orderAmount && sellOrderInfo.orderAmount == buyOrderInfo.remainingAmount, "UNMATCH_ORDER_AMOUNT" ); } _validateSellOrder( sellNFTOrder, sellOrderSignature, sellOrderInfo, buyOrder.maker ); _validateBuyOrder( buyNFTOrder, buyOrderSignature, buyOrderInfo, sellOrder.maker, sellOrder.erc1155TokenId ); // fillAmount = min(sellOrder.remainingAmount, buyOrder.remainingAmount) uint128 erc1155FillAmount = sellOrderInfo.remainingAmount < buyOrderInfo.remainingAmount ? sellOrderInfo.remainingAmount : buyOrderInfo.remainingAmount; // Reset sellOrder.erc20TokenAmount if (erc1155FillAmount != sellOrderInfo.orderAmount) { sellOrder.erc20TokenAmount = _ceilDiv( sellOrder.erc20TokenAmount * erc1155FillAmount, sellOrderInfo.orderAmount ); } // Reset buyOrder.erc20TokenAmount if (erc1155FillAmount != buyOrderInfo.orderAmount) { buyOrder.erc20TokenAmount = buyOrder.erc20TokenAmount * erc1155FillAmount / buyOrderInfo.orderAmount; } if (isEnglishAuction) { _resetEnglishAuctionTokenAmountAndFees( sellNFTOrder, buyOrder.erc20TokenAmount, erc1155FillAmount, sellOrderInfo.orderAmount ); } // Mark both orders as filled. _updateOrderState(sellNFTOrder, sellOrderInfo.orderHash, erc1155FillAmount); _updateOrderState(buyNFTOrder.asNFTSellOrder(), buyOrderInfo.orderHash, erc1155FillAmount); // The difference in ERC20 token amounts is the spread. uint256 spread = buyOrder.erc20TokenAmount - sellOrder.erc20TokenAmount; // Transfer the ERC1155 asset from seller to buyer. _transferERC1155AssetFrom( sellOrder.erc1155Token, sellOrder.maker, buyOrder.maker, sellOrder.erc1155TokenId, erc1155FillAmount ); // Handle the ERC20 side of the order: if ( address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS && buyOrder.erc20Token == WETH ) { // The sell order specifies ETH, while the buy order specifies WETH. // The orders are still compatible with one another, but we'll have // to unwrap the WETH on behalf of the buyer. // Step 1: Transfer WETH from the buyer to the EP. // Note that we transfer `buyOrder.erc20TokenAmount`, which // is the amount the buyer signaled they are willing to pay // for the ERC1155 asset, which may be more than the seller's // ask. _transferERC20TokensFrom( WETH, buyOrder.maker, address(this), buyOrder.erc20TokenAmount ); // Step 2: Unwrap the WETH into ETH. We unwrap the entire // `buyOrder.erc20TokenAmount`. // The ETH will be used for three purposes: // - To pay the seller // - To pay fees for the sell order // - Any remaining ETH will be sent to // `msg.sender` as profit. WETH.withdraw(buyOrder.erc20TokenAmount); // Step 3: Pay the seller (in ETH). _transferEth(payable(sellOrder.maker), sellOrder.erc20TokenAmount); // Step 4: Pay fees for the buy order. Note that these are paid // in _WETH_ by the _buyer_. By signing the buy order, the // buyer signals that they are willing to spend a total // of `erc20TokenAmount` _plus_ fees, all denominated in // the `erc20Token`, which in this case is WETH. _payFees( buyNFTOrder.asNFTSellOrder(), buyOrder.maker, // payer erc1155FillAmount, buyOrderInfo.orderAmount, false // useNativeToken ); // Step 5: Pay fees for the sell order. The `erc20Token` of the // sell order is ETH, so the fees are paid out in ETH. // There should be `spread` wei of ETH remaining in the // EP at this point, which we will use ETH to pay the // sell order fees. uint256 sellOrderFees = _payFees( sellNFTOrder, address(this), // payer erc1155FillAmount, sellOrderInfo.orderAmount, true // useNativeToken ); // Step 6: The spread less the sell order fees is the amount of ETH // remaining in the EP that can be sent to `msg.sender` as // the profit from matching these two orders. profit = spread - sellOrderFees; if (profit > 0) { _transferEth(payable(msg.sender), profit); } } else { // ERC20 tokens must match if (sellOrder.erc20Token != buyOrder.erc20Token) { revert("ERC20_TOKEN_MISMATCH"); } // Step 1: Transfer the ERC20 token from the buyer to the seller. // Note that we transfer `sellOrder.erc20TokenAmount`, which // is at most `buyOrder.erc20TokenAmount`. _transferERC20TokensFrom( buyOrder.erc20Token, buyOrder.maker, sellOrder.maker, sellOrder.erc20TokenAmount ); // Step 2: Pay fees for the buy order. Note that these are paid // by the buyer. By signing the buy order, the buyer signals // that they are willing to spend a total of // `buyOrder.erc20TokenAmount` _plus_ `buyOrder.fees`. _payFees( buyNFTOrder.asNFTSellOrder(), buyOrder.maker, // payer erc1155FillAmount, buyOrderInfo.orderAmount, false // useNativeToken ); // Step 3: Pay fees for the sell order. These are paid by the buyer // as well. After paying these fees, we may have taken more // from the buyer than they agreed to in the buy order. If // so, we revert in the following step. uint256 sellOrderFees = _payFees( sellNFTOrder, buyOrder.maker, // payer erc1155FillAmount, sellOrderInfo.orderAmount, false // useNativeToken ); // Step 4: We calculate the profit as: // profit = buyOrder.erc20TokenAmount - sellOrder.erc20TokenAmount - sellOrderFees // = spread - sellOrderFees // I.e. the buyer would've been willing to pay up to `profit` // more to buy the asset, so instead that amount is sent to // `msg.sender` as the profit from matching these two orders. profit = spread - sellOrderFees; if (profit > 0) { _transferERC20TokensFrom( buyOrder.erc20Token, buyOrder.maker, msg.sender, profit ); } } _emitEventSellOrderFilled( sellOrder, buyOrder.maker, // taker erc1155FillAmount, sellOrderInfo.orderHash ); _emitEventBuyOrderFilled( buyOrder, sellOrder.maker, // taker sellOrder.erc1155TokenId, erc1155FillAmount, buyOrderInfo.orderHash ); } function _emitEventSellOrderFilled( LibNFTOrder.ERC1155SellOrder memory sellOrder, address taker, uint128 erc1155FillAmount, bytes32 orderHash ) private { emit ERC1155SellOrderFilled( sellOrder.maker, taker, (sellOrder.erc20TokenAmount << 160) | uint160(address(sellOrder.erc20Token)), (sellOrder.erc1155TokenId << 160) | uint160(sellOrder.erc1155Token), erc1155FillAmount, orderHash ); } function _emitEventBuyOrderFilled( LibNFTOrder.ERC1155BuyOrder memory buyOrder, address taker, uint256 erc1155TokenId, uint128 erc1155FillAmount, bytes32 orderHash ) private { emit ERC1155BuyOrderFilled( buyOrder.maker, taker, (buyOrder.erc20TokenAmount << 160) | uint160(address(buyOrder.erc20Token)), (erc1155TokenId << 160) | uint160(buyOrder.erc1155Token), erc1155FillAmount, orderHash ); } /// @dev Matches pairs of complementary orders that have /// non-negative spreads. Each order is filled at /// their respective price, and the matcher receives /// a profit denominated in the ERC20 token. /// @param sellOrders Orders selling ERC1155 assets. /// @param buyOrders Orders buying ERC1155 assets. /// @param sellOrderSignatures Signatures for the sell orders. /// @param buyOrderSignatures Signatures for the buy orders. /// @return profits The amount of profit earned by the caller /// of this function for each pair of matched orders /// (denominated in the ERC20 token of the order pair). /// @return successes An array of booleans corresponding to /// whether each pair of orders was successfully matched. function batchMatchERC1155Orders( LibNFTOrder.ERC1155SellOrder[] memory sellOrders, LibNFTOrder.ERC1155BuyOrder[] memory buyOrders, LibSignature.Signature[] memory sellOrderSignatures, LibSignature.Signature[] memory buyOrderSignatures ) public override returns (uint256[] memory profits, bool[] memory successes) { require( sellOrders.length == buyOrders.length && sellOrderSignatures.length == buyOrderSignatures.length && sellOrders.length == sellOrderSignatures.length ); profits = new uint256[](sellOrders.length); successes = new bool[](sellOrders.length); for (uint256 i = 0; i < sellOrders.length; i++) { bytes memory returnData; // Delegatecall `matchERC1155Orders` to catch reverts while // preserving execution context. (successes[i], returnData) = _implementation.delegatecall( abi.encodeWithSelector( this.matchERC1155Orders.selector, sellOrders[i], buyOrders[i], sellOrderSignatures[i], buyOrderSignatures[i] ) ); if (successes[i]) { // If the matching succeeded, record the profit. (uint256 profit) = abi.decode(returnData, (uint256)); profits[i] = profit; } } } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; /// @dev Helpers for moving ERC1155 assets around. abstract contract FixinERC1155Spender { // Mask of the lower 20 bytes of a bytes32. uint256 constant private ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; /// @dev Transfers an ERC1155 asset from `owner` to `to`. /// @param token The address of the ERC1155 token contract. /// @param owner The owner of the asset. /// @param to The recipient of the asset. /// @param tokenId The token ID of the asset to transfer. /// @param amount The amount of the asset to transfer. function _transferERC1155AssetFrom( address token, address owner, address to, uint256 tokenId, uint256 amount ) internal { uint256 success; assembly { let ptr := mload(0x40) // free memory pointer // selector for safeTransferFrom(address,address,uint256,uint256,bytes) mstore(ptr, 0xf242432a00000000000000000000000000000000000000000000000000000000) mstore(add(ptr, 0x04), and(owner, ADDRESS_MASK)) mstore(add(ptr, 0x24), and(to, ADDRESS_MASK)) mstore(add(ptr, 0x44), tokenId) mstore(add(ptr, 0x64), amount) mstore(add(ptr, 0x84), 0xa0) mstore(add(ptr, 0xa4), 0) success := call( gas(), and(token, ADDRESS_MASK), 0, ptr, 0xc4, 0, 0 ) } require(success != 0, "_transferERC1155/TRANSFER_FAILED"); } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2022 Element.Market 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.8.13; import "./LibStorage.sol"; library LibCommonNftOrdersStorage { /// @dev Storage bucket for this feature. struct Storage { /* Track per-maker nonces that can be incremented by the maker to cancel orders in bulk. */ // The current nonce for the maker represents the only valid nonce that can be signed by the maker // If a signature was signed with a nonce that's different from the one stored in nonces, it // will fail validation. mapping(address => uint256) hashNonces; } /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { uint256 storageSlot = LibStorage.STORAGE_ID_COMMON_NFT_ORDERS; // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries assembly { stor.slot := storageSlot } } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "./LibStorage.sol"; /// @dev Storage helpers for `ERC1155OrdersFeature`. library LibERC1155OrdersStorage { struct OrderState { // The amount (denominated in the ERC1155 asset) // that the order has been filled by. uint128 filledAmount; // Whether the order has been pre-signed. uint128 preSigned; } /// @dev Storage bucket for this feature. struct Storage { // Mapping from order hash to order state: mapping(bytes32 => OrderState) orderState; // maker => nonce range => order cancellation bit vector mapping(address => mapping(uint248 => uint256)) orderCancellationByMaker; } /// @dev Get the storage bucket for this contract. function getStorage() internal pure returns (Storage storage stor) { uint256 storageSlot = LibStorage.STORAGE_ID_ERC1155_ORDERS; // Dip into assembly to change the slot pointed to by the local // variable `stor`. // See https://solidity.readthedocs.io/en/v0.6.8/assembly.html?highlight=slot#access-to-external-variables-functions-and-libraries assembly { stor.slot := storageSlot } } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../libs/LibNFTOrder.sol"; import "../libs/LibSignature.sol"; import "./IERC1155OrdersEvent.sol"; /// @dev Feature for interacting with ERC1155 orders. interface IERC1155OrdersFeature is IERC1155OrdersEvent { /// @dev Sells an ERC1155 asset to fill the given order. /// @param buyOrder The ERC1155 buy order. /// @param signature The order signature from the maker. /// @param erc1155TokenId The ID of the ERC1155 asset being /// sold. If the given order specifies properties, /// the asset must satisfy those properties. Otherwise, /// it must equal the tokenId in the order. /// @param erc1155SellAmount The amount of the ERC1155 asset /// to sell. /// @param unwrapNativeToken If this parameter is true and the /// ERC20 token of the order is e.g. WETH, unwraps the /// token before transferring it to the taker. /// @param callbackData If this parameter is non-zero, invokes /// `zeroExERC1155OrderCallback` on `msg.sender` after /// the ERC20 tokens have been transferred to `msg.sender` /// but before transferring the ERC1155 asset to the buyer. function sellERC1155( LibNFTOrder.ERC1155BuyOrder calldata buyOrder, LibSignature.Signature calldata signature, uint256 erc1155TokenId, uint128 erc1155SellAmount, bool unwrapNativeToken, bytes calldata callbackData ) external; /// @dev Buys an ERC1155 asset by filling the given order. /// @param sellOrder The ERC1155 sell order. /// @param signature The order signature. /// @param erc1155BuyAmount The amount of the ERC1155 asset /// to buy. function buyERC1155( LibNFTOrder.ERC1155SellOrder calldata sellOrder, LibSignature.Signature calldata signature, uint128 erc1155BuyAmount ) external payable; /// @dev Buys an ERC1155 asset by filling the given order. /// @param sellOrder The ERC1155 sell order. /// @param signature The order signature. /// @param taker The address to receive ERC1155. If this parameter /// is zero, transfer ERC1155 to `msg.sender`. /// @param erc1155BuyAmount The amount of the ERC1155 asset /// to buy. /// @param callbackData If this parameter is non-zero, invokes /// `zeroExERC1155OrderCallback` on `msg.sender` after /// the ERC1155 asset has been transferred to `msg.sender` /// but before transferring the ERC20 tokens to the seller. /// Native tokens acquired during the callback can be used /// to fill the order. function buyERC1155Ex( LibNFTOrder.ERC1155SellOrder calldata sellOrder, LibSignature.Signature calldata signature, address taker, uint128 erc1155BuyAmount, bytes calldata callbackData ) external payable; /// @dev Cancel a single ERC1155 order by its nonce. The caller /// should be the maker of the order. Silently succeeds if /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonce The order nonce. function cancelERC1155Order(uint256 orderNonce) external; /// @dev Cancel multiple ERC1155 orders by their nonces. The caller /// should be the maker of the orders. Silently succeeds if /// an order with the same nonce has already been filled or /// cancelled. /// @param orderNonces The order nonces. function batchCancelERC1155Orders(uint256[] calldata orderNonces) external; /// @dev Buys multiple ERC1155 assets by filling the /// given orders. /// @param sellOrders The ERC1155 sell orders. /// @param signatures The order signatures. /// @param erc1155TokenAmounts The amounts of the ERC1155 assets /// to buy for each order. /// @param revertIfIncomplete If true, reverts if this /// function fails to fill any individual order. /// @return successes An array of booleans corresponding to whether /// each order in `orders` was successfully filled. function batchBuyERC1155s( LibNFTOrder.ERC1155SellOrder[] calldata sellOrders, LibSignature.Signature[] calldata signatures, uint128[] calldata erc1155TokenAmounts, bool revertIfIncomplete ) external payable returns (bool[] memory successes); /// @dev Buys multiple ERC1155 assets by filling the /// given orders. /// @param sellOrders The ERC1155 sell orders. /// @param signatures The order signatures. /// @param erc1155TokenAmounts The amounts of the ERC1155 assets /// to buy for each order. /// @param takers The address to receive ERC1155. /// @param callbackData The data (if any) to pass to the taker /// callback for each order. Refer to the `callbackData` /// parameter to for `buyERC1155`. /// @param revertIfIncomplete If true, reverts if this /// function fails to fill any individual order. /// @return successes An array of booleans corresponding to whether /// each order in `orders` was successfully filled. function batchBuyERC1155sEx( LibNFTOrder.ERC1155SellOrder[] calldata sellOrders, LibSignature.Signature[] calldata signatures, address[] calldata takers, uint128[] calldata erc1155TokenAmounts, bytes[] calldata callbackData, bool revertIfIncomplete ) external payable returns (bool[] memory successes); /// @dev Callback for the ERC1155 `safeTransferFrom` function. /// This callback can be used to sell an ERC1155 asset if /// a valid ERC1155 order, signature and `unwrapNativeToken` /// are encoded in `data`. This allows takers to sell their /// ERC1155 asset without first calling `setApprovalForAll`. /// @param operator The address which called `safeTransferFrom`. /// @param from The address which previously owned the token. /// @param tokenId The ID of the asset being transferred. /// @param value The amount being transferred. /// @param data Additional data with no specified format. If a /// valid ERC1155 order, signature and `unwrapNativeToken` /// are encoded in `data`, this function will try to fill /// the order using the received asset. /// @return success The selector of this function (0xf23a6e61), /// indicating that the callback succeeded. function onERC1155Received( address operator, address from, uint256 tokenId, uint256 value, bytes calldata data ) external returns (bytes4 success); /// @dev Approves an ERC1155 sell order on-chain. After pre-signing /// the order, the `PRESIGNED` signature type will become /// valid for that order and signer. /// @param order An ERC1155 sell order. function preSignERC1155SellOrder(LibNFTOrder.ERC1155SellOrder calldata order) external; /// @dev Approves an ERC1155 buy order on-chain. After pre-signing /// the order, the `PRESIGNED` signature type will become /// valid for that order and signer. /// @param order An ERC1155 buy order. function preSignERC1155BuyOrder(LibNFTOrder.ERC1155BuyOrder calldata order) external; /// @dev Checks whether the given signature is valid for the /// the given ERC1155 sell order. Reverts if not. /// @param order The ERC1155 sell order. /// @param signature The signature to validate. function validateERC1155SellOrderSignature( LibNFTOrder.ERC1155SellOrder calldata order, LibSignature.Signature calldata signature ) external view; /// @dev Checks whether the given signature is valid for the /// the given ERC1155 buy order. Reverts if not. /// @param order The ERC1155 buy order. /// @param signature The signature to validate. function validateERC1155BuyOrderSignature( LibNFTOrder.ERC1155BuyOrder calldata order, LibSignature.Signature calldata signature ) external view; /// @dev Get the order info for an ERC1155 sell order. /// @param order The ERC1155 sell order. /// @return orderInfo Infor about the order. function getERC1155SellOrderInfo(LibNFTOrder.ERC1155SellOrder calldata order) external view returns (LibNFTOrder.OrderInfo memory orderInfo); /// @dev Get the order info for an ERC1155 buy order. /// @param order The ERC1155 buy order. /// @return orderInfo Infor about the order. function getERC1155BuyOrderInfo(LibNFTOrder.ERC1155BuyOrder calldata order) external view returns (LibNFTOrder.OrderInfo memory orderInfo); /// @dev Get the EIP-712 hash of an ERC1155 sell order. /// @param order The ERC1155 sell order. /// @return orderHash The order hash. function getERC1155SellOrderHash(LibNFTOrder.ERC1155SellOrder calldata order) external view returns (bytes32 orderHash); /// @dev Get the EIP-712 hash of an ERC1155 buy order. /// @param order The ERC1155 buy order. /// @return orderHash The order hash. function getERC1155BuyOrderHash(LibNFTOrder.ERC1155BuyOrder calldata order) external view returns (bytes32 orderHash); /// @dev Get the order nonce status bit vector for the given /// maker address and nonce range. /// @param maker The maker of the order. /// @param nonceRange Order status bit vectors are indexed /// by maker address and the upper 248 bits of the /// order nonce. We define `nonceRange` to be these /// 248 bits. /// @return bitVector The order status bit vector for the /// given maker and nonce range. function getERC1155OrderNonceStatusBitVector(address maker, uint248 nonceRange) external view returns (uint256); /// @dev Matches a pair of complementary orders that have /// a non-negative spread. Each order is filled at /// their respective price, and the matcher receives /// a profit denominated in the ERC20 token. /// @param sellOrder Order selling an ERC1155 asset. /// @param buyOrder Order buying an ERC1155 asset. /// @param sellOrderSignature Signature for the sell order. /// @param buyOrderSignature Signature for the buy order. /// @return profit The amount of profit earned by the caller /// of this function (denominated in the ERC20 token /// of the matched orders). function matchERC1155Orders( LibNFTOrder.ERC1155SellOrder calldata sellOrder, LibNFTOrder.ERC1155BuyOrder calldata buyOrder, LibSignature.Signature calldata sellOrderSignature, LibSignature.Signature calldata buyOrderSignature ) external returns (uint256 profit); /// @dev Matches pairs of complementary orders that have /// non-negative spreads. Each order is filled at /// their respective price, and the matcher receives /// a profit denominated in the ERC20 token. /// @param sellOrders Orders selling ERC1155 assets. /// @param buyOrders Orders buying ERC1155 assets. /// @param sellOrderSignatures Signatures for the sell orders. /// @param buyOrderSignatures Signatures for the buy orders. /// @return profits The amount of profit earned by the caller /// of this function for each pair of matched orders /// (denominated in the ERC20 token of the order pair). /// @return successes An array of booleans corresponding to /// whether each pair of orders was successfully matched. function batchMatchERC1155Orders( LibNFTOrder.ERC1155SellOrder[] calldata sellOrders, LibNFTOrder.ERC1155BuyOrder[] calldata buyOrders, LibSignature.Signature[] calldata sellOrderSignatures, LibSignature.Signature[] calldata buyOrderSignatures ) external returns (uint256[] memory profits, bool[] memory successes); } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../vendor/IPropertyValidator.sol"; /// @dev A library for common NFT order operations. library LibNFTOrder { enum OrderStatus { INVALID, FILLABLE, UNFILLABLE, EXPIRED } struct Property { IPropertyValidator propertyValidator; bytes propertyData; } struct Fee { address recipient; uint256 amount; bytes feeData; } struct NFTSellOrder { address maker; address taker; uint256 expiry; uint256 nonce; IERC20 erc20Token; uint256 erc20TokenAmount; Fee[] fees; address nft; uint256 nftId; } // All fields except `nftProperties` align // with those of NFTSellOrder struct NFTBuyOrder { address maker; address taker; uint256 expiry; uint256 nonce; IERC20 erc20Token; uint256 erc20TokenAmount; Fee[] fees; address nft; uint256 nftId; Property[] nftProperties; } // All fields except `erc1155TokenAmount` align // with those of NFTSellOrder struct ERC1155SellOrder { address maker; address taker; uint256 expiry; uint256 nonce; IERC20 erc20Token; uint256 erc20TokenAmount; Fee[] fees; address erc1155Token; uint256 erc1155TokenId; // End of fields shared with NFTOrder uint128 erc1155TokenAmount; } // All fields except `erc1155TokenAmount` align // with those of NFTBuyOrder struct ERC1155BuyOrder { address maker; address taker; uint256 expiry; uint256 nonce; IERC20 erc20Token; uint256 erc20TokenAmount; Fee[] fees; address erc1155Token; uint256 erc1155TokenId; Property[] erc1155TokenProperties; // End of fields shared with NFTOrder uint128 erc1155TokenAmount; } struct OrderInfo { bytes32 orderHash; OrderStatus status; // `orderAmount` is 1 for all ERC721Orders, and // `erc1155TokenAmount` for ERC1155Orders. uint128 orderAmount; // The remaining amount of the ERC721/ERC1155 asset // that can be filled for the order. uint128 remainingAmount; } // The type hash for sell orders, which is: // keccak256(abi.encodePacked( // "NFTSellOrder(", // "address maker,", // "address taker,", // "uint256 expiry,", // "uint256 nonce,", // "address erc20Token,", // "uint256 erc20TokenAmount,", // "Fee[] fees,", // "address nft,", // "uint256 nftId,", // "uint256 hashNonce", // ")", // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")" // )) uint256 private constant _NFT_SELL_ORDER_TYPE_HASH = 0xed676c7f3e8232a311454799b1cf26e75b4abc90c9bf06c9f7e8e79fcc7fe14d; // The type hash for buy orders, which is: // keccak256(abi.encodePacked( // "NFTBuyOrder(", // "address maker,", // "address taker,", // "uint256 expiry,", // "uint256 nonce,", // "address erc20Token,", // "uint256 erc20TokenAmount,", // "Fee[] fees,", // "address nft,", // "uint256 nftId,", // "Property[] nftProperties,", // "uint256 hashNonce", // ")", // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")", // "Property(", // "address propertyValidator,", // "bytes propertyData", // ")" // )) uint256 private constant _NFT_BUY_ORDER_TYPE_HASH = 0xa525d336300f566329800fcbe82fd263226dc27d6c109f060d9a4a364281521c; // The type hash for ERC1155 sell orders, which is: // keccak256(abi.encodePacked( // "ERC1155SellOrder(", // "address maker,", // "address taker,", // "uint256 expiry,", // "uint256 nonce,", // "address erc20Token,", // "uint256 erc20TokenAmount,", // "Fee[] fees,", // "address erc1155Token,", // "uint256 erc1155TokenId,", // "uint128 erc1155TokenAmount,", // "uint256 hashNonce", // ")", // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")" // )) uint256 private constant _ERC_1155_SELL_ORDER_TYPE_HASH = 0x3529b5920cc48ecbceb24e9c51dccb50fefd8db2cf05d36e356aeb1754e19eda; // The type hash for ERC1155 buy orders, which is: // keccak256(abi.encodePacked( // "ERC1155BuyOrder(", // "address maker,", // "address taker,", // "uint256 expiry,", // "uint256 nonce,", // "address erc20Token,", // "uint256 erc20TokenAmount,", // "Fee[] fees,", // "address erc1155Token,", // "uint256 erc1155TokenId,", // "Property[] erc1155TokenProperties,", // "uint128 erc1155TokenAmount,", // "uint256 hashNonce", // ")", // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")", // "Property(", // "address propertyValidator,", // "bytes propertyData", // ")" // )) uint256 private constant _ERC_1155_BUY_ORDER_TYPE_HASH = 0x1a6eaae1fbed341e0974212ec17f035a9d419cadc3bf5154841cbf7fd605ba48; // keccak256(abi.encodePacked( // "Fee(", // "address recipient,", // "uint256 amount,", // "bytes feeData", // ")" // )) uint256 private constant _FEE_TYPE_HASH = 0xe68c29f1b4e8cce0bbcac76eb1334bdc1dc1f293a517c90e9e532340e1e94115; // keccak256(abi.encodePacked( // "Property(", // "address propertyValidator,", // "bytes propertyData", // ")" // )) uint256 private constant _PROPERTY_TYPE_HASH = 0x6292cf854241cb36887e639065eca63b3af9f7f70270cebeda4c29b6d3bc65e8; // keccak256(""); bytes32 private constant _EMPTY_ARRAY_KECCAK256 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // keccak256(abi.encodePacked(keccak256(abi.encode( // _PROPERTY_TYPE_HASH, // address(0), // keccak256("") // )))); bytes32 private constant _NULL_PROPERTY_STRUCT_HASH = 0x720ee400a9024f6a49768142c339bf09d2dd9056ab52d20fbe7165faba6e142d; uint256 private constant ADDRESS_MASK = (1 << 160) - 1; function asNFTSellOrder(NFTBuyOrder memory nftBuyOrder) internal pure returns (NFTSellOrder memory order) { assembly { order := nftBuyOrder } } function asNFTSellOrder(ERC1155SellOrder memory erc1155SellOrder) internal pure returns (NFTSellOrder memory order) { assembly { order := erc1155SellOrder } } function asNFTBuyOrder(ERC1155BuyOrder memory erc1155BuyOrder) internal pure returns (NFTBuyOrder memory order) { assembly { order := erc1155BuyOrder } } function asERC1155SellOrder(NFTSellOrder memory nftSellOrder) internal pure returns (ERC1155SellOrder memory order) { assembly { order := nftSellOrder } } function asERC1155BuyOrder(NFTBuyOrder memory nftBuyOrder) internal pure returns (ERC1155BuyOrder memory order) { assembly { order := nftBuyOrder } } // @dev Get the struct hash of an sell order. /// @param order The sell order. /// @return structHash The struct hash of the order. function getNFTSellOrderStructHash(NFTSellOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) { bytes32 feesHash = _feesHash(order.fees); // Hash in place, equivalent to: // return keccak256(abi.encode( // _NFT_SELL_ORDER_TYPE_HASH, // order.maker, // order.taker, // order.expiry, // order.nonce, // order.erc20Token, // order.erc20TokenAmount, // feesHash, // order.nft, // order.nftId, // hashNonce // )); assembly { if lt(order, 32) { invalid() } // Don't underflow memory. let typeHashPos := sub(order, 32) // order - 32 let feesHashPos := add(order, 192) // order + (32 * 6) let hashNoncePos := add(order, 288) // order + (32 * 9) let typeHashMemBefore := mload(typeHashPos) let feeHashMemBefore := mload(feesHashPos) let hashNonceMemBefore := mload(hashNoncePos) mstore(typeHashPos, _NFT_SELL_ORDER_TYPE_HASH) mstore(feesHashPos, feesHash) mstore(hashNoncePos, hashNonce) structHash := keccak256(typeHashPos, 352 /* 32 * 11 */ ) mstore(typeHashPos, typeHashMemBefore) mstore(feesHashPos, feeHashMemBefore) mstore(hashNoncePos, hashNonceMemBefore) } return structHash; } /// @dev Get the struct hash of an buy order. /// @param order The buy order. /// @return structHash The struct hash of the order. function getNFTBuyOrderStructHash(NFTBuyOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) { bytes32 propertiesHash = _propertiesHash(order.nftProperties); bytes32 feesHash = _feesHash(order.fees); // Hash in place, equivalent to: // return keccak256(abi.encode( // _NFT_BUY_ORDER_TYPE_HASH, // order.maker, // order.taker, // order.expiry, // order.nonce, // order.erc20Token, // order.erc20TokenAmount, // feesHash, // order.nft, // order.nftId, // propertiesHash, // hashNonce // )); assembly { if lt(order, 32) { invalid() } // Don't underflow memory. let typeHashPos := sub(order, 32) // order - 32 let feesHashPos := add(order, 192) // order + (32 * 6) let propertiesHashPos := add(order, 288) // order + (32 * 9) let hashNoncePos := add(order, 320) // order + (32 * 10) let typeHashMemBefore := mload(typeHashPos) let feeHashMemBefore := mload(feesHashPos) let propertiesHashMemBefore := mload(propertiesHashPos) let hashNonceMemBefore := mload(hashNoncePos) mstore(typeHashPos, _NFT_BUY_ORDER_TYPE_HASH) mstore(feesHashPos, feesHash) mstore(propertiesHashPos, propertiesHash) mstore(hashNoncePos, hashNonce) structHash := keccak256(typeHashPos, 384 /* 32 * 12 */ ) mstore(typeHashPos, typeHashMemBefore) mstore(feesHashPos, feeHashMemBefore) mstore(propertiesHashPos, propertiesHashMemBefore) mstore(hashNoncePos, hashNonceMemBefore) } return structHash; } /// @dev Get the struct hash of an ERC1155 sell order. /// @param order The ERC1155 sell order. /// @return structHash The struct hash of the order. function getERC1155SellOrderStructHash(ERC1155SellOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) { bytes32 feesHash = _feesHash(order.fees); // Hash in place, equivalent to: // return keccak256(abi.encode( // _ERC_1155_SELL_ORDER_TYPE_HASH, // order.maker, // order.taker, // order.expiry, // order.nonce, // order.erc20Token, // order.erc20TokenAmount, // feesHash, // order.erc1155Token, // order.erc1155TokenId, // order.erc1155TokenAmount, // hashNonce // )); assembly { if lt(order, 32) { invalid() } // Don't underflow memory. let typeHashPos := sub(order, 32) // order - 32 let feesHashPos := add(order, 192) // order + (32 * 6) let hashNoncePos := add(order, 320) // order + (32 * 10) let typeHashMemBefore := mload(typeHashPos) let feesHashMemBefore := mload(feesHashPos) let hashNonceMemBefore := mload(hashNoncePos) mstore(typeHashPos, _ERC_1155_SELL_ORDER_TYPE_HASH) mstore(feesHashPos, feesHash) mstore(hashNoncePos, hashNonce) structHash := keccak256(typeHashPos, 384 /* 32 * 12 */ ) mstore(typeHashPos, typeHashMemBefore) mstore(feesHashPos, feesHashMemBefore) mstore(hashNoncePos, hashNonceMemBefore) } return structHash; } /// @dev Get the struct hash of an ERC1155 buy order. /// @param order The ERC1155 buy order. /// @return structHash The struct hash of the order. function getERC1155BuyOrderStructHash(ERC1155BuyOrder memory order, uint256 hashNonce) internal pure returns (bytes32 structHash) { bytes32 propertiesHash = _propertiesHash(order.erc1155TokenProperties); bytes32 feesHash = _feesHash(order.fees); // Hash in place, equivalent to: // return keccak256(abi.encode( // _ERC_1155_BUY_ORDER_TYPE_HASH, // order.maker, // order.taker, // order.expiry, // order.nonce, // order.erc20Token, // order.erc20TokenAmount, // feesHash, // order.erc1155Token, // order.erc1155TokenId, // propertiesHash, // order.erc1155TokenAmount, // hashNonce // )); assembly { if lt(order, 32) { invalid() } // Don't underflow memory. let typeHashPos := sub(order, 32) // order - 32 let feesHashPos := add(order, 192) // order + (32 * 6) let propertiesHashPos := add(order, 288) // order + (32 * 9) let hashNoncePos := add(order, 352) // order + (32 * 11) let typeHashMemBefore := mload(typeHashPos) let feesHashMemBefore := mload(feesHashPos) let propertiesHashMemBefore := mload(propertiesHashPos) let hashNonceMemBefore := mload(hashNoncePos) mstore(typeHashPos, _ERC_1155_BUY_ORDER_TYPE_HASH) mstore(feesHashPos, feesHash) mstore(propertiesHashPos, propertiesHash) mstore(hashNoncePos, hashNonce) structHash := keccak256(typeHashPos, 416 /* 32 * 13 */ ) mstore(typeHashPos, typeHashMemBefore) mstore(feesHashPos, feesHashMemBefore) mstore(propertiesHashPos, propertiesHashMemBefore) mstore(hashNoncePos, hashNonceMemBefore) } return structHash; } // Hashes the `properties` array as part of computing the // EIP-712 hash of an `ERC721Order` or `ERC1155Order`. function _propertiesHash(Property[] memory properties) private pure returns (bytes32 propertiesHash) { uint256 numProperties = properties.length; // We give `properties.length == 0` and `properties.length == 1` // special treatment because we expect these to be the most common. if (numProperties == 0) { propertiesHash = _EMPTY_ARRAY_KECCAK256; } else if (numProperties == 1) { Property memory property = properties[0]; if (address(property.propertyValidator) == address(0) && property.propertyData.length == 0) { propertiesHash = _NULL_PROPERTY_STRUCT_HASH; } else { // propertiesHash = keccak256(abi.encodePacked(keccak256(abi.encode( // _PROPERTY_TYPE_HASH, // properties[0].propertyValidator, // keccak256(properties[0].propertyData) // )))); bytes32 dataHash = keccak256(property.propertyData); assembly { // Load free memory pointer let mem := mload(64) mstore(mem, _PROPERTY_TYPE_HASH) // property.propertyValidator mstore(add(mem, 32), and(ADDRESS_MASK, mload(property))) // keccak256(property.propertyData) mstore(add(mem, 64), dataHash) mstore(mem, keccak256(mem, 96)) propertiesHash := keccak256(mem, 32) } } } else { bytes32[] memory propertyStructHashArray = new bytes32[](numProperties); for (uint256 i = 0; i < numProperties; i++) { propertyStructHashArray[i] = keccak256(abi.encode( _PROPERTY_TYPE_HASH, properties[i].propertyValidator, keccak256(properties[i].propertyData))); } assembly { propertiesHash := keccak256(add(propertyStructHashArray, 32), mul(numProperties, 32)) } } } // Hashes the `fees` array as part of computing the // EIP-712 hash of an `ERC721Order` or `ERC1155Order`. function _feesHash(Fee[] memory fees) private pure returns (bytes32 feesHash) { uint256 numFees = fees.length; // We give `fees.length == 0` and `fees.length == 1` // special treatment because we expect these to be the most common. if (numFees == 0) { feesHash = _EMPTY_ARRAY_KECCAK256; } else if (numFees == 1) { // feesHash = keccak256(abi.encodePacked(keccak256(abi.encode( // _FEE_TYPE_HASH, // fees[0].recipient, // fees[0].amount, // keccak256(fees[0].feeData) // )))); Fee memory fee = fees[0]; bytes32 dataHash = keccak256(fee.feeData); assembly { // Load free memory pointer let mem := mload(64) mstore(mem, _FEE_TYPE_HASH) // fee.recipient mstore(add(mem, 32), and(ADDRESS_MASK, mload(fee))) // fee.amount mstore(add(mem, 64), mload(add(fee, 32))) // keccak256(fee.feeData) mstore(add(mem, 96), dataHash) mstore(mem, keccak256(mem, 128)) feesHash := keccak256(mem, 32) } } else { bytes32[] memory feeStructHashArray = new bytes32[](numFees); for (uint256 i = 0; i < numFees; i++) { feeStructHashArray[i] = keccak256(abi.encode(_FEE_TYPE_HASH, fees[i].recipient, fees[i].amount, keccak256(fees[i].feeData))); } assembly { feesHash := keccak256(add(feeStructHashArray, 32), mul(numFees, 32)) } } } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; /// @dev A library for validating signatures. library LibSignature { /// @dev Allowed signature types. enum SignatureType { EIP712, PRESIGNED } /// @dev Encoded EC signature. struct Signature { // How to validate the signature. SignatureType signatureType; // EC Signature data. uint8 v; // EC Signature data. bytes32 r; // EC Signature data. bytes32 s; } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../fixins/FixinEIP712.sol"; import "../../fixins/FixinTokenSpender.sol"; import "../../vendor/IEtherToken.sol"; import "../../vendor/IFeeRecipient.sol"; import "../../vendor/ITakerCallback.sol"; import "../libs/LibSignature.sol"; import "../libs/LibNFTOrder.sol"; /// @dev Abstract base contract inherited by ERC721OrdersFeature and NFTOrders abstract contract NFTOrders is FixinEIP712, FixinTokenSpender { using LibNFTOrder for LibNFTOrder.NFTBuyOrder; /// @dev Native token pseudo-address. address constant internal NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev The WETH token contract. IEtherToken internal immutable WETH; /// @dev The implementation address of this feature. address internal immutable _implementation; /// @dev The magic return value indicating the success of a `receiveZeroExFeeCallback`. bytes4 private constant FEE_CALLBACK_MAGIC_BYTES = IFeeRecipient.receiveZeroExFeeCallback.selector; /// @dev The magic return value indicating the success of a `zeroExTakerCallback`. bytes4 private constant TAKER_CALLBACK_MAGIC_BYTES = ITakerCallback.zeroExTakerCallback.selector; constructor(IEtherToken weth) { require(address(weth) != address(0), "WETH_ADDRESS_ERROR"); WETH = weth; // Remember this feature's original address. _implementation = address(this); } struct SellParams { uint128 sellAmount; uint256 tokenId; bool unwrapNativeToken; address taker; address currentNftOwner; bytes takerCallbackData; } struct BuyParams { uint128 buyAmount; uint256 ethAvailable; address taker; bytes takerCallbackData; } // Core settlement logic for selling an NFT asset. function _sellNFT( LibNFTOrder.NFTBuyOrder memory buyOrder, LibSignature.Signature memory signature, SellParams memory params ) internal returns (uint256 erc20FillAmount, bytes32 orderHash) { LibNFTOrder.OrderInfo memory orderInfo = _getOrderInfo(buyOrder); orderHash = orderInfo.orderHash; // Check that the order can be filled. _validateBuyOrder(buyOrder, signature, orderInfo, params.taker, params.tokenId); // Check amount. if (params.sellAmount > orderInfo.remainingAmount) { revert("_sellNFT/EXCEEDS_REMAINING_AMOUNT"); } // Update the order state. _updateOrderState(buyOrder.asNFTSellOrder(), orderInfo.orderHash, params.sellAmount); // Calculate erc20 pay amount. erc20FillAmount = (params.sellAmount == orderInfo.orderAmount) ? buyOrder.erc20TokenAmount : buyOrder.erc20TokenAmount * params.sellAmount / orderInfo.orderAmount; if (params.unwrapNativeToken) { // The ERC20 token must be WETH for it to be unwrapped. require(buyOrder.erc20Token == WETH, "_sellNFT/ERC20_TOKEN_MISMATCH_ERROR"); // Transfer the WETH from the maker to the Exchange Proxy // so we can unwrap it before sending it to the seller. // TODO: Probably safe to just use WETH.transferFrom for some // small gas savings _transferERC20TokensFrom(WETH, buyOrder.maker, address(this), erc20FillAmount); // Unwrap WETH into ETH. WETH.withdraw(erc20FillAmount); // Send ETH to the seller. _transferEth(payable(params.taker), erc20FillAmount); } else { // Transfer the ERC20 token from the buyer to the seller. _transferERC20TokensFrom(buyOrder.erc20Token, buyOrder.maker, params.taker, erc20FillAmount); } if (params.takerCallbackData.length > 0) { require(params.taker != address(this), "_sellNFT/CANNOT_CALLBACK_SELF"); // Invoke the callback bytes4 callbackResult = ITakerCallback(params.taker).zeroExTakerCallback(orderInfo.orderHash, params.takerCallbackData); // Check for the magic success bytes require(callbackResult == TAKER_CALLBACK_MAGIC_BYTES, "_sellNFT/CALLBACK_FAILED"); } // Transfer the NFT asset to the buyer. // If this function is called from the // `onNFTReceived` callback the Exchange Proxy // holds the asset. Otherwise, transfer it from // the seller. _transferNFTAssetFrom(buyOrder.nft, params.currentNftOwner, buyOrder.maker, params.tokenId, params.sellAmount); // The buyer pays the order fees. _payFees(buyOrder.asNFTSellOrder(), buyOrder.maker, params.sellAmount, orderInfo.orderAmount, false); } // Core settlement logic for buying an NFT asset. function _buyNFT( LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature, uint128 buyAmount ) internal returns (uint256 erc20FillAmount, bytes32 orderHash) { LibNFTOrder.OrderInfo memory orderInfo = _getOrderInfo(sellOrder); orderHash = orderInfo.orderHash; // Check that the order can be filled. _validateSellOrder(sellOrder, signature, orderInfo, msg.sender); // Check amount. if (buyAmount > orderInfo.remainingAmount) { revert("_buyNFT/EXCEEDS_REMAINING_AMOUNT"); } // Update the order state. _updateOrderState(sellOrder, orderInfo.orderHash, buyAmount); // Calculate erc20 pay amount. erc20FillAmount = (buyAmount == orderInfo.orderAmount) ? sellOrder.erc20TokenAmount : _ceilDiv(sellOrder.erc20TokenAmount * buyAmount, orderInfo.orderAmount); // Transfer the NFT asset to the buyer (`msg.sender`). _transferNFTAssetFrom(sellOrder.nft, sellOrder.maker, msg.sender, sellOrder.nftId, buyAmount); if (address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS) { // Transfer ETH to the seller. _transferEth(payable(sellOrder.maker), erc20FillAmount); // Fees are paid from the EP's current balance of ETH. _payFees(sellOrder, address(this), buyAmount, orderInfo.orderAmount, true); } else { // Transfer ERC20 token from the buyer to the seller. _transferERC20TokensFrom(sellOrder.erc20Token, msg.sender, sellOrder.maker, erc20FillAmount); // The buyer pays fees. _payFees(sellOrder, msg.sender, buyAmount, orderInfo.orderAmount, false); } } function _buyNFTEx( LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature, BuyParams memory params ) internal returns (uint256 erc20FillAmount, bytes32 orderHash) { LibNFTOrder.OrderInfo memory orderInfo = _getOrderInfo(sellOrder); orderHash = orderInfo.orderHash; // Check that the order can be filled. _validateSellOrder(sellOrder, signature, orderInfo, params.taker); // Check amount. if (params.buyAmount > orderInfo.remainingAmount) { revert("_buyNFTEx/EXCEEDS_REMAINING_AMOUNT"); } // Update the order state. _updateOrderState(sellOrder, orderInfo.orderHash, params.buyAmount); // Dutch Auction if (sellOrder.expiry >> 252 == 1) { uint256 count = (sellOrder.expiry >> 64) & 0xffffffff; if (count > 0) { _resetDutchAuctionTokenAmountAndFees(sellOrder, count); } } // Calculate erc20 pay amount. erc20FillAmount = (params.buyAmount == orderInfo.orderAmount) ? sellOrder.erc20TokenAmount : _ceilDiv(sellOrder.erc20TokenAmount * params.buyAmount, orderInfo.orderAmount); // Transfer the NFT asset to the buyer. _transferNFTAssetFrom(sellOrder.nft, sellOrder.maker, params.taker, sellOrder.nftId, params.buyAmount); uint256 ethAvailable = params.ethAvailable; if (params.takerCallbackData.length > 0) { require(params.taker != address(this), "_buyNFTEx/CANNOT_CALLBACK_SELF"); uint256 ethBalanceBeforeCallback = address(this).balance; // Invoke the callback bytes4 callbackResult = ITakerCallback(params.taker).zeroExTakerCallback(orderInfo.orderHash, params.takerCallbackData); // Update `ethAvailable` with amount acquired during // the callback ethAvailable += address(this).balance - ethBalanceBeforeCallback; // Check for the magic success bytes require(callbackResult == TAKER_CALLBACK_MAGIC_BYTES, "_buyNFTEx/CALLBACK_FAILED"); } if (address(sellOrder.erc20Token) == NATIVE_TOKEN_ADDRESS) { uint256 totalPaid = erc20FillAmount + _calcTotalFeesPaid(sellOrder.fees, params.buyAmount, orderInfo.orderAmount); if (ethAvailable < totalPaid) { // Transfer WETH from the buyer to this contract. uint256 withDrawAmount = totalPaid - ethAvailable; _transferERC20TokensFrom(WETH, msg.sender, address(this), withDrawAmount); // Unwrap WETH into ETH. WETH.withdraw(withDrawAmount); } // Transfer ETH to the seller. _transferEth(payable(sellOrder.maker), erc20FillAmount); // Fees are paid from the EP's current balance of ETH. _payFees(sellOrder, address(this), params.buyAmount, orderInfo.orderAmount, true); } else if (sellOrder.erc20Token == WETH) { uint256 totalFeesPaid = _calcTotalFeesPaid(sellOrder.fees, params.buyAmount, orderInfo.orderAmount); if (ethAvailable > totalFeesPaid) { uint256 depositAmount = ethAvailable - totalFeesPaid; if (depositAmount < erc20FillAmount) { // Transfer WETH from the buyer to this contract. _transferERC20TokensFrom(WETH, msg.sender, address(this), (erc20FillAmount - depositAmount)); } else { depositAmount = erc20FillAmount; } // Wrap ETH. WETH.deposit{value: depositAmount}(); // Transfer WETH to the seller. _transferERC20Tokens(WETH, sellOrder.maker, erc20FillAmount); // Fees are paid from the EP's current balance of ETH. _payFees(sellOrder, address(this), params.buyAmount, orderInfo.orderAmount, true); } else { // Transfer WETH from the buyer to the seller. _transferERC20TokensFrom(WETH, msg.sender, sellOrder.maker, erc20FillAmount); if (ethAvailable > 0) { if (ethAvailable < totalFeesPaid) { // Transfer WETH from the buyer to this contract. uint256 value = totalFeesPaid - ethAvailable; _transferERC20TokensFrom(WETH, msg.sender, address(this), value); // Unwrap WETH into ETH. WETH.withdraw(value); } // Fees are paid from the EP's current balance of ETH. _payFees(sellOrder, address(this), params.buyAmount, orderInfo.orderAmount, true); } else { // The buyer pays fees using WETH. _payFees(sellOrder, msg.sender, params.buyAmount, orderInfo.orderAmount, false); } } } else { // Transfer ERC20 token from the buyer to the seller. _transferERC20TokensFrom(sellOrder.erc20Token, msg.sender, sellOrder.maker, erc20FillAmount); // The buyer pays fees. _payFees(sellOrder, msg.sender, params.buyAmount, orderInfo.orderAmount, false); } } function _validateSellOrder( LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature, LibNFTOrder.OrderInfo memory orderInfo, address taker ) internal view { // Taker must match the order taker, if one is specified. require(sellOrder.taker == address(0) || sellOrder.taker == taker, "_validateOrder/ONLY_TAKER"); // Check that the order is valid and has not expired, been cancelled, // or been filled. require(orderInfo.status == LibNFTOrder.OrderStatus.FILLABLE, "_validateOrder/ORDER_NOT_FILL"); // Check the signature. _validateOrderSignature(orderInfo.orderHash, signature, sellOrder.maker); } function _validateBuyOrder( LibNFTOrder.NFTBuyOrder memory buyOrder, LibSignature.Signature memory signature, LibNFTOrder.OrderInfo memory orderInfo, address taker, uint256 tokenId ) internal view { // The ERC20 token cannot be ETH. require(address(buyOrder.erc20Token) != NATIVE_TOKEN_ADDRESS, "_validateBuyOrder/TOKEN_MISMATCH"); // Taker must match the order taker, if one is specified. require(buyOrder.taker == address(0) || buyOrder.taker == taker, "_validateBuyOrder/ONLY_TAKER"); // Check that the order is valid and has not expired, been cancelled, // or been filled. require(orderInfo.status == LibNFTOrder.OrderStatus.FILLABLE, "_validateOrder/ORDER_NOT_FILL"); // Check that the asset with the given token ID satisfies the properties // specified by the order. _validateOrderProperties(buyOrder, tokenId); // Check the signature. _validateOrderSignature(orderInfo.orderHash, signature, buyOrder.maker); } function _resetDutchAuctionTokenAmountAndFees(LibNFTOrder.NFTSellOrder memory order, uint256 count) internal view { require(count <= 100000000, "COUNT_OUT_OF_SIDE"); uint256 listingTime = (order.expiry >> 32) & 0xffffffff; uint256 denominator = ((order.expiry & 0xffffffff) - listingTime) * 100000000; uint256 multiplier = (block.timestamp - listingTime) * count; // Reset erc20TokenAmount uint256 amount = order.erc20TokenAmount; order.erc20TokenAmount = amount - amount * multiplier / denominator; // Reset fees for (uint256 i = 0; i < order.fees.length; i++) { amount = order.fees[i].amount; order.fees[i].amount = amount - amount * multiplier / denominator; } } function _resetEnglishAuctionTokenAmountAndFees( LibNFTOrder.NFTSellOrder memory sellOrder, uint256 buyERC20Amount, uint256 fillAmount, uint256 orderAmount ) internal pure { uint256 sellOrderFees = _calcTotalFeesPaid(sellOrder.fees, fillAmount, orderAmount); uint256 sellTotalAmount = sellOrderFees + sellOrder.erc20TokenAmount; if (buyERC20Amount != sellTotalAmount) { uint256 spread = buyERC20Amount - sellTotalAmount; uint256 sum; // Reset fees if (sellTotalAmount > 0) { for (uint256 i = 0; i < sellOrder.fees.length; i++) { uint256 diff = spread * sellOrder.fees[i].amount / sellTotalAmount; sellOrder.fees[i].amount += diff; sum += diff; } } // Reset erc20TokenAmount sellOrder.erc20TokenAmount += spread - sum; } } function _ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // ceil(a / b) = floor((a + b - 1) / b) return (a + b - 1) / b; } function _calcTotalFeesPaid(LibNFTOrder.Fee[] memory fees, uint256 fillAmount, uint256 orderAmount) private pure returns (uint256 totalFeesPaid) { if (fillAmount == orderAmount) { for (uint256 i = 0; i < fees.length; i++) { totalFeesPaid += fees[i].amount; } } else { for (uint256 i = 0; i < fees.length; i++) { totalFeesPaid += fees[i].amount * fillAmount / orderAmount; } } return totalFeesPaid; } function _payFees( LibNFTOrder.NFTSellOrder memory order, address payer, uint128 fillAmount, uint128 orderAmount, bool useNativeToken ) internal returns (uint256 totalFeesPaid) { for (uint256 i = 0; i < order.fees.length; i++) { LibNFTOrder.Fee memory fee = order.fees[i]; uint256 feeFillAmount = (fillAmount == orderAmount) ? fee.amount : fee.amount * fillAmount / orderAmount; if (useNativeToken) { // Transfer ETH to the fee recipient. _transferEth(payable(fee.recipient), feeFillAmount); } else { if (feeFillAmount > 0) { // Transfer ERC20 token from payer to recipient. _transferERC20TokensFrom(order.erc20Token, payer, fee.recipient, feeFillAmount); } } // Note that the fee callback is _not_ called if zero // `feeData` is provided. If `feeData` is provided, we assume // the fee recipient is a contract that implements the // `IFeeRecipient` interface. if (fee.feeData.length > 0) { // Invoke the callback bytes4 callbackResult = IFeeRecipient(fee.recipient).receiveZeroExFeeCallback( useNativeToken ? NATIVE_TOKEN_ADDRESS : address(order.erc20Token), feeFillAmount, fee.feeData ); // Check for the magic success bytes require(callbackResult == FEE_CALLBACK_MAGIC_BYTES, "_payFees/CALLBACK_FAILED"); } // Sum the fees paid totalFeesPaid += feeFillAmount; } return totalFeesPaid; } function _validateOrderProperties(LibNFTOrder.NFTBuyOrder memory order, uint256 tokenId) internal view { // If no properties are specified, check that the given // `tokenId` matches the one specified in the order. if (order.nftProperties.length == 0) { require(tokenId == order.nftId, "_validateProperties/TOKEN_ID_ERR"); } else { // Validate each property for (uint256 i = 0; i < order.nftProperties.length; i++) { LibNFTOrder.Property memory property = order.nftProperties[i]; // `address(0)` is interpreted as a no-op. Any token ID // will satisfy a property with `propertyValidator == address(0)`. if (address(property.propertyValidator) != address(0)) { // Call the property validator and throw a descriptive error // if the call reverts. try property.propertyValidator.validateProperty(order.nft, tokenId, property.propertyData) { } catch (bytes memory /* reason */) { revert("PROPERTY_VALIDATION_FAILED"); } } } } } /// @dev Validates that the given signature is valid for the /// given maker and order hash. Reverts if the signature /// is not valid. /// @param orderHash The hash of the order that was signed. /// @param signature The signature to check. /// @param maker The maker of the order. function _validateOrderSignature(bytes32 orderHash, LibSignature.Signature memory signature, address maker) internal virtual view; /// @dev Transfers an NFT asset. /// @param token The address of the NFT contract. /// @param from The address currently holding the asset. /// @param to The address to transfer the asset to. /// @param tokenId The ID of the asset to transfer. /// @param amount The amount of the asset to transfer. Always /// 1 for ERC721 assets. function _transferNFTAssetFrom(address token, address from, address to, uint256 tokenId, uint256 amount) internal virtual; /// @dev Updates storage to indicate that the given order /// has been filled by the given amount. /// @param order The order that has been filled. /// @param orderHash The hash of `order`. /// @param fillAmount The amount (denominated in the NFT asset) /// that the order has been filled by. function _updateOrderState(LibNFTOrder.NFTSellOrder memory order, bytes32 orderHash, uint128 fillAmount) internal virtual; /// @dev Get the order info for an NFT sell order. /// @param nftSellOrder The NFT sell order. /// @return orderInfo Info about the order. function _getOrderInfo(LibNFTOrder.NFTSellOrder memory nftSellOrder) internal virtual view returns (LibNFTOrder.OrderInfo memory); /// @dev Get the order info for an NFT buy order. /// @param nftBuyOrder The NFT buy order. /// @return orderInfo Info about the order. function _getOrderInfo(LibNFTOrder.NFTBuyOrder memory nftBuyOrder) internal virtual view returns (LibNFTOrder.OrderInfo memory); } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; /// @dev Common storage helpers library LibStorage { /// @dev What to bit-shift a storage ID by to get its slot. /// This gives us a maximum of 2**128 inline fields in each bucket. uint256 constant STORAGE_ID_PROXY = 1 << 128; uint256 constant STORAGE_ID_SIMPLE_FUNCTION_REGISTRY = 2 << 128; uint256 constant STORAGE_ID_OWNABLE = 3 << 128; uint256 constant STORAGE_ID_COMMON_NFT_ORDERS = 4 << 128; uint256 constant STORAGE_ID_ERC721_ORDERS = 5 << 128; uint256 constant STORAGE_ID_ERC1155_ORDERS = 6 << 128; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../libs/LibNFTOrder.sol"; interface IERC1155OrdersEvent { /// @dev Emitted whenever an `ERC1155SellOrder` is filled. /// @param maker The maker of the order. /// @param taker The taker of the order. /// @param erc20Token (96bit ERC20FillAmount + 160bit ERC20TokenAddress). /// @param erc1155Token (96bit ERC1155TokenId + 160bit ERC1155TokenAddress). /// @param erc1155FillAmount The amount of ERC1155 asset filled. event ERC1155SellOrderFilled( address maker, address taker, uint256 erc20Token, uint256 erc1155Token, uint128 erc1155FillAmount, bytes32 orderHash ); /// @dev Emitted whenever an `ERC1155BuyOrder` is filled. /// @param maker The maker of the order. /// @param taker The taker of the order. /// @param erc20Token (96bit ERC20FillAmount + 160bit ERC20TokenAddress). /// @param erc1155Token (96bit ERC1155TokenId + 160bit ERC1155TokenAddress). /// @param erc1155FillAmount The amount of ERC1155 asset filled. event ERC1155BuyOrderFilled( address maker, address taker, uint256 erc20Token, uint256 erc1155Token, uint128 erc1155FillAmount, bytes32 orderHash ); /// @dev Emitted when an `ERC1155SellOrder` is pre-signed. /// Contains all the fields of the order. event ERC1155SellOrderPreSigned( address maker, address taker, uint256 expiry, uint256 nonce, IERC20 erc20Token, uint256 erc20TokenAmount, LibNFTOrder.Fee[] fees, address erc1155Token, uint256 erc1155TokenId, uint128 erc1155TokenAmount ); /// @dev Emitted when an `ERC1155BuyOrder` is pre-signed. /// Contains all the fields of the order. event ERC1155BuyOrderPreSigned( address maker, address taker, uint256 expiry, uint256 nonce, IERC20 erc20Token, uint256 erc20TokenAmount, LibNFTOrder.Fee[] fees, address erc1155Token, uint256 erc1155TokenId, LibNFTOrder.Property[] erc1155TokenProperties, uint128 erc1155TokenAmount ); /// @dev Emitted whenever an `ERC1155Order` is cancelled. /// @param maker The maker of the order. /// @param nonce The nonce of the order that was cancelled. event ERC1155OrderCancelled(address maker, uint256 nonce); } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; interface IPropertyValidator { /// @dev Checks that the given ERC721/ERC1155 asset satisfies the properties encoded in `propertyData`. /// Should revert if the asset does not satisfy the specified properties. /// @param tokenAddress The ERC721/ERC1155 token contract address. /// @param tokenId The ERC721/ERC1155 tokenId of the asset to check. /// @param propertyData Encoded properties or auxiliary data needed to perform the check. function validateProperty(address tokenAddress, uint256 tokenId, bytes calldata propertyData) external view; } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; /// @dev EIP712 helpers for features. abstract contract FixinEIP712 { bytes32 private constant DOMAIN = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); bytes32 private constant NAME = keccak256("ElementEx"); bytes32 private constant VERSION = keccak256("1.0.0"); uint256 private immutable CHAIN_ID; constructor() { uint256 chainId; assembly { chainId := chainid() } CHAIN_ID = chainId; } function _getEIP712Hash(bytes32 structHash) internal view returns (bytes32) { return keccak256(abi.encodePacked(hex"1901", keccak256(abi.encode(DOMAIN, NAME, VERSION, CHAIN_ID, address(this))), structHash)); } } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2020 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; /// @dev Helpers for moving tokens around. abstract contract FixinTokenSpender { // Mask of the lower 20 bytes of a bytes32. uint256 constant private ADDRESS_MASK = 0x000000000000000000000000ffffffffffffffffffffffffffffffffffffffff; /// @dev Transfers ERC20 tokens from `owner` to `to`. /// @param token The token to spend. /// @param owner The owner of the tokens. /// @param to The recipient of the tokens. /// @param amount The amount of `token` to transfer. function _transferERC20TokensFrom(IERC20 token, address owner, address to, uint256 amount) internal { uint256 success; assembly { let ptr := mload(0x40) // free memory pointer // selector for transferFrom(address,address,uint256) mstore(ptr, 0x23b872dd00000000000000000000000000000000000000000000000000000000) mstore(add(ptr, 0x04), and(owner, ADDRESS_MASK)) mstore(add(ptr, 0x24), and(to, ADDRESS_MASK)) mstore(add(ptr, 0x44), amount) success := call(gas(), and(token, ADDRESS_MASK), 0, ptr, 0x64, ptr, 32) let rdsize := returndatasize() // Check for ERC20 success. ERC20 tokens should return a boolean, // but some don't. We accept 0-length return data as success, or at // least 32 bytes that starts with a 32-byte boolean true. success := and( success, // call itself succeeded or( iszero(rdsize), // no return data, or and( iszero(lt(rdsize, 32)), // at least 32 bytes eq(mload(ptr), 1) // starts with uint256(1) ) ) ) } require(success != 0, "_transferERC20/TRANSFER_FAILED"); } /// @dev Transfers ERC20 tokens from ourselves to `to`. /// @param token The token to spend. /// @param to The recipient of the tokens. /// @param amount The amount of `token` to transfer. function _transferERC20Tokens(IERC20 token, address to, uint256 amount) internal { uint256 success; assembly { let ptr := mload(0x40) // free memory pointer // selector for transfer(address,uint256) mstore(ptr, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) mstore(add(ptr, 0x04), and(to, ADDRESS_MASK)) mstore(add(ptr, 0x24), amount) success := call(gas(), and(token, ADDRESS_MASK), 0, ptr, 0x44, ptr, 32) let rdsize := returndatasize() // Check for ERC20 success. ERC20 tokens should return a boolean, // but some don't. We accept 0-length return data as success, or at // least 32 bytes that starts with a 32-byte boolean true. success := and( success, // call itself succeeded or( iszero(rdsize), // no return data, or and( iszero(lt(rdsize, 32)), // at least 32 bytes eq(mload(ptr), 1) // starts with uint256(1) ) ) ) } require(success != 0, "_transferERC20/TRANSFER_FAILED"); } /// @dev Transfers some amount of ETH to the given recipient and /// reverts if the transfer fails. /// @param recipient The recipient of the ETH. /// @param amount The amount of ETH to transfer. function _transferEth(address payable recipient, uint256 amount) internal { if (amount > 0) { (bool success,) = recipient.call{value: amount}(""); require(success, "_transferEth/TRANSFER_FAILED"); } } } // SPDX-License-Identifier: Apache-2.0 /* Copyright 2022 Element.Market 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.8.13; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IEtherToken is IERC20 { /// @dev Wrap ether. function deposit() external payable; /// @dev Unwrap ether. function withdraw(uint256 amount) external; } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; interface IFeeRecipient { /// @dev A callback function invoked in the ERC721Feature for each ERC721 /// order fee that get paid. Integrators can make use of this callback /// to implement arbitrary fee-handling logic, e.g. splitting the fee /// between multiple parties. /// @param tokenAddress The address of the token in which the received fee is /// denominated. `0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE` indicates /// that the fee was paid in the native token (e.g. ETH). /// @param amount The amount of the given token received. /// @param feeData Arbitrary data encoded in the `Fee` used by this callback. /// @return success The selector of this function (0x0190805e), /// indicating that the callback succeeded. function receiveZeroExFeeCallback(address tokenAddress, uint256 amount, bytes calldata feeData) external returns (bytes4 success); } // SPDX-License-Identifier: Apache-2.0 /* Modifications Copyright 2022 Element.Market Copyright 2021 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.8.13; interface ITakerCallback { /// @dev A taker callback function invoked in ERC721OrdersFeature and /// ERC1155OrdersFeature between the maker -> taker transfer and /// the taker -> maker transfer. /// @param orderHash The hash of the order being filled when this /// callback is invoked. /// @param data Arbitrary data used by this callback. /// @return success The selector of this function, /// indicating that the callback succeeded. function zeroExTakerCallback(bytes32 orderHash, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (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); } }
Taker must match the order taker, if one is specified. Check that the order is valid and has not expired, been cancelled, or been filled. Check the signature.
function _validateSellOrder( LibNFTOrder.NFTSellOrder memory sellOrder, LibSignature.Signature memory signature, LibNFTOrder.OrderInfo memory orderInfo, address taker ) internal view { require(sellOrder.taker == address(0) || sellOrder.taker == taker, "_validateOrder/ONLY_TAKER"); require(orderInfo.status == LibNFTOrder.OrderStatus.FILLABLE, "_validateOrder/ORDER_NOT_FILL"); _validateOrderSignature(orderInfo.orderHash, signature, sellOrder.maker); }
1,499,190
[ 1, 56, 6388, 1297, 845, 326, 1353, 268, 6388, 16, 309, 1245, 353, 1269, 18, 2073, 716, 326, 1353, 353, 923, 471, 711, 486, 7708, 16, 2118, 13927, 16, 578, 2118, 6300, 18, 2073, 326, 3372, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 5662, 55, 1165, 2448, 12, 203, 3639, 10560, 50, 4464, 2448, 18, 50, 4464, 55, 1165, 2448, 3778, 357, 80, 2448, 16, 203, 3639, 10560, 5374, 18, 5374, 3778, 3372, 16, 203, 3639, 10560, 50, 4464, 2448, 18, 2448, 966, 3778, 1353, 966, 16, 203, 3639, 1758, 268, 6388, 203, 565, 262, 2713, 1476, 288, 203, 3639, 2583, 12, 87, 1165, 2448, 18, 88, 6388, 422, 1758, 12, 20, 13, 747, 357, 80, 2448, 18, 88, 6388, 422, 268, 6388, 16, 4192, 5662, 2448, 19, 10857, 67, 9833, 27221, 8863, 203, 203, 3639, 2583, 12, 1019, 966, 18, 2327, 422, 10560, 50, 4464, 2448, 18, 2448, 1482, 18, 1653, 11998, 16, 4192, 5662, 2448, 19, 7954, 67, 4400, 67, 29818, 8863, 203, 203, 3639, 389, 5662, 2448, 5374, 12, 1019, 966, 18, 1019, 2310, 16, 3372, 16, 357, 80, 2448, 18, 29261, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * Note for the truffle testversion: * DragonKingTest inherits from DragonKing and adds one more function for testing the volcano from truffle. * For deployment on ropsten or mainnet, just deploy the DragonKing contract and remove this comment before verifying on * etherscan. * */ /** * Dragonking is a blockchain game in which players may purchase dragons and knights of different levels and values. * Once every period of time the volcano erupts and wipes a few of them from the board. The value of the killed characters * gets distributed amongst all of the survivors. The dragon king receive a bigger share than the others. * In contrast to dragons, knights need to be teleported to the battlefield first with the use of teleport tokens. * Additionally, they may attack a dragon once per period. * Both character types can be protected from death up to three times. * Take a look at dragonking.io for more detailed information. * @author: Julia Altenried, Yuriy Kashnikov * */ pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Destructible * @dev Base contract that can be destroyed by owner. All funds in contract will be sent to the owner. */ contract Destructible is Ownable { function Destructible() public payable { } /** * @dev Transfers the current balance to the owner and terminates the contract. */ function destroy() onlyOwner public { selfdestruct(owner); } function destroyAndSend(address _recipient) onlyOwner public { selfdestruct(_recipient); } } contract DragonKingConfig { /** the cost of each character type */ uint128[] public costs; /** the value of each character type (cost - fee), so it's not necessary to compute it each time*/ uint128[] public values; /** the fee to be paid each time an character is bought in percent*/ uint8 fee; /** The maximum of characters allowed in the game */ uint16 public maxCharacters; /** the amount of time that should pass since last eruption **/ uint256 public eruptionThreshold; /** the amount of time that should pass ince last castle loot distribution **/ uint256 public castleLootDistributionThreshold; /** how many characters to kill in %, e.g. 20 will stand for 20%, should be < 100 **/ uint8 public percentageToKill; /* Cooldown threshold */ uint256 public constant CooldownThreshold = 1 days; /** fight factor, used to compute extra probability in fight **/ uint8 public fightFactor; /** the price for teleportation*/ uint256 public teleportPrice; /** the price for protection */ uint256 public protectionPrice; } interface Token { function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function transfer(address _to, uint256 _value) external returns (bool success); function balanceOf(address who) external view returns (uint256); } contract DragonKing is Destructible { /** * @dev Throws if called by contract not a user */ modifier onlyUser() { require(msg.sender == tx.origin, "contracts cannot execute this method" ); _; } struct Character { uint8 characterType; uint128 value; address owner; uint64 purchaseTimestamp; } DragonKingConfig public config; /** the neverdue token contract used to purchase protection from eruptions and fights */ Token public neverdieToken; /** the teleport token contract used to send knights to the game scene */ Token public teleportToken; /** the SKL token contract **/ Token public sklToken; /** the XP token contract **/ Token public xperToken; /** array holding ids of the curret characters **/ uint32[] public ids; /** the id to be given to the next character **/ uint32 public nextId; /** non-existant character **/ uint16 public constant INVALID_CHARACTER_INDEX = ~uint16(0); /** the castle treasury **/ uint128 public castleTreasury; /** the id of the oldest character **/ uint32 public oldest; /** the character belonging to a given id **/ mapping(uint32 => Character) characters; /** teleported knights **/ mapping(uint32 => bool) teleported; /** constant used to signal that there is no King at the moment **/ uint32 constant public noKing = ~uint32(0); /** total number of characters in the game **/ uint16 public numCharacters; /** number of characters per type **/ mapping(uint8 => uint16) public numCharactersXType; /** timestampt of the last eruption event **/ uint256 public lastEruptionTimestamp; /** timestampt of the last castle loot distribution **/ uint256 public lastCastleLootDistributionTimestamp; /** character type range constants **/ uint8 public constant DRAGON_MIN_TYPE = 0; uint8 public constant DRAGON_MAX_TYPE = 5; uint8 public constant KNIGHT_MIN_TYPE = 6; uint8 public constant KNIGHT_MAX_TYPE = 11; uint8 public constant BALLOON_MIN_TYPE = 12; uint8 public constant BALLOON_MAX_TYPE = 14; uint8 public constant WIZARD_MIN_TYPE = 15; uint8 public constant WIZARD_MAX_TYPE = 20; uint8 public constant ARCHER_MIN_TYPE = 21; uint8 public constant ARCHER_MAX_TYPE = 26; uint8 public constant NUMBER_OF_LEVELS = 6; uint8 public constant INVALID_CHARACTER_TYPE = 27; /** minimum amount of XPER and SKL to purchase wizards **/ uint8 public MIN_XPER_AMOUNT_TO_PURCHASE_WIZARD = 100; uint8 public MIN_SKL_AMOUNT_TO_PURCHASE_WIZARD = 50; /** minimum amount of XPER and SKL to purchase archer **/ uint8 public MIN_XPER_AMOUNT_TO_PURCHASE_ARCHER = 10; uint8 public MIN_SKL_AMOUNT_TO_PURCHASE_ARCHER = 5; /** knight cooldown. contains the timestamp of the earliest possible moment to start a fight */ mapping(uint32 => uint) public cooldown; /** tells the number of times a character is protected */ mapping(uint32 => uint8) public protection; // EVENTS /** is fired when new characters are purchased (who bought how many characters of which type?) */ event NewPurchase(address player, uint8 characterType, uint16 amount, uint32 startId); /** is fired when a player leaves the game */ event NewExit(address player, uint256 totalBalance, uint32[] removedCharacters); /** is fired when an eruption occurs */ event NewEruption(uint32[] hitCharacters, uint128 value, uint128 gasCost); /** is fired when a single character is sold **/ event NewSell(uint32 characterId, address player, uint256 value); /** is fired when a knight fights a dragon **/ event NewFight(uint32 winnerID, uint32 loserID, uint256 value, uint16 probability, uint16 dice); /** is fired when a knight is teleported to the field **/ event NewTeleport(uint32 characterId); /** is fired when a protection is purchased **/ event NewProtection(uint32 characterId, uint8 lifes); /** is fired when a castle loot distribution occurs**/ event NewDistributionCastleLoot(uint128 castleLoot); /** initializes the contract parameters */ constructor(address tptAddress, address ndcAddress, address sklAddress, address xperAddress, address _configAddress) public { nextId = 1; teleportToken = Token(tptAddress); neverdieToken = Token(ndcAddress); sklToken = Token(sklAddress); xperToken = Token(xperAddress); config = DragonKingConfig(_configAddress); } /** * buys as many characters as possible with the transfered value of the given type * @param characterType the type of the character */ function addCharacters(uint8 characterType) payable public onlyUser { uint16 amount = uint16(msg.value / config.costs(characterType)); uint16 nchars = numCharacters; if (characterType >= INVALID_CHARACTER_TYPE || msg.value < config.costs(characterType) || nchars + amount > config.maxCharacters()) revert(); uint32 nid = nextId; //if type exists, enough ether was transferred and there are less than maxCharacters characters in the game if (characterType <= DRAGON_MAX_TYPE) { //dragons enter the game directly if (oldest == 0 || oldest == noKing) oldest = nid; for (uint8 i = 0; i < amount; i++) { addCharacter(nid + i, nchars + i); characters[nid + i] = Character(characterType, config.values(characterType), msg.sender, uint64(now)); } numCharactersXType[characterType] += amount; numCharacters += amount; } else { uint256 amountSKL = sklToken.balanceOf(msg.sender); uint256 amountXPER = xperToken.balanceOf(msg.sender); if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { require( amountSKL >= MIN_SKL_AMOUNT_TO_PURCHASE_WIZARD && amountXPER >= MIN_XPER_AMOUNT_TO_PURCHASE_WIZARD, "insufficient amount of SKL and XPER tokens" ); } if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { require( amountSKL >= MIN_SKL_AMOUNT_TO_PURCHASE_ARCHER && amountXPER >= MIN_XPER_AMOUNT_TO_PURCHASE_ARCHER, "insufficient amount of SKL and XPER tokens" ); } // to enter game knights, mages, and archers should be teleported later for (uint8 j = 0; j < amount; j++) { characters[nid + j] = Character(characterType, config.values(characterType), msg.sender, uint64(now)); } } nextId = nid + amount; emit NewPurchase(msg.sender, characterType, amount, nid); } /** * adds a single dragon of the given type to the ids array, which is used to iterate over all characters * @param nId the id the character is about to receive * @param nchars the number of characters currently in the game */ function addCharacter(uint32 nId, uint16 nchars) internal { if (nchars < ids.length) ids[nchars] = nId; else ids.push(nId); } /** * leave the game. * pays out the sender's balance and removes him and his characters from the game * */ function exit() public { uint32[] memory removed = new uint32[](50); uint8 count; uint32 lastId; uint playerBalance; uint16 nchars = numCharacters; for (uint16 i = 0; i < nchars; i++) { if (characters[ids[i]].owner == msg.sender && characters[ids[i]].purchaseTimestamp + 1 days < now && (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) { //first delete all characters at the end of the array while (nchars > 0 && characters[ids[nchars - 1]].owner == msg.sender && characters[ids[nchars - 1]].purchaseTimestamp + 1 days < now && (characters[ids[i]].characterType < BALLOON_MIN_TYPE || characters[ids[i]].characterType > BALLOON_MAX_TYPE)) { nchars--; lastId = ids[nchars]; numCharactersXType[characters[lastId].characterType]--; playerBalance += characters[lastId].value; removed[count] = lastId; count++; if (lastId == oldest) oldest = 0; delete characters[lastId]; } //replace the players character by the last one if (nchars > i + 1) { playerBalance += characters[ids[i]].value; removed[count] = ids[i]; count++; nchars--; replaceCharacter(i, nchars); } } } numCharacters = nchars; emit NewExit(msg.sender, playerBalance, removed); //fire the event to notify the client msg.sender.transfer(playerBalance); if (oldest == 0) findOldest(); } /** * Replaces the character with the given id with the last character in the array * @param index the index of the character in the id array * @param nchars the number of characters * */ function replaceCharacter(uint16 index, uint16 nchars) internal { uint32 characterId = ids[index]; numCharactersXType[characters[characterId].characterType]--; if (characterId == oldest) oldest = 0; delete characters[characterId]; ids[index] = ids[nchars]; delete ids[nchars]; } /** * The volcano eruption can be triggered by anybody but only if enough time has passed since the last eription. * The volcano hits up to a certain percentage of characters, but at least one. * The percantage is specified in 'percentageToKill' * */ function triggerVolcanoEruption() public onlyUser { require(now >= lastEruptionTimestamp + config.eruptionThreshold(), "not enough time passed since last eruption"); require(numCharacters > 0, "there are no characters in the game"); lastEruptionTimestamp = now; uint128 pot; uint128 value; uint16 random; uint32 nextHitId; uint16 nchars = numCharacters; uint32 howmany = nchars * config.percentageToKill() / 100; uint128 neededGas = 80000 + 10000 * uint32(nchars); if(howmany == 0) howmany = 1;//hit at least 1 uint32[] memory hitCharacters = new uint32[](howmany); bool[] memory alreadyHit = new bool[](nextId); uint8 i = 0; uint16 j = 0; while (i < howmany) { j++; random = uint16(generateRandomNumber(lastEruptionTimestamp + j) % nchars); nextHitId = ids[random]; if (!alreadyHit[nextHitId]) { alreadyHit[nextHitId] = true; hitCharacters[i] = nextHitId; value = hitCharacter(random, nchars, 0); if (value > 0) { nchars--; } pot += value; i++; } } uint128 gasCost = uint128(neededGas * tx.gasprice); numCharacters = nchars; if (pot > gasCost){ distribute(pot - gasCost); //distribute the pot minus the oraclize gas costs emit NewEruption(hitCharacters, pot - gasCost, gasCost); } else emit NewEruption(hitCharacters, 0, gasCost); } /** * Knight can attack a dragon. * Archer can attack only a balloon. * Dragon can attack wizards and archers. * Wizard can attack anyone, except balloon. * Balloon cannot attack. * The value of the loser is transfered to the winner. * @param characterID the ID of the knight to perfrom the attack * @param characterIndex the index of the knight in the ids-array. Just needed to save gas costs. * In case it's unknown or incorrect, the index is looked up in the array. * */ function fight(uint32 characterID, uint16 characterIndex) public onlyUser { if (characterID != ids[characterIndex]) characterIndex = getCharacterIndex(characterID); Character storage character = characters[characterID]; require(cooldown[characterID] + config.CooldownThreshold() <= now, "not enough time passed since the last fight of this character"); require(character.owner == msg.sender, "only owner can initiate a fight for this character"); uint8 ctype = character.characterType; require(ctype < BALLOON_MIN_TYPE || ctype > BALLOON_MAX_TYPE, "balloons cannot fight"); uint16 adversaryIndex = getRandomAdversary(characterID, ctype); assert(adversaryIndex != INVALID_CHARACTER_INDEX); uint32 adversaryID = ids[adversaryIndex]; Character storage adversary = characters[adversaryID]; uint128 value; uint16 base_probability; uint16 dice = uint16(generateRandomNumber(characterID) % 100); uint256 characterPower = sklToken.balanceOf(character.owner) / 10**15 + xperToken.balanceOf(character.owner); uint256 adversaryPower = sklToken.balanceOf(adversary.owner) / 10**15 + xperToken.balanceOf(adversary.owner); if (character.value == adversary.value) { base_probability = 50; if (characterPower > adversaryPower) { base_probability += uint16(100 / config.fightFactor()); } else if (adversaryPower > characterPower) { base_probability -= uint16(100 / config.fightFactor()); } } else if (character.value > adversary.value) { base_probability = 100; if (adversaryPower > characterPower) { base_probability -= uint16((100 * adversary.value) / character.value / config.fightFactor()); } } else if (characterPower > adversaryPower) { base_probability += uint16((100 * character.value) / adversary.value / config.fightFactor()); } if (dice >= base_probability) { // adversary won if (adversary.characterType < BALLOON_MIN_TYPE || adversary.characterType > BALLOON_MAX_TYPE) { value = hitCharacter(characterIndex, numCharacters, adversary.characterType); if (value > 0) { numCharacters--; } if (adversary.characterType >= ARCHER_MIN_TYPE && adversary.characterType <= ARCHER_MAX_TYPE) { castleTreasury += value; } else { adversary.value += value; } emit NewFight(adversaryID, characterID, value, base_probability, dice); } else { emit NewFight(adversaryID, characterID, 0, base_probability, dice); // balloons do not hit back } } else { // character won value = hitCharacter(adversaryIndex, numCharacters, character.characterType); if (value > 0) { numCharacters--; } if (character.characterType >= ARCHER_MIN_TYPE && character.characterType <= ARCHER_MAX_TYPE) { castleTreasury += value; } else { character.value += value; } if (oldest == 0) findOldest(); emit NewFight(characterID, adversaryID, value, base_probability, dice); } cooldown[characterID] = now; } /* * @param characterType * @param adversaryType * @return whether adversaryType is a valid type of adversary for a given character */ function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) { if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight return (adversaryType <= DRAGON_MAX_TYPE); } else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE); } else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon return (adversaryType >= WIZARD_MIN_TYPE); } else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE) || (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE)); } return false; } /** * pick a random adversary. * @param nonce a nonce to make sure there's not always the same adversary chosen in a single block. * @return the index of a random adversary character * */ function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) { uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters); // use 7, 11 or 13 as step size. scales for up to 1000 characters uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7; uint16 i = randomIndex; //if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number) //will at some point return to the startingPoint if no character is suited do { if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) { return i; } i = (i + stepSize) % numCharacters; } while (i != randomIndex); return INVALID_CHARACTER_INDEX; } /** * generate a random number. * @param nonce a nonce to make sure there's not always the same number returned in a single block. * @return the random number * */ function generateRandomNumber(uint256 nonce) internal view returns(uint) { return uint(keccak256(block.blockhash(block.number - 1), now, numCharacters, nonce)); } /** * Hits the character of the given type at the given index. * Wizards can knock off two protections. Other characters can do only one. * @param index the index of the character * @param nchars the number of characters * @return the value gained from hitting the characters (zero is the character was protected) * */ function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) { uint32 id = ids[index]; uint8 knockOffProtections = 1; if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { knockOffProtections = 2; } if (protection[id] >= knockOffProtections) { protection[id] = protection[id] - knockOffProtections; return 0; } characterValue = characters[ids[index]].value; nchars--; replaceCharacter(index, nchars); } /** * finds the oldest character * */ function findOldest() public { uint32 newOldest = noKing; for (uint16 i = 0; i < numCharacters; i++) { if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE) newOldest = ids[i]; } oldest = newOldest; } /** * distributes the given amount among the surviving characters * @param totalAmount nthe amount to distribute */ function distribute(uint128 totalAmount) internal { uint128 amount; if (oldest == 0) findOldest(); if (oldest != noKing) { //pay 10% to the oldest dragon characters[oldest].value += totalAmount / 10; amount = totalAmount / 10 * 9; } else { amount = totalAmount; } //distribute the rest according to their type uint128 valueSum; uint8 size = ARCHER_MAX_TYPE; uint128[] memory shares = new uint128[](size); for (uint8 v = 0; v < size; v++) { if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[v] > 0) { valueSum += config.values(v); } } for (uint8 m = 0; m < size; m++) { if ((v < BALLOON_MIN_TYPE || v > BALLOON_MAX_TYPE) && numCharactersXType[m] > 0) { shares[m] = amount * config.values(m) / valueSum / numCharactersXType[m]; } } uint8 cType; for (uint16 i = 0; i < numCharacters; i++) { cType = characters[ids[i]].characterType; if (cType < BALLOON_MIN_TYPE || cType > BALLOON_MAX_TYPE) characters[ids[i]].value += shares[characters[ids[i]].characterType]; } } /** * allows the owner to collect the accumulated fees * sends the given amount to the owner's address if the amount does not exceed the * fees (cannot touch the players' balances) minus 100 finney (ensure that oraclize fees can be paid) * @param amount the amount to be collected * */ function collectFees(uint128 amount) public onlyOwner { uint collectedFees = getFees(); if (amount + 100 finney < collectedFees) { owner.transfer(amount); } } /** * withdraw NDC and TPT tokens */ function withdraw() public onlyOwner { uint256 ndcBalance = neverdieToken.balanceOf(this); assert(neverdieToken.transfer(owner, ndcBalance)); uint256 tptBalance = teleportToken.balanceOf(this); assert(teleportToken.transfer(owner, tptBalance)); } /** * pays out the players. * */ function payOut() public onlyOwner { for (uint16 i = 0; i < numCharacters; i++) { characters[ids[i]].owner.transfer(characters[ids[i]].value); delete characters[ids[i]]; } delete ids; numCharacters = 0; } /** * pays out the players and kills the game. * */ function stop() public onlyOwner { withdraw(); payOut(); destroy(); } /* @dev distributes castle loot among archers */ function distributeCastleLoot() external onlyUser { require(now >= lastCastleLootDistributionTimestamp + config.castleLootDistributionThreshold(), "not enough time passed since the last castle loot distribution"); lastCastleLootDistributionTimestamp = now; uint128 luckFactor = uint128(generateRandomNumber(now) % 51); if (luckFactor < 5) { luckFactor = 5; } uint128 amount = castleTreasury * luckFactor / 100; uint128 valueSum; uint128[] memory shares = new uint128[](NUMBER_OF_LEVELS); uint16 archersCount; uint32[] memory archers = new uint32[](numCharacters); uint8 cType; for (uint8 i = 0; i < ids.length; i++) { cType = characters[ids[i]].characterType; if ((cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE) && (((uint64(now) - characters[ids[i]].purchaseTimestamp) / config.eruptionThreshold()) >= 7)) { valueSum += config.values(cType); archers[archersCount] = ids[i]; archersCount++; } } if (valueSum > 0) { for (uint8 j = 0; j < NUMBER_OF_LEVELS; j++) { shares[j] = amount * config.values(ARCHER_MIN_TYPE + j) / valueSum; } for (uint16 k = 0; k < archersCount; k++) { characters[archers[k]].value += shares[characters[archers[k]].characterType - ARCHER_MIN_TYPE]; } castleTreasury -= amount; emit NewDistributionCastleLoot(amount); } else { emit NewDistributionCastleLoot(0); } } /** * sell the character of the given id * throws an exception in case of a knight not yet teleported to the game * @param characterId the id of the character * */ function sellCharacter(uint32 characterId) public onlyUser { require(msg.sender == characters[characterId].owner, "only owners can sell their characters"); require(characters[characterId].characterType < BALLOON_MIN_TYPE || characters[characterId].characterType > BALLOON_MAX_TYPE, "balloons are not sellable"); require(characters[characterId].purchaseTimestamp + 1 days < now, "character can be sold only 1 day after the purchase"); uint128 val = characters[characterId].value; numCharacters--; replaceCharacter(getCharacterIndex(characterId), numCharacters); msg.sender.transfer(val); if (oldest == 0) findOldest(); emit NewSell(characterId, msg.sender, val); } /** * receive approval to spend some tokens. * used for teleport and protection. * @param sender the sender address * @param value the transferred value * @param tokenContract the address of the token contract * @param callData the data passed by the token contract * */ function receiveApproval(address sender, uint256 value, address tokenContract, bytes callData) public { uint32 id; uint256 price; if (msg.sender == address(teleportToken)) { id = toUint32(callData); price = config.teleportPrice(); if (characters[id].characterType >= BALLOON_MIN_TYPE && characters[id].characterType <= WIZARD_MAX_TYPE) { price *= 2; } require(value >= price, "insufficinet amount of tokens to teleport this character"); assert(teleportToken.transferFrom(sender, this, price)); teleportCharacter(id); } else if (msg.sender == address(neverdieToken)) { id = toUint32(callData); // user can purchase extra lifes only right after character purchaes // in other words, user value should be equal the initial value uint8 cType = characters[id].characterType; require(characters[id].value == config.values(cType), "protection could be bought only before the first fight and before the first volcano eruption"); // calc how many lifes user can actually buy // the formula is the following: uint256 lifePrice; uint8 max; if(cType <= KNIGHT_MAX_TYPE || (cType >= ARCHER_MIN_TYPE && cType <= ARCHER_MAX_TYPE)){ lifePrice = ((cType % NUMBER_OF_LEVELS) + 1) * config.protectionPrice(); max = 3; } else if (cType >= BALLOON_MIN_TYPE && cType <= BALLOON_MAX_TYPE) { lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2; max = 6; } else if (cType >= WIZARD_MIN_TYPE && cType <= WIZARD_MAX_TYPE) { lifePrice = (((cType+3) % NUMBER_OF_LEVELS) + 1) * config.protectionPrice() * 2; max = 3; } price = 0; uint8 i = protection[id]; for (i; i < max && value >= price + lifePrice * (i + 1); i++) { price += lifePrice * (i + 1); } assert(neverdieToken.transferFrom(sender, this, price)); protectCharacter(id, i); } else { revert("Should be either from Neverdie or Teleport tokens"); } } /** * Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene * @param id the character id * */ function teleportCharacter(uint32 id) internal { // ensure we do not teleport twice require(teleported[id] == false, "already teleported"); teleported[id] = true; Character storage character = characters[id]; require(character.characterType > DRAGON_MAX_TYPE, "dragons do not need to be teleported"); //this also makes calls with non-existent ids fail addCharacter(id, numCharacters); numCharacters++; numCharactersXType[character.characterType]++; emit NewTeleport(id); } /** * adds protection to a character * @param id the character id * @param lifes the number of protections * */ function protectCharacter(uint32 id, uint8 lifes) internal { protection[id] = lifes; emit NewProtection(id, lifes); } /****************** GETTERS *************************/ /** * returns the character of the given id * @param characterId the character id * @return the type, value and owner of the character * */ function getCharacter(uint32 characterId) public view returns(uint8, uint128, address) { return (characters[characterId].characterType, characters[characterId].value, characters[characterId].owner); } /** * returns the index of a character of the given id * @param characterId the character id * @return the character id * */ function getCharacterIndex(uint32 characterId) constant public returns(uint16) { for (uint16 i = 0; i < ids.length; i++) { if (ids[i] == characterId) { return i; } } revert(); } /** * returns 10 characters starting from a certain indey * @param startIndex the index to start from * @return 4 arrays containing the ids, types, values and owners of the characters * */ function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) { uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10; uint8 j = 0; uint32 id; for (uint16 i = startIndex; i < endIndex; i++) { id = ids[i]; characterIds[j] = id; types[j] = characters[id].characterType; values[j] = characters[id].value; owners[j] = characters[id].owner; j++; } } /** * returns the number of dragons in the game * @return the number of dragons * */ function getNumDragons() constant public returns(uint16 numDragons) { for (uint8 i = DRAGON_MIN_TYPE; i <= DRAGON_MAX_TYPE; i++) numDragons += numCharactersXType[i]; } /** * returns the number of wizards in the game * @return the number of wizards * */ function getNumWizards() constant public returns(uint16 numWizards) { for (uint8 i = WIZARD_MIN_TYPE; i <= WIZARD_MAX_TYPE; i++) numWizards += numCharactersXType[i]; } /** * returns the number of archers in the game * @return the number of archers * */ function getNumArchers() constant public returns(uint16 numArchers) { for (uint8 i = ARCHER_MIN_TYPE; i <= ARCHER_MAX_TYPE; i++) numArchers += numCharactersXType[i]; } /** * returns the number of knights in the game * @return the number of knights * */ function getNumKnights() constant public returns(uint16 numKnights) { for (uint8 i = KNIGHT_MIN_TYPE; i <= KNIGHT_MAX_TYPE; i++) numKnights += numCharactersXType[i]; } /** * @return the accumulated fees * */ function getFees() constant public returns(uint) { uint reserved = 0; for (uint16 j = 0; j < numCharacters; j++) reserved += characters[ids[j]].value; return address(this).balance - reserved; } /************* HELPERS ****************/ /** * only works for bytes of length < 32 * @param b the byte input * @return the uint * */ function toUint32(bytes b) internal pure returns(uint32) { bytes32 newB; assembly { newB: = mload(0xa0) } return uint32(newB); } }
* timestampt of the last eruption event **/
uint256 public lastEruptionTimestamp;
1,757,997
[ 1, 8584, 395, 301, 337, 434, 326, 1142, 6445, 89, 375, 871, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 5034, 1071, 1142, 41, 21421, 4921, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/token/ERC721/ERC721.sol"; contract CryptoStar is ERC721, Ownable { // https://ethereum.meta.stackexchange.com/questions/443/blog-simple-storage-patterns-in-solidity // Using struct mapping with internal bool indicating Star is valid struct Star { string name; bool isStar; } // Name and symbol of CryptoStar token string public constant name = "CryptoStar"; string public constant symbol = "CST"; // Mapping of Star tokenIds and Star data mapping(uint256 => Star) public tokenIdToStarInfo; // Mapping of Stars for sale (tokenId) and price mapping(uint256 => uint256) public starsForSale; // Way to check if the star data exists and is valid function isStar(uint256 _tokenId) public view returns(bool isIndeed) { return tokenIdToStarInfo[_tokenId].isStar; } // Claim a star function claimStar(string _name, uint256 _tokenId) public { require(!isStar(_tokenId), "Star tokenId already exists"); tokenIdToStarInfo[_tokenId].name = _name; tokenIdToStarInfo[_tokenId].isStar = true; _mint(msg.sender, _tokenId); } // Find a star function lookUptokenIdToStarInfo(uint256 _tokenId) public view returns (string, address) { require(isStar(_tokenId), "not a valid Star tokenId"); return (tokenIdToStarInfo[_tokenId].name, ownerOf(_tokenId)); } // List a star for sale function putStarUpForSale(uint256 _tokenId, uint256 _price) public { require(ownerOf(_tokenId) == msg.sender, "only owner is allowed to put a Star up for sale"); starsForSale[_tokenId] = _price; } // Buy a star function buyStar(uint256 _tokenId) public payable { require(starsForSale[_tokenId] > 0, "Star tokenId is not for sale"); uint256 starCost = starsForSale[_tokenId]; address starOwner = ownerOf(_tokenId); require(msg.value >= starCost, "not enough Wei to buy Star"); _removeTokenFrom(starOwner, _tokenId); _addTokenTo(msg.sender, _tokenId); starOwner.transfer(starCost); if(msg.value > starCost) { msg.sender.transfer(msg.value - starCost); } starsForSale[_tokenId] = 0; } // Exchange Stars between two different accounts function exchangeStars(uint256 _tokenFrom, uint256 _tokenTo) public payable { require(isStar(_tokenFrom), "not a valid Star 'from' tokenId"); require(isStar(_tokenTo), "not a valid Star 'to' tokenId"); require(ownerOf(_tokenFrom) == msg.sender, "only an owner can initiate a Star transfer"); address to = ownerOf(_tokenTo); require(ownerOf(_tokenTo) == to, "Star 'to' address is not owner of tokenId"); require(ownerOf(_tokenFrom) != ownerOf(_tokenTo), "can't exchange Stars with the same owner"); _removeTokenFrom(msg.sender, _tokenFrom); _addTokenTo(to, _tokenFrom); _removeTokenFrom(to, _tokenTo); _addTokenTo(msg.sender, _tokenTo); } // Owner transfers ownership of a Star to another account function transferStar(address to, uint256 _tokenId) public payable returns(address) { require(isStar(_tokenId), "not a valid Star tokenId"); require(ownerOf(_tokenId) == msg.sender, "only owner is allowed to transfer a Star"); _removeTokenFrom(msg.sender, _tokenId); _addTokenTo(to, _tokenId); return (to); } // https://ethereum.stackexchange.com/questions/11758/converting-oraclize-result-from-string-to-address?rq=1 // Adapted, by Miguel Mota // // Parses a string address and returns an address type function parseAddress(bytes _address) public pure returns (address) { uint160 m = 0; uint160 b = 0; for (uint8 i = 0; i < 20; i++) { m *= 256; b = uint160(_address[i]); m += (b); } return address(m); } // Expire or kill the CryptoStar contract function expire() public onlyOwner { // destroys the contract and returns tokens to Contract owner selfdestruct(msg.sender); } }
https:ethereum.stackexchange.com/questions/11758/converting-oraclize-result-from-string-to-address?rq=1 Adapted, by Miguel Mota Parses a string address and returns an address type
function parseAddress(bytes _address) public pure returns (address) { uint160 m = 0; uint160 b = 0; for (uint8 i = 0; i < 20; i++) { m *= 256; b = uint160(_address[i]); m += (b); } return address(m); }
12,613,078
[ 1, 4528, 30, 546, 822, 379, 18, 3772, 16641, 18, 832, 19, 9758, 19, 2499, 5877, 28, 19, 6283, 310, 17, 280, 10150, 554, 17, 2088, 17, 2080, 17, 1080, 17, 869, 17, 2867, 35, 86, 85, 33, 21, 22792, 329, 16, 635, 490, 8810, 292, 490, 25441, 2280, 2420, 279, 533, 1758, 471, 1135, 392, 1758, 618, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1109, 1887, 12, 3890, 389, 2867, 13, 1071, 16618, 1135, 261, 2867, 13, 288, 203, 3639, 2254, 16874, 312, 273, 374, 31, 203, 3639, 2254, 16874, 324, 273, 374, 31, 203, 203, 3639, 364, 261, 11890, 28, 277, 273, 374, 31, 277, 411, 4200, 31, 277, 27245, 288, 203, 5411, 312, 6413, 8303, 31, 203, 5411, 324, 273, 2254, 16874, 24899, 2867, 63, 77, 19226, 203, 5411, 312, 1011, 261, 70, 1769, 203, 3639, 289, 203, 203, 3639, 327, 1758, 12, 81, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x999512dC124371E6B9ff43CE8D1AF83252F0C851/sources/src/BaseVault.sol
* @notice Redeems a queued withdrawal for `recipient`. The user can redeem the tokens after the rebalance. This can be easily check by comparing the current round with the round of the withdrawal, if they're equal, the withdrawal is still pending. @param recipient The address that will receive the withdrawn tokens after the rebalance. @return amountX The amount of token X to be withdrawn. @return amountY The amount of token Y to be withdrawn./ Get the amounts to be redeemed. Transfer the tokens to the recipient.
function redeemQueuedWithdrawal(uint256 round, address recipient) public virtual override nonReentrant onlyValidRecipient(recipient) returns (uint256 amountX, uint256 amountY) { (amountX, amountY) = _redeemWithdrawal(round, recipient); if (amountX > 0) _tokenX().safeTransfer(recipient, amountX); if (amountY > 0) _tokenY().safeTransfer(recipient, amountY); }
1,894,049
[ 1, 426, 323, 7424, 279, 12234, 598, 9446, 287, 364, 1375, 20367, 8338, 1021, 729, 848, 283, 24903, 326, 2430, 1839, 326, 283, 12296, 18, 1220, 848, 506, 17997, 866, 635, 17553, 326, 783, 3643, 598, 326, 3643, 434, 326, 598, 9446, 287, 16, 309, 2898, 4565, 3959, 16, 326, 598, 9446, 287, 353, 4859, 4634, 18, 225, 8027, 1021, 1758, 716, 903, 6798, 326, 598, 9446, 82, 2430, 1839, 326, 283, 12296, 18, 327, 3844, 60, 1021, 3844, 434, 1147, 1139, 358, 506, 598, 9446, 82, 18, 327, 3844, 61, 1021, 3844, 434, 1147, 1624, 358, 506, 598, 9446, 82, 18, 19, 968, 326, 30980, 358, 506, 283, 24903, 329, 18, 12279, 326, 2430, 358, 326, 8027, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 283, 24903, 21039, 1190, 9446, 287, 12, 11890, 5034, 3643, 16, 1758, 8027, 13, 203, 3639, 1071, 203, 3639, 5024, 203, 3639, 3849, 203, 3639, 1661, 426, 8230, 970, 203, 3639, 1338, 1556, 18241, 12, 20367, 13, 203, 3639, 1135, 261, 11890, 5034, 3844, 60, 16, 2254, 5034, 3844, 61, 13, 203, 565, 288, 203, 3639, 261, 8949, 60, 16, 3844, 61, 13, 273, 389, 266, 24903, 1190, 9446, 287, 12, 2260, 16, 8027, 1769, 203, 203, 3639, 309, 261, 8949, 60, 405, 374, 13, 389, 2316, 60, 7675, 4626, 5912, 12, 20367, 16, 3844, 60, 1769, 203, 3639, 309, 261, 8949, 61, 405, 374, 13, 389, 2316, 61, 7675, 4626, 5912, 12, 20367, 16, 3844, 61, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0xd4980e33357F7B971e4a28EAB83B63Dd42985248/sources/Fortuna.sol
Kullanıcı geçen TC bloğun üçüncüsü anlamına geliyor.üçüncü yüzde 10 alır!
function getTCrewardsBack() public { require(msg.sender == tcdetailz[dailyOLDMix(0)]._address || msg.sender == tcdetailz[dailyOLDMix(1)]._address || msg.sender == tcdetailz[dailyOLDMix(2)]._address); uint256 _bnum = (block.number - genesisBlock)/BlockSizeForTC; uint256 onepercentofamount = totalRewardforTC[_bnum -1] / 100; if(msg.sender == tcdetailz[dailyOLDMix(0)]._address) { require(tcdetailz[dailyOLDMix(0)]._paid == false); uint usershare = onepercentofamount*60; tcdetailz[dailyOLDMix(0)] = TradCompdetails(msg.sender, 0, true); _cleantransfer(address(this), msg.sender, usershare); require(tcdetailz[dailyOLDMix(1)]._paid == false); uint usershare = onepercentofamount*30; tcdetailz[dailyOLDMix(1)] = TradCompdetails(msg.sender, 0, true); _cleantransfer(address(this), msg.sender, usershare); require(tcdetailz[dailyOLDMix(2)]._paid == false); uint usershare = onepercentofamount*10; tcdetailz[dailyOLDMix(2)] = TradCompdetails(msg.sender, 0, true); _cleantransfer(address(this), msg.sender, usershare); } }
3,353,823
[ 1, 47, 29336, 133, 114, 71, 133, 114, 8244, 132, 105, 275, 23718, 324, 383, 133, 258, 318, 225, 132, 125, 132, 105, 132, 125, 14202, 132, 125, 87, 132, 125, 392, 28448, 133, 114, 6582, 314, 292, 77, 93, 280, 18, 132, 125, 132, 105, 132, 125, 14202, 132, 125, 677, 132, 125, 94, 323, 1728, 524, 133, 114, 86, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 377, 445, 3181, 1996, 6397, 2711, 1435, 1071, 288, 203, 540, 2583, 12, 3576, 18, 15330, 422, 1715, 8992, 94, 63, 26790, 11846, 21294, 12, 20, 25887, 6315, 2867, 747, 1234, 18, 15330, 422, 1715, 8992, 94, 63, 26790, 11846, 21294, 12, 21, 25887, 6315, 2867, 747, 1234, 18, 15330, 422, 1715, 8992, 94, 63, 26790, 11846, 21294, 12, 22, 25887, 6315, 2867, 1769, 203, 203, 540, 2254, 5034, 389, 70, 2107, 273, 261, 2629, 18, 2696, 300, 21906, 1768, 13176, 22506, 1290, 15988, 31, 203, 1850, 2254, 5034, 1245, 8849, 792, 8949, 273, 2078, 17631, 1060, 1884, 15988, 63, 67, 70, 2107, 300, 21, 65, 342, 2130, 31, 203, 540, 309, 12, 3576, 18, 15330, 422, 1715, 8992, 94, 63, 26790, 11846, 21294, 12, 20, 25887, 6315, 2867, 13, 288, 203, 5411, 2583, 12, 12444, 1641, 94, 63, 26790, 11846, 21294, 12, 20, 25887, 6315, 29434, 422, 629, 1769, 203, 5411, 2254, 3677, 76, 834, 273, 1245, 8849, 792, 8949, 14, 4848, 31, 203, 5411, 1715, 8992, 94, 63, 26790, 11846, 21294, 12, 20, 25887, 225, 273, 2197, 72, 2945, 6395, 12, 3576, 18, 15330, 16, 374, 16, 638, 1769, 203, 5411, 389, 6200, 13866, 12, 2867, 12, 2211, 3631, 1234, 18, 15330, 16, 3677, 76, 834, 1769, 203, 2398, 2583, 12, 12444, 1641, 94, 63, 26790, 11846, 21294, 12, 21, 25887, 6315, 29434, 422, 629, 1769, 203, 5411, 2254, 3677, 76, 834, 273, 1245, 8849, 792, 8949, 14, 5082, 31, 203, 5411, 1715, 8992, 94, 63, 26790, 11846, 21294, 12, 21, 25887, 2 ]
pragma solidity 0.5.16; interface IERC20 { function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function transfer(address recipient, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function transferFrom(address sender, address recipient, uint amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Context { constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping (address => uint) private _balances; mapping (address => mapping (address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns (uint) { return _totalSupply; } function balanceOf(address account) public view returns (uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal { } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; uint256 private _cap; constructor (string memory name, string memory symbol, uint8 decimals, uint256 cap) public { _name = name; _symbol = symbol; _decimals = decimals; _cap = cap; } 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; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view returns (uint256) { return _cap; } } library SafeMath { function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns (uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function isContract(address account) internal view returns (bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { 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"); } } } /** * HD Token */ contract HD is ERC20, ERC20Detailed { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; address public governance; address public pendingGov; mapping (address => bool) public minters; event NewPendingGov(address oldPendingGov, address newPendingGov); event NewGov(address oldGov, address newGov); // Modifiers modifier onlyGov() { require(msg.sender == governance, "HUB-Token: !governance"); _; } constructor () public ERC20Detailed("HUB.finance", "HD", 18, 21000000 * 10 ** 18) { governance = tx.origin; } /** * Minte Token for Account * @param _account minter * @param _amount amount */ function mint(address _account, uint256 _amount) public { require(minters[msg.sender], "HUB-Token: !minter"); _mint(_account, _amount); } /** * Add minter * @param _minter minter */ function addMinter(address _minter) public onlyGov { minters[_minter] = true; } /** * Remove minter * @param _minter minter */ function removeMinter(address _minter) public onlyGov { minters[_minter] = false; } /** * Set new governance * @param _pendingGov the new governance */ function setPendingGov(address _pendingGov) external onlyGov { address oldPendingGov = pendingGov; pendingGov = _pendingGov; emit NewPendingGov(oldPendingGov, _pendingGov); } /** * lets msg.sender accept governance */ function acceptGov() external { require(msg.sender == pendingGov, "HUB-Token: !pending"); address oldGov = governance; governance = pendingGov; pendingGov = address(0); emit NewGov(oldGov, governance); } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - minted tokens must not cause the total supply to go over the cap. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal { super._beforeTokenTransfer(from, to, amount); if (from == address(0)) { // When minting tokens require(totalSupply().add(amount) <= cap(), "HUB-Token: Cap exceeded"); } } }
* lets msg.sender accept governance/
function acceptGov() external { require(msg.sender == pendingGov, "HUB-Token: !pending"); address oldGov = governance; governance = pendingGov; pendingGov = address(0); emit NewGov(oldGov, governance); }
2,440,629
[ 1, 17307, 1234, 18, 15330, 2791, 314, 1643, 82, 1359, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2791, 43, 1527, 1435, 203, 3639, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 4634, 43, 1527, 16, 315, 44, 3457, 17, 1345, 30, 401, 9561, 8863, 203, 3639, 1758, 1592, 43, 1527, 273, 314, 1643, 82, 1359, 31, 203, 3639, 314, 1643, 82, 1359, 273, 4634, 43, 1527, 31, 203, 3639, 4634, 43, 1527, 273, 1758, 12, 20, 1769, 203, 3639, 3626, 1166, 43, 1527, 12, 1673, 43, 1527, 16, 314, 1643, 82, 1359, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xACD8f27EAF5B160d460b60E4f45F9FFafb70516a/sources/project_/contracts/Implementation/SimpleAccount.sol
* change entry-point: an account must have a method for replacing the entryPoint, in case the the entryPoint is upgraded to a newer version./
function initialize(IEntryPoint anEntryPoint) external initializer { require( isBase == false, "SimpleAccount: this is the base contract, cannot be initialized" ); _entryPoint = anEntryPoint; }
1,868,359
[ 1, 3427, 1241, 17, 1153, 30, 392, 2236, 1297, 1240, 279, 707, 364, 13993, 326, 28671, 16, 316, 648, 326, 326, 28671, 353, 31049, 358, 279, 16069, 1177, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4046, 12, 45, 1622, 2148, 392, 1622, 2148, 13, 3903, 12562, 288, 203, 3639, 2583, 12, 203, 5411, 353, 2171, 422, 629, 16, 203, 5411, 315, 5784, 3032, 30, 333, 353, 326, 1026, 6835, 16, 2780, 506, 6454, 6, 203, 3639, 11272, 203, 3639, 389, 4099, 2148, 273, 392, 1622, 2148, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43114/0x096F07be24Fb85528bf67f2790a3B72F764D4540/sources/artifacts/MasterChef.sol
We do some fancy math here. Basically, any point in time, the amount of npt entitled to a user but is pending to be distributed is: pending reward = (user.amount * pool.accNptPerShare) - user.rewardDebt Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: 1. The pool's `accNptPerShare` (and `lastRewardBlock`) gets updated. 2. User receives the pending reward sent to his/her address. 3. User's `amount` gets updated. 4. User's `rewardDebt` gets updated.
struct UserInfo { }
4,572,179
[ 1, 3218, 741, 2690, 31701, 4233, 2674, 18, 7651, 1230, 16, 1281, 1634, 316, 813, 16, 326, 3844, 434, 290, 337, 3281, 305, 1259, 358, 279, 729, 1496, 353, 4634, 358, 506, 16859, 353, 30, 282, 4634, 19890, 273, 261, 1355, 18, 8949, 225, 2845, 18, 8981, 50, 337, 2173, 9535, 13, 300, 729, 18, 266, 2913, 758, 23602, 3497, 4009, 502, 279, 729, 443, 917, 1282, 578, 598, 9446, 87, 511, 52, 2430, 358, 279, 2845, 18, 13743, 1807, 4121, 10555, 30, 282, 404, 18, 1021, 2845, 1807, 1375, 8981, 50, 337, 2173, 9535, 68, 261, 464, 1375, 2722, 17631, 1060, 1768, 24065, 5571, 3526, 18, 282, 576, 18, 2177, 17024, 326, 4634, 19890, 3271, 358, 18423, 19, 1614, 1758, 18, 282, 890, 18, 2177, 1807, 1375, 8949, 68, 5571, 3526, 18, 282, 1059, 18, 2177, 1807, 1375, 266, 2913, 758, 23602, 68, 5571, 3526, 18, 2, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0 ]
[ 1, 565, 1958, 25003, 288, 203, 377, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//***********************************ETH BANK // // It's an EthBank, every depositor earns interest on their deposits when a new depositor joins! // // The interest rate is defined by the "Interest_Rate" variable, and is initially set to 2%, and may be changed later! // // The Bank will exist for long because it only pays out when the balance is above 60%. And if the balance is below 80% it pays out only half the interest. // // Minimum Deposit: 0.2 Ether (200 Finney) // // // It is a long term project, so have fun saving your Ether here! // //***********************************START contract EthBank { struct InvestorArray { address etherAddress; uint amount; } InvestorArray[] public depositors; //********************************************PUBLIC VARIABLES uint public Total_Savers=0; uint public Fees=0; uint public Balance = 0; uint public Total_Deposited=0; uint public Total_Paid_Out=0; uint public Interest_Rate=2; // the interest rate payout for deposits! string public Message="Welcome to EthBank"; address public owner; // simple single-sig function modifier modifier onlyowner { if (msg.sender == owner) _ } //********************************************INIT function EthBank() { owner = 0xEe462A6717f17C57C826F1ad9b4d3813495296C9; //this contract is an attachment to EthVentures } //********************************************TRIGGER function() { enter(); } //********************************************ENTER function enter() { if (msg.value > 200 finney) { uint amount=msg.value; // add a new participant to the system and calculate total players Total_Savers=depositors.length+1; depositors.length += 1; depositors[depositors.length-1].etherAddress = msg.sender; depositors[depositors.length-1].amount = amount; // collect Fees and update contract Balance and deposited amount Fees = amount * Interest_Rate / 100; // fee to the owner Total_Deposited+=amount; //update deposited amount amount-=amount * Interest_Rate / 100; // minus the fee from amount Balance += amount; // Balance update //********************************EthVenturesFinal Fee Plugin // payout Fees to the owner if (Fees != 0) { uint minimal= 1990 finney; if(Fees<minimal) { owner.send(Fees); //send fee to owner Total_Paid_Out+=Fees; //update paid out amount } else { uint Times= Fees/minimal; for(uint i=0; i<Times;i++) // send the Fees out in packets compatible to EthVentures dividend function if(Fees>0) { owner.send(minimal); //send fee to owner Total_Paid_Out+=Fees; //update paid out amount Fees-=minimal; } } } //********************************End Plugin //loop variables uint payout; uint nr=0; if(Total_Deposited * 80/100 < Balance ) //if balance is at 80% or higher, then pay depositors { while (Balance > depositors[nr].amount * Interest_Rate/100 && nr<depositors.length) //exit condition to avoid infinite loop { payout = depositors[nr].amount *Interest_Rate/100; //calculate pay out depositors[nr].etherAddress.send(payout); //send pay out to participant Balance -= depositors[nr].amount *Interest_Rate/100; //Balance update Total_Paid_Out += depositors[nr].amount *Interest_Rate/100; //update paid out amount nr += 1; //go to next participant } Message="The Full Interest has been paid to Depositors!"; } else { if(Total_Deposited * 60/100 < Balance ) //if balance is at 60% or higher, then pay depositors with half interest { while (Balance > depositors[nr].amount * Interest_Rate/200 && nr<depositors.length) //exit condition to avoid infinite loop { payout = depositors[nr].amount *Interest_Rate/200; //calculate pay out depositors[nr].etherAddress.send(payout); //send pay out to participant Balance -= depositors[nr].amount *Interest_Rate/200; //Balance update Total_Paid_Out += depositors[nr].amount *Interest_Rate/200; //update paid out amount nr += 1; //go to next participant } Message="Funds are between 60% and 80%, so only Half Interest has been paid!"; } else Message="Funds are below 60%, no interest payout until new Depositors join!"; } } //********************************************SET INTEREST RATE } function Set_Interest_Rate(uint new_interest) onlyowner //set new interest rate { Interest_Rate = new_interest; Message="The Bank has changed it's Interest Rates!"; } }
the interest rate payout for deposits!
uint public Interest_Rate=2;
6,472,331
[ 1, 5787, 16513, 4993, 293, 2012, 364, 443, 917, 1282, 5, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 1071, 5294, 395, 67, 4727, 33, 22, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity =0.8.7; import "@openzeppelin/contracts/interfaces/IERC2981.sol"; abstract contract ERC2981Royalties is IERC2981 { struct Royalty { address recipient; uint256 value; // as a % unit, from 0 - 10000 (2 extra 0s) for eg 25% is 2500 } mapping(uint256 => Royalty) internal _royalties; // tokenId => royalty function _setTokenRoyalty( uint256 id, address recipient, uint256 value ) internal { require(value <= 100_00, "ERC2981Royalties: value too high"); _royalties[id] = Royalty(recipient, value); } function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view override returns (address receiver, uint256 royaltyAmount) { Royalty memory royalty = _royalties[_tokenId]; return (royalty.recipient, (_salePrice * royalty.value) / 100_00); } }
tokenId => royalty
mapping(uint256 => Royalty) internal _royalties;
12,769,709
[ 1, 2316, 548, 516, 721, 93, 15006, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 11890, 5034, 516, 534, 13372, 15006, 13, 2713, 389, 3800, 2390, 606, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; // File: contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event 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; } } // File: contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: contracts/token/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: contracts/token/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); 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 balance) { return balances[_owner]; } } // File: contracts/token/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/token/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); 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: contracts/token/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: contracts/FFUELCoinToken.sol contract FFUELCoinToken is MintableToken { string public constant name = "FIFO FUEL"; string public constant symbol = "FFUEL"; uint8 public decimals = 18; bool public tradingStarted = false; // version cache buster string public constant version = "v2"; // allow exceptional transfer for sender address - this mapping can be modified only before the starting rounds mapping (address => bool) public transferable; /** * @dev modifier that throws if spender address is not allowed to transfer * and the trading is not enabled */ modifier allowTransfer(address _spender) { require(tradingStarted || transferable[_spender]); _; } /** * * Only the owner of the token smart contract can add allow token to be transfer before the trading has started * */ function modifyTransferableHash(address _spender, bool value) onlyOwner public { transferable[_spender] = value; } /** * @dev Allows the owner to enable the trading. */ function startTrading() onlyOwner public { tradingStarted = true; } /** * @dev Allows anyone to transfer the tokens once trading has started * @param _to the recipient address of the tokens. * @param _value number of tokens to be transfered. */ function transfer(address _to, uint _value) allowTransfer(msg.sender) public returns (bool){ return super.transfer(_to, _value); } /** * @dev Allows anyone to transfer the tokens once trading has started or if the spender is part of the mapping * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) allowTransfer(_from) public returns (bool){ return super.transferFrom(_from, _to, _value); } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender when not paused. * @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 allowTransfer(_spender) returns (bool) { return super.approve(_spender, _value); } /** * Adding whenNotPaused */ function increaseApproval(address _spender, uint _addedValue) public allowTransfer(_spender) returns (bool success) { return super.increaseApproval(_spender, _addedValue); } /** * Adding whenNotPaused */ function decreaseApproval(address _spender, uint _subtractedValue) public allowTransfer(_spender) returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // File: contracts/crowdsale/Crowdsale.sol /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function // override to create custom buy function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // send ether to the fund collection wallet // overrided to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } } // File: contracts/crowdsale/FinalizableCrowdsale.sol /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); emit Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal{ } } // File: contracts/FFUELCoinTokenCrowdSale.sol contract FFUELCoinTokenCrowdSale is FinalizableCrowdsale { using SafeMath for uint256; uint256 public numberOfPurchasers = 0; // maximum tokens that can be minted in this crowd sale uint256 public maxTokenSupply = 0; // amounts of tokens already minted at the begining of this crowd sale - initialised later by the constructor uint256 public initialTokenAmount = 0; // version cache buster string public constant version = "v2"; // pending contract owner address public pendingOwner; // minimum amount to participate uint256 public minimumAmount = 0; // FFUELCoinToken public token; // white listing admin - initialised later by the constructor address public whiteListingAdmin; address public rateAdmin; bool public preSaleMode = true; uint256 public tokenRateGwei; address vested; uint256 vestedAmount; function FFUELCoinTokenCrowdSale( uint256 _startTime, uint256 _endTime, uint256 _rate, uint256 _minimumAmount, uint256 _maxTokenSupply, address _wallet, address _pendingOwner, address _whiteListingAdmin, address _rateAdmin, address _vested, uint256 _vestedAmount, FFUELCoinToken _token ) FinalizableCrowdsale() Crowdsale(_startTime, _endTime, _rate, _wallet) public { require(_pendingOwner != address(0)); require(_minimumAmount >= 0); require(_maxTokenSupply > 0); pendingOwner = _pendingOwner; minimumAmount = _minimumAmount; maxTokenSupply = _maxTokenSupply; // whitelisting admin setAdmin(_whiteListingAdmin, true); setAdmin(_rateAdmin, false); vested = _vested; vestedAmount = _vestedAmount; token=_token; } /** * @dev Calculates the amount of coins the buyer gets * @param weiAmount uint the amount of wei send to the contract * @return uint the amount of tokens the buyer gets */ function computeTokenWithBonus(uint256 weiAmount) public view returns (uint256) { uint256 tokens_ = 0; if (weiAmount >= 100000 ether) { tokens_ = weiAmount.mul(50).div(100); } else if (weiAmount < 100000 ether && weiAmount >= 50000 ether) { tokens_ = weiAmount.mul(35).div(100); } else if (weiAmount < 50000 ether && weiAmount >= 10000 ether) { tokens_ = weiAmount.mul(25).div(100); } else if (weiAmount < 10000 ether && weiAmount >= 2500 ether) { tokens_ = weiAmount.mul(15).div(100); } return tokens_; } /** * * Create the token on the fly, owner is the contract, not the contract owner yet * **/ function createTokenContract() internal returns (MintableToken) { return token; } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0), "not for 0x0"); // require(validPurchase(), "Crowd sale not started or ended, or min amount too low"); // buying can only begins as soon as the ownership has been transferred require(owner == pendingOwner, "ownership transfer not done"); require(tokenRateGwei != 0, "rate invalid"); // validate KYC here // if not part of kyc then throw bool cleared; uint16 contributor_get; address ref; uint16 affiliate_get; (cleared, contributor_get, ref, affiliate_get) = getContributor(beneficiary); // Transaction do not happen if the contributor is not KYC cleared require(cleared, "not whitelisted"); uint256 weiAmount = msg.value; // make sure we accept only the minimum contribution require(weiAmount > 0); // Compute the number of tokens per Gwei uint256 tokens = weiAmount.div(1000000000).mul(tokenRateGwei); // compute the amount of bonus, from the contribution amount uint256 bonus = computeTokenWithBonus(tokens); // compute the amount of token bonus for the contributor thank to his referral uint256 contributorGet = tokens.mul(contributor_get).div(10000); // Sum it all tokens = tokens.add(bonus); tokens = tokens.add(contributorGet); token.mint(beneficiary, tokens); emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); // update weiRaised = weiRaised.add(weiAmount); numberOfPurchasers = numberOfPurchasers + 1; forwardFunds(); // ------------------------------------------------------------------ // compute the amount of token bonus that the referral get : // only if KYC cleared, only if enough tokens still available // ------------------------------------------------------------------ bool refCleared; (refCleared) = getClearance(ref); if (refCleared && ref != beneficiary) { // recompute the tokens amount using only the rate tokens = weiAmount.div(1000000000).mul(tokenRateGwei); // compute the amount of token for the affiliate uint256 affiliateGet = tokens.mul(affiliate_get).div(10000); // capped to a maxTokenSupply // make sure we can not mint more token than expected // we do not throw here as if this edge case happens it can be dealt with of chain if (token.totalSupply() + affiliateGet <= maxTokenSupply) { // Mint the token token.mint(ref, affiliateGet); emit TokenPurchase(ref, ref, 0, affiliateGet); } } } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { // make sure we accept only the minimum contribution bool minAmount = (msg.value >= minimumAmount); // cap crowdsaled to a maxTokenSupply // make sure we can not mint more token than expected bool lessThanMaxSupply = (token.totalSupply() + msg.value.div(1000000000).mul(tokenRateGwei)) <= maxTokenSupply; //bool withinCap = weiRaised.add(msg.value) <= cap; return super.validPurchase() && minAmount && lessThanMaxSupply; } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { bool capReached = token.totalSupply() >= maxTokenSupply; return super.hasEnded() || capReached; } /** * * Called when the admin function finalize is called : * * it mint the remaining amount to have the supply exactly as planned * it transfer the ownership of the token to the owner of the smart contract * */ function finalization() internal { // // send back to the owner the remaining tokens before finishing minting // it ensure that there is only a exact maxTokenSupply token minted ever // uint256 remainingTokens = maxTokenSupply - token.totalSupply(); // mint the remaining amount and assign them to the owner token.mint(owner, remainingTokens); emit TokenPurchase(owner, owner, 0, remainingTokens); // finalize the refundable inherited contract super.finalization(); // no more minting allowed - immutable token.finishMinting(); // transfer the token owner ship from the contract address to the real owner token.transferOwnership(owner); } /** * * Admin functions only called by owner: * Can change events dates * */ function changeDates(uint256 _startTime, uint256 _endTime) public onlyOwner { require(_endTime >= _startTime, "End time need to be in the > _startTime"); startTime = _startTime; endTime = _endTime; } /** * * Admin functions only called by owner: * Change the owner * */ function transferOwnerShipToPendingOwner() public { // only the pending owner can change the ownership require(msg.sender == pendingOwner, "only the pending owner can change the ownership"); // can only be changed one time require(owner != pendingOwner, "Only one time allowed"); // raise the event emit OwnershipTransferred(owner, pendingOwner); // change the ownership owner = pendingOwner; // pre mint the coins preMint(vested, vestedAmount); } /** * * Return the amount of token minted during that crowd sale, removing the token pre minted * */ function minted() public view returns (uint256) { return token.totalSupply().sub(initialTokenAmount); } // hard code the pre minting function preMint(address vestedAddress, uint256 _amount) public onlyOwner { runPreMint(vestedAddress, _amount); // runPreMint(0x6B36b48Cb69472193444658b0b181C8049d371e1, 50000000000000000000000000); // reserved runPreMint(0xa484Ebcb519a6E50e4540d48F40f5ee466dEB7A7, 5000000000000000000000000); // bounty runPreMint(0x999f7f15Cf00E4495872D55221256Da7BCec2214, 5000000000000000000000000); // team runPreMint(0xB2233A3c93937E02a579422b6Ffc12DA5fc917E7, 5000000000000000000000000); // advisors // only one time preSaleMode = false; } // run the pre minting // can be done only one time function runPreMint(address _target, uint256 _amount) public onlyOwner { if (preSaleMode) { token.mint(_target, _amount); emit TokenPurchase(owner, _target, 0, _amount); initialTokenAmount = token.totalSupply(); } } /** * * Allow exceptional transfer * */ function modifyTransferableHash(address _spender, bool value) public onlyOwner { token.modifyTransferableHash(_spender, value); } // add a way to change the whitelistadmin user function setAdmin(address _adminAddress, bool whiteListAdmin) public onlyOwner { if (whiteListAdmin) { whiteListingAdmin = _adminAddress; } else { rateAdmin = _adminAddress; } } /** * * Admin functions only executed by rateAdmin * Can change the rate for the token sold * to increase the trust we could imagine to setup a range to avoid modification that are too far outside of the * acceptable range : * */ function setTokenRateInGwei(uint256 _tokenRateGwei) public { require(msg.sender == rateAdmin, "invalid admin"); tokenRateGwei = _tokenRateGwei; // update the integer rate accordingly, even if not used to not confuse users rate = _tokenRateGwei.div(1000000000); } // // Whitelist with affiliated structure // struct Contributor { bool cleared; // % more for the contributor bring on board uint16 contributor_get; // eth address of the referer if any - the contributor address is the key of the hash address ref; // % more for the referrer uint16 affiliate_get; } mapping(address => Contributor) public whitelist; address[] public whitelistArray; /** * @dev Populate the whitelist, only executed by whiteListingAdmin * */ function setContributor(address _address, bool cleared, uint16 contributor_get, uint16 affiliate_get, address ref) public { // not possible to give an exorbitant bonus to be more than 100% (100x100 = 10000) require(contributor_get < 10000, "c too high"); require(affiliate_get < 10000, "a too high"); require(msg.sender == whiteListingAdmin, "invalid admin"); Contributor storage contributor = whitelist[_address]; contributor.cleared = cleared; contributor.contributor_get = contributor_get; contributor.ref = ref; contributor.affiliate_get = affiliate_get; } function getContributor(address _address) public view returns (bool, uint16, address, uint16) { return (whitelist[_address].cleared, whitelist[_address].contributor_get, whitelist[_address].ref, whitelist[_address].affiliate_get); } function getClearance(address _address) public view returns (bool) { return whitelist[_address].cleared; } }
not possible to give an exorbitant bonus to be more than 100% (100x100 = 10000)
function setContributor(address _address, bool cleared, uint16 contributor_get, uint16 affiliate_get, address ref) public { require(contributor_get < 10000, "c too high"); require(affiliate_get < 10000, "a too high"); require(msg.sender == whiteListingAdmin, "invalid admin"); Contributor storage contributor = whitelist[_address]; contributor.cleared = cleared; contributor.contributor_get = contributor_get; contributor.ref = ref; contributor.affiliate_get = affiliate_get; }
1,082,935
[ 1, 902, 3323, 358, 8492, 392, 431, 280, 3682, 970, 324, 22889, 358, 506, 1898, 2353, 2130, 9, 261, 6625, 92, 6625, 273, 12619, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 442, 19293, 12, 2867, 389, 2867, 16, 1426, 16054, 16, 2254, 2313, 31123, 67, 588, 16, 2254, 2313, 7103, 330, 3840, 67, 588, 16, 1758, 1278, 13, 1071, 288, 203, 203, 3639, 2583, 12, 591, 19293, 67, 588, 411, 12619, 16, 315, 71, 4885, 3551, 8863, 203, 3639, 2583, 12, 7329, 330, 3840, 67, 588, 411, 12619, 16, 315, 69, 4885, 3551, 8863, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 9578, 19081, 4446, 16, 315, 5387, 3981, 8863, 203, 203, 3639, 735, 19293, 2502, 31123, 273, 10734, 63, 67, 2867, 15533, 203, 203, 3639, 31123, 18, 2131, 2258, 273, 16054, 31, 203, 3639, 31123, 18, 591, 19293, 67, 588, 273, 31123, 67, 588, 31, 203, 203, 3639, 31123, 18, 1734, 273, 1278, 31, 203, 3639, 31123, 18, 7329, 330, 3840, 67, 588, 273, 7103, 330, 3840, 67, 588, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File contracts/libraries/SafeMath.sol // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } } // File contracts/libraries/Address.sol pragma solidity 0.7.5; library Address { function isContract(address account) internal view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, 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); } } } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // 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 { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } function addressToString(address _address) internal pure returns(string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _addr = new bytes(42); _addr[0] = '0'; _addr[1] = 'x'; for(uint256 i = 0; i < 20; i++) { _addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)]; _addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_addr); } } // File contracts/interfaces/IERC20.sol pragma solidity 0.7.5; interface IERC20 { function decimals() external view returns (uint8); 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); } // File contracts/libraries/SafeERC20.sol pragma solidity 0.7.5; 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 { 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)); } function _callOptionalReturn(IERC20 token, bytes memory data) private { 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/libraries/FullMath.sol pragma solidity 0.7.5; library FullMath { function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; require(h < d, 'FullMath::mulDiv: overflow'); return fullDiv(l, h, d); } } // File contracts/libraries/FixedPoint.sol pragma solidity 0.7.5; library Babylonian { function sqrt(uint256 x) internal pure returns (uint256) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return (r < r1 ? r : r1); } } library BitMath { function mostSignificantBit(uint256 x) internal pure returns (uint8 r) { require(x > 0, 'BitMath::mostSignificantBit: zero'); if (x >= 0x100000000000000000000000000000000) { x >>= 128; r += 128; } if (x >= 0x10000000000000000) { x >>= 64; r += 64; } if (x >= 0x100000000) { x >>= 32; r += 32; } if (x >= 0x10000) { x >>= 16; r += 16; } if (x >= 0x100) { x >>= 8; r += 8; } if (x >= 0x10) { x >>= 4; r += 4; } if (x >= 0x4) { x >>= 2; r += 2; } if (x >= 0x2) r += 1; } } library FixedPoint { struct uq112x112 { uint224 _x; } struct uq144x112 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } function decode112with18(uq112x112 memory self) internal pure returns (uint) { return uint(self._x) / 5192296858534827; } function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } // square root of a UQ112x112 // lossy between 0/1 and 40 bits function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { if (self._x <= uint144(-1)) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112))); } uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x); safeShiftBits -= safeShiftBits % 2; return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2))); } } // File contracts/types/Ownable.sol pragma solidity 0.7.5; contract Ownable { address public policy; constructor () { policy = msg.sender; } modifier onlyPolicy() { require( policy == msg.sender, "Ownable: caller is not the owner" ); _; } function transferManagment(address _newOwner) external onlyPolicy() { require( _newOwner != address(0) ); policy = _newOwner; } } // File contracts/Bankless/CustomBond.sol pragma solidity 0.7.5; interface ITreasury { function deposit(address _principleTokenAddress, uint _amountPrincipleToken, uint _amountPayoutToken) external; function valueOfToken( address _principalTokenAddress, uint _amount ) external view returns ( uint value_ ); function payoutToken() external view returns (address); } contract CustomBANKBond is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMath for uint; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint payout, uint expires ); event BondRedeemed( address recipient, uint payout, uint remaining ); event BondPriceChanged( uint internalPrice, uint debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ IERC20 immutable payoutToken; // token paid for principal IERC20 immutable principalToken; // inflow token ITreasury immutable customTreasury; // pays for and receives principal address immutable olympusDAO; address olympusTreasury; // receives fee address immutable subsidyRouter; // pays subsidy in OHM to custom treasury uint public totalPrincipalBonded; uint public totalPayoutGiven; uint public totalDebt; // total value of outstanding bonds; used for pricing uint public lastDecay; // reference block for debt decay uint payoutSinceLastSubsidy; // principal accrued since subsidy paid Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data FeeTiers[] private feeTiers; // stores fee tiers bool immutable private feeInPayout; mapping( address => Bond ) public bondInfo; // stores bond information for depositors /* ======== STRUCTS ======== */ struct FeeTiers { uint tierCeilings; // principal bonded till next tier uint fees; // in ten-thousandths (i.e. 33300 = 3.33%) } // Info for creating new bonds struct Terms { uint controlVariable; // scaling variable for price uint vestingTerm; // in blocks uint minimumPrice; // vs principal value uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint maxDebt; // payout token decimal debt ratio, max % total supply created as debt } // Info for bond holder struct Bond { uint payout; // payout token remaining to be paid uint vesting; // Blocks left to vest uint lastBlock; // Last interaction uint truePricePaid; // Price paid (principal tokens per payout token) in ten-millionths - 4000000 = 0.4 } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint buffer; // minimum length (in blocks) between adjustments uint lastBlock; // block when last adjustment made } /* ======== CONSTRUCTOR ======== */ constructor( address _customTreasury, address _principalToken, address _olympusTreasury, address _subsidyRouter, address _initialOwner, address _olympusDAO, uint[] memory _tierCeilings, uint[] memory _fees, bool _feeInPayout ) { require( _customTreasury != address(0) ); customTreasury = ITreasury( _customTreasury ); payoutToken = IERC20( ITreasury(_customTreasury).payoutToken() ); require( _principalToken != address(0) ); principalToken = IERC20( _principalToken ); require( _olympusTreasury != address(0) ); olympusTreasury = _olympusTreasury; require( _subsidyRouter != address(0) ); subsidyRouter = _subsidyRouter; require( _initialOwner != address(0) ); policy = _initialOwner; require( _olympusDAO != address(0) ); olympusDAO = _olympusDAO; require(_tierCeilings.length == _fees.length, "tier length and fee length not the same"); for(uint i; i < _tierCeilings.length; i++) { feeTiers.push( FeeTiers({ tierCeilings: _tierCeilings[i], fees: _fees[i] })); } feeInPayout = _feeInPayout; } /* ======== INITIALIZATION ======== */ /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint * @param _minimumPrice uint * @param _maxPayout uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBond( uint _controlVariable, uint _vestingTerm, uint _minimumPrice, uint _maxPayout, uint _maxDebt, uint _initialDebt ) external onlyPolicy() { require( currentDebt() == 0, "Debt must be 0 for initialization" ); terms = Terms ({ controlVariable: _controlVariable, vestingTerm: _vestingTerm, minimumPrice: _minimumPrice, maxPayout: _maxPayout, maxDebt: _maxDebt }); totalDebt = _initialDebt; lastDecay = block.number; } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, DEBT } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyPolicy() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 10000, "Vesting must be longer than 36 hours" ); terms.vestingTerm = _input; } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 2 terms.maxDebt = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint _buffer ) external onlyPolicy() { require( _increment <= terms.controlVariable.mul( 30 ).div( 1000 ), "Increment too large" ); adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastBlock: block.number }); } /** * @notice change address of Olympus Treasury * @param _olympusTreasury uint */ function changeOlympusTreasury(address _olympusTreasury) external { require( msg.sender == olympusDAO, "Only Olympus DAO" ); olympusTreasury = _olympusTreasury; } /** * @notice subsidy controller checks payouts since last subsidy and resets counter * @return payoutSinceLastSubsidy_ uint */ function paySubsidy() external returns ( uint payoutSinceLastSubsidy_ ) { require( msg.sender == subsidyRouter, "Only subsidy controller" ); payoutSinceLastSubsidy_ = payoutSinceLastSubsidy; payoutSinceLastSubsidy = 0; } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit(uint _amount, uint _maxPrice, address _depositor) external returns (uint) { require( _depositor != address(0), "Invalid address" ); decayDebt(); uint nativePrice = trueBondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = customTreasury.valueOfToken( address(principalToken), _amount ); uint payout; uint fee; if(feeInPayout) { (payout, fee) = payoutFor( value ); // payout to bonder is computed } else { (payout, fee) = payoutFor( _amount ); // payout to bonder is computed _amount = _amount.sub(fee); } require( payout >= 10 ** payoutToken.decimals() / 100, "Bond too small" ); // must be > 0.01 payout token ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage // total debt is increased totalDebt = totalDebt.add( value ); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastBlock: block.number, truePricePaid: trueBondPrice() }); totalPrincipalBonded = totalPrincipalBonded.add(_amount); // total bonded increased totalPayoutGiven = totalPayoutGiven.add(payout); // total payout increased payoutSinceLastSubsidy = payoutSinceLastSubsidy.add( payout ); // subsidy counter increased principalToken.approve( address(customTreasury), _amount ); if(feeInPayout) { principalToken.safeTransferFrom( msg.sender, address(this), _amount ); customTreasury.deposit( address(principalToken), _amount, payout.add(fee) ); } else { principalToken.safeTransferFrom( msg.sender, address(this), _amount.add(fee) ); customTreasury.deposit( address(principalToken), _amount, payout ); } if ( fee != 0 ) { // fee is transferred to dao if(feeInPayout) { payoutToken.safeTransfer(olympusTreasury, fee); } else { principalToken.safeTransfer( olympusTreasury, fee ); } } // indexed events are emitted emit BondCreated( _amount, payout, block.number.add( terms.vestingTerm ) ); emit BondPriceChanged( _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @return uint */ function redeem(address _depositor) external returns (uint) { Bond memory info = bondInfo[ _depositor ]; uint percentVested = percentVestedFor( _depositor ); // (blocks since last interaction / vesting term remaining) if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _depositor ]; // delete user info emit BondRedeemed( _depositor, info.payout, 0 ); // emit bond data payoutToken.safeTransfer( _depositor, info.payout ); return info.payout; } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _depositor ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub( block.number.sub( info.lastBlock ) ), lastBlock: block.number, truePricePaid: info.truePricePaid }); emit BondRedeemed( _depositor, payout, bondInfo[ _depositor ].payout ); payoutToken.safeTransfer( _depositor, payout ); return payout; } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint blockCanAdjust = adjustment.lastBlock.add( adjustment.buffer ); if( adjustment.rate != 0 && block.number >= blockCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target ) { adjustment.rate = 0; } } adjustment.lastBlock = block.number; emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = block.number; } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 10 ** (uint256(payoutToken.decimals()).sub(5)) ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /* ======== VIEW FUNCTIONS ======== */ /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).div( 10 ** (uint256(payoutToken.decimals()).sub(5)) ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate true bond price a user pays * @return price_ uint */ function trueBondPrice() public view returns ( uint price_ ) { price_ = bondPrice().add(bondPrice().mul( currentOlympusFee() ).div( 1e6 ) ); } /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return payoutToken.totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate user's interest due for new bond, accounting for Olympus Fee. If fee is in payout then takes in the already calcualted value. If fee is in principal token than takes in the amount of principal being deposited and then calculautes the fee based on the amount of principal and not in terms of the payout token * @param _value uint * @return _payout uint * @return _fee uint */ function payoutFor( uint _value ) public view returns ( uint _payout, uint _fee) { if(feeInPayout) { uint total = FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e11 ); _fee = total.mul( currentOlympusFee() ).div( 1e6 ); _payout = total.sub(_fee); } else { _fee = _value.mul( currentOlympusFee() ).div( 1e6 ); _payout = FixedPoint.fraction( customTreasury.valueOfToken(address(principalToken), _value.sub(_fee)), bondPrice() ).decode112with18().div( 1e11 ); } } /** * @notice calculate current ratio of debt to payout token supply * @notice protocols using Olympus Pro should be careful when quickly adding large %s to total supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { debtRatio_ = FixedPoint.fraction( currentDebt().mul( 10 ** payoutToken.decimals() ), payoutToken.totalSupply() ).decode112with18().div( 1e18 ); } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint blocksSinceLast = block.number.sub( lastDecay ); decay_ = totalDebt.mul( blocksSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint blocksSinceLast = block.number.sub( bond.lastBlock ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = blocksSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of payout token available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /** * @notice current fee Olympus takes of each bond * @return currentFee_ uint */ function currentOlympusFee() public view returns( uint currentFee_ ) { uint tierLength = feeTiers.length; for(uint i; i < tierLength; i++) { if(totalPrincipalBonded < feeTiers[i].tierCeilings || i == tierLength - 1 ) { return feeTiers[i].fees; } } } }
scaling variable for price
uint controlVariable;
33,378
[ 1, 24576, 2190, 364, 6205, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 3325, 3092, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0xE9Cc97730a4e951BbfF27bbE998282cE73579C72/sources/contracts/BaseChain.sol
@param blocksCountOffset number of all blocks that were generated before switching to this contract @param sequence is a total number of blocks (consensus rounds) including previous contracts @param lastTimestamp is a timestamp of last submitted block @param padding number of seconds that need to pass before new submit will be possible @param deprecated flag that changes to TRUE on `unregister`, when TRUE submissions are not longer available
struct ConsensusData { uint32 blocksCountOffset; uint32 sequence; uint32 lastTimestamp; uint32 padding; bool deprecated; } uint256 constant public VERSION = 2; bytes4 constant private _VERSION_SELECTOR = bytes4(keccak256("VERSION()")); ConsensusData internal _consensusData; bytes constant public ETH_PREFIX = "\x19Ethereum Signed Message:\n32"; event LogDeprecation(address indexed deprecator); event LogPadding(address indexed executor, uint32 timePadding); error ArraysDataDoNotMatch(); error AlreadyDeprecated(); error AlreadyRegistered(); error BlockSubmittedToFastOrDataToOld(); error ContractNotReady(); error FCDOverflow(); error InvalidContractType(); error NoChangeToState(); error OnlyOwnerOrRegistry(); error UnregisterFirst();
7,206,320
[ 1, 7996, 1380, 2335, 1300, 434, 777, 4398, 716, 4591, 4374, 1865, 30882, 358, 333, 6835, 225, 3102, 353, 279, 2078, 1300, 434, 4398, 261, 29220, 21196, 13, 6508, 2416, 20092, 225, 1142, 4921, 353, 279, 2858, 434, 1142, 9638, 1203, 225, 4992, 1300, 434, 3974, 716, 1608, 358, 1342, 1865, 394, 4879, 903, 506, 3323, 225, 6849, 2982, 716, 3478, 358, 5383, 603, 1375, 318, 4861, 9191, 1347, 5383, 22071, 854, 486, 7144, 2319, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 11020, 9781, 751, 288, 203, 3639, 2254, 1578, 4398, 1380, 2335, 31, 203, 3639, 2254, 1578, 3102, 31, 203, 3639, 2254, 1578, 1142, 4921, 31, 203, 3639, 2254, 1578, 4992, 31, 203, 3639, 1426, 6849, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 5381, 1071, 8456, 273, 576, 31, 203, 203, 203, 565, 1731, 24, 5381, 3238, 389, 5757, 67, 4803, 916, 273, 1731, 24, 12, 79, 24410, 581, 5034, 2932, 5757, 1435, 7923, 1769, 203, 203, 565, 11020, 9781, 751, 2713, 389, 29220, 751, 31, 203, 203, 565, 1731, 5381, 1071, 512, 2455, 67, 6307, 273, 1548, 92, 3657, 41, 18664, 379, 16724, 2350, 5581, 82, 1578, 14432, 203, 203, 203, 203, 565, 871, 1827, 758, 13643, 12, 2867, 8808, 443, 4036, 639, 1769, 203, 565, 871, 1827, 9485, 12, 2867, 8808, 6601, 16, 2254, 1578, 813, 9485, 1769, 203, 203, 565, 555, 5647, 751, 3244, 1248, 2060, 5621, 203, 565, 555, 17009, 13534, 5621, 203, 565, 555, 17009, 10868, 5621, 203, 565, 555, 3914, 28882, 774, 12305, 1162, 751, 774, 7617, 5621, 203, 565, 555, 13456, 1248, 8367, 5621, 203, 565, 555, 478, 39, 3191, 502, 2426, 5621, 203, 565, 555, 1962, 8924, 559, 5621, 203, 565, 555, 2631, 3043, 774, 1119, 5621, 203, 565, 555, 5098, 5541, 1162, 4243, 5621, 203, 565, 555, 1351, 4861, 3759, 5621, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xAfCf0e333614286D8e20000781121adB28cEf33D/sources/localhost/contracts/deposit/StafiNodeDeposit.sol
Accept a node deposit and create a new staking pool under the node Check node settings Load contracts Get deposit type by node deposit amount
function deposit() override external payable onlyLatestContract("stafiNodeDeposit", address(this)) { require(getDepositEnabled(), "Node deposits are currently disabled"); require(msg.value == 0 || msg.value == getCurrentNodeDepositAmount(), "Invalid node deposit amount"); IStafiUserDeposit stafiUserDeposit = IStafiUserDeposit(getContractAddress("stafiUserDeposit")); IStafiStakingPoolManager stafiStakingPoolManager = IStafiStakingPoolManager(getContractAddress("stafiStakingPoolManager")); IStafiStakingPoolSettings stafiStakingPoolSettings = IStafiStakingPoolSettings(getContractAddress("stafiStakingPoolSettings")); DepositType depositType = DepositType.None; IStafiNodeManager stafiNodeManager = IStafiNodeManager(getContractAddress("stafiNodeManager")); if (depositType == DepositType.None && stafiNodeManager.getNodeTrusted(msg.sender)) { depositType = DepositType.Empty; } IStafiStakingPool stakingPool = IStafiStakingPool(stakingPoolAddress); }
17,084,017
[ 1, 5933, 279, 756, 443, 1724, 471, 752, 279, 394, 384, 6159, 2845, 3613, 326, 756, 2073, 756, 1947, 4444, 20092, 968, 443, 1724, 618, 635, 756, 443, 1724, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 1435, 3849, 3903, 8843, 429, 1338, 18650, 8924, 2932, 334, 1727, 77, 907, 758, 1724, 3113, 1758, 12, 2211, 3719, 288, 203, 3639, 2583, 12, 588, 758, 1724, 1526, 9334, 315, 907, 443, 917, 1282, 854, 4551, 5673, 8863, 203, 3639, 2583, 12, 3576, 18, 1132, 422, 374, 747, 1234, 18, 1132, 422, 5175, 907, 758, 1724, 6275, 9334, 315, 1941, 756, 443, 1724, 3844, 8863, 203, 3639, 467, 510, 1727, 77, 1299, 758, 1724, 384, 1727, 77, 1299, 758, 1724, 273, 467, 510, 1727, 77, 1299, 758, 1724, 12, 588, 8924, 1887, 2932, 334, 1727, 77, 1299, 758, 1724, 7923, 1769, 203, 3639, 467, 510, 1727, 77, 510, 6159, 2864, 1318, 384, 1727, 77, 510, 6159, 2864, 1318, 273, 467, 510, 1727, 77, 510, 6159, 2864, 1318, 12, 588, 8924, 1887, 2932, 334, 1727, 77, 510, 6159, 2864, 1318, 7923, 1769, 203, 3639, 467, 510, 1727, 77, 510, 6159, 2864, 2628, 384, 1727, 77, 510, 6159, 2864, 2628, 273, 467, 510, 1727, 77, 510, 6159, 2864, 2628, 12, 588, 8924, 1887, 2932, 334, 1727, 77, 510, 6159, 2864, 2628, 7923, 1769, 203, 3639, 4019, 538, 305, 559, 443, 1724, 559, 273, 4019, 538, 305, 559, 18, 7036, 31, 203, 203, 3639, 467, 510, 1727, 77, 907, 1318, 384, 1727, 77, 907, 1318, 273, 467, 510, 1727, 77, 907, 1318, 12, 588, 8924, 1887, 2932, 334, 1727, 77, 907, 1318, 7923, 1769, 203, 3639, 309, 261, 323, 1724, 559, 422, 4019, 538, 305, 559, 18, 7036, 597, 384, 1727, 77, 2 ]
./full_match/80001/0xf8259f553438C1C00C01E1552A59e05B4bD9CDC3/sources/foxV18.sol
DEV: TODO ADD setReferralAddress and implement referral mecanism in UserInfo and deposit Info of each user.
contract MasterChef is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeBEP20 for IBEP20; struct UserInfo { } struct PoolInfo { } event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmissionRateUpdated(address indexed caller, uint256 previousAmount, uint256 newAmount); event ReferralCommissionPaid(address indexed user, address indexed referrer, uint256 commissionAmount); event StartBlockUpdated(address indexed user, uint256 newStartBlock); constructor( FoxToken _fox, uint256 _startBlock FoxToken public fox; address public devAddress; address public feeAddress; uint256 public foxPerBlock; uint256 public constant BONUS_MULTIPLIER = 1; uint256 public constant INITIAL_EMISSION_RATE = 650 finney; uint256 public constant MINIMUM_EMISSION_RATE = 1 wei; uint256 public constant EMISSION_REDUCTION_PERIOD_BLOCKS = 15770000; uint256 public constant EMISSION_REDUCTION_RATE_PER_PERIOD = 5000; uint256 public lastReductionPeriodIndex = 0; PoolInfo[] public poolInfo; mapping(uint256 => mapping(address => UserInfo)) public userInfo; uint256 public totalAllocPoint = 0; uint256 public startBlock; IFoxReferral public foxReferral; uint16 public referralCommissionRate = 100; uint16 public constant MAXIMUM_REFERRAL_COMMISSION_RATE = 2000; ) public { fox = _fox; startBlock = _startBlock; devAddress = msg.sender; feeAddress = msg.sender; foxPerBlock = INITIAL_EMISSION_RATE; } function poolLength() external view returns (uint256) { return poolInfo.length; } mapping(IBEP20 => bool) public poolExistence; modifier nonDuplicated(IBEP20 _lpToken) { require(poolExistence[_lpToken] == false, "nonDuplicated: duplicated"); _; } function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner nonDuplicated(_lpToken) { require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolExistence[_lpToken] = true; poolInfo.push(PoolInfo({ lpToken : _lpToken, allocPoint : _allocPoint, lastRewardBlock : lastRewardBlock, accFoxPerShare : 0, depositFeeBP : _depositFeeBP })); } function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner nonDuplicated(_lpToken) { require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolExistence[_lpToken] = true; poolInfo.push(PoolInfo({ lpToken : _lpToken, allocPoint : _allocPoint, lastRewardBlock : lastRewardBlock, accFoxPerShare : 0, depositFeeBP : _depositFeeBP })); } function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner nonDuplicated(_lpToken) { require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolExistence[_lpToken] = true; poolInfo.push(PoolInfo({ lpToken : _lpToken, allocPoint : _allocPoint, lastRewardBlock : lastRewardBlock, accFoxPerShare : 0, depositFeeBP : _depositFeeBP })); } function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 10000, "set: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].depositFeeBP = _depositFeeBP; } function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner { require(_depositFeeBP <= 10000, "set: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].depositFeeBP = _depositFeeBP; } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } function pendingEgg(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accFoxPerShare = pool.accFoxPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 eggReward = multiplier.mul(foxPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accFoxPerShare = accFoxPerShare.add(eggReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accFoxPerShare).div(1e12).sub(user.rewardDebt); } function pendingEgg(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accFoxPerShare = pool.accFoxPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 eggReward = multiplier.mul(foxPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accFoxPerShare = accFoxPerShare.add(eggReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accFoxPerShare).div(1e12).sub(user.rewardDebt); } function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 foxReward = multiplier.mul(foxPerBlock).mul(pool.allocPoint).div(totalAllocPoint); fox.mint(devAddress, foxReward.div(10)); fox.mint(address(this), foxReward); pool.accFoxPerShare = pool.accFoxPerShare.add(foxReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 foxReward = multiplier.mul(foxPerBlock).mul(pool.allocPoint).div(totalAllocPoint); fox.mint(devAddress, foxReward.div(10)); fox.mint(address(this), foxReward); pool.accFoxPerShare = pool.accFoxPerShare.add(foxReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 foxReward = multiplier.mul(foxPerBlock).mul(pool.allocPoint).div(totalAllocPoint); fox.mint(devAddress, foxReward.div(10)); fox.mint(address(this), foxReward); pool.accFoxPerShare = pool.accFoxPerShare.add(foxReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } function deposit(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accFoxPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeEggTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (pool.depositFeeBP > 0) { uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accFoxPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accFoxPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeEggTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (pool.depositFeeBP > 0) { uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accFoxPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accFoxPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeEggTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (pool.depositFeeBP > 0) { uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accFoxPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accFoxPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeEggTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (pool.depositFeeBP > 0) { uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accFoxPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accFoxPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeEggTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); if (pool.depositFeeBP > 0) { uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000); pool.lpToken.safeTransfer(feeAddress, depositFee); user.amount = user.amount.add(_amount).sub(depositFee); user.amount = user.amount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accFoxPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } } else { function withdraw(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accFoxPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeEggTransfer(msg.sender, pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accFoxPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } function withdraw(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accFoxPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeEggTransfer(msg.sender, pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accFoxPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } function withdraw(uint256 _pid, uint256 _amount) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accFoxPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeEggTransfer(msg.sender, pending); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accFoxPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } function emergencyWithdraw(uint256 _pid) public nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } function safeEggTransfer(address _to, uint256 _amount) internal { uint256 foxBal = fox.balanceOf(address(this)); bool transferSuccess = false; if (_amount > foxBal) { transferSuccess = fox.transfer(_to, foxBal); transferSuccess = fox.transfer(_to, _amount); } require(transferSuccess, "safeEggTransfer: transfer failed"); } function safeEggTransfer(address _to, uint256 _amount) internal { uint256 foxBal = fox.balanceOf(address(this)); bool transferSuccess = false; if (_amount > foxBal) { transferSuccess = fox.transfer(_to, foxBal); transferSuccess = fox.transfer(_to, _amount); } require(transferSuccess, "safeEggTransfer: transfer failed"); } } else { function dev(address _devaddr) public { require(msg.sender == devAddress, "dev: what are you trying to do exactly?"); devAddress = _devaddr; } function setFeeAddress(address _feeAddress) public onlyOwner { feeAddress = _feeAddress; } function updateStartBlock(uint256 _startBlock) public onlyOwner { startBlock = _startBlock; emit StartBlockUpdated(msg.sender, _startBlock); } function updateEmissionRate() public onlyOwner { require(block.number > startBlock, "updateEmissionRate: Can only be called after mining starts"); require(foxPerBlock > MINIMUM_EMISSION_RATE, "updateEmissionRate: Emission rate has reached the minimum threshold"); uint256 currentIndex = block.number.sub(startBlock).div(EMISSION_REDUCTION_PERIOD_BLOCKS); if (currentIndex <= lastReductionPeriodIndex) { return; } uint256 newEmissionRate = foxPerBlock; for (uint256 index = lastReductionPeriodIndex; index < currentIndex; ++index) { newEmissionRate = newEmissionRate.mul(1e4 - EMISSION_REDUCTION_RATE_PER_PERIOD).div(1e4); } newEmissionRate = newEmissionRate < MINIMUM_EMISSION_RATE ? MINIMUM_EMISSION_RATE : newEmissionRate; if (newEmissionRate >= foxPerBlock) { return; } massUpdatePools(); lastReductionPeriodIndex = currentIndex; uint256 previousEmissionRate = foxPerBlock; foxPerBlock = newEmissionRate; emit EmissionRateUpdated(msg.sender, previousEmissionRate, newEmissionRate); } function updateEmissionRate() public onlyOwner { require(block.number > startBlock, "updateEmissionRate: Can only be called after mining starts"); require(foxPerBlock > MINIMUM_EMISSION_RATE, "updateEmissionRate: Emission rate has reached the minimum threshold"); uint256 currentIndex = block.number.sub(startBlock).div(EMISSION_REDUCTION_PERIOD_BLOCKS); if (currentIndex <= lastReductionPeriodIndex) { return; } uint256 newEmissionRate = foxPerBlock; for (uint256 index = lastReductionPeriodIndex; index < currentIndex; ++index) { newEmissionRate = newEmissionRate.mul(1e4 - EMISSION_REDUCTION_RATE_PER_PERIOD).div(1e4); } newEmissionRate = newEmissionRate < MINIMUM_EMISSION_RATE ? MINIMUM_EMISSION_RATE : newEmissionRate; if (newEmissionRate >= foxPerBlock) { return; } massUpdatePools(); lastReductionPeriodIndex = currentIndex; uint256 previousEmissionRate = foxPerBlock; foxPerBlock = newEmissionRate; emit EmissionRateUpdated(msg.sender, previousEmissionRate, newEmissionRate); } function updateEmissionRate() public onlyOwner { require(block.number > startBlock, "updateEmissionRate: Can only be called after mining starts"); require(foxPerBlock > MINIMUM_EMISSION_RATE, "updateEmissionRate: Emission rate has reached the minimum threshold"); uint256 currentIndex = block.number.sub(startBlock).div(EMISSION_REDUCTION_PERIOD_BLOCKS); if (currentIndex <= lastReductionPeriodIndex) { return; } uint256 newEmissionRate = foxPerBlock; for (uint256 index = lastReductionPeriodIndex; index < currentIndex; ++index) { newEmissionRate = newEmissionRate.mul(1e4 - EMISSION_REDUCTION_RATE_PER_PERIOD).div(1e4); } newEmissionRate = newEmissionRate < MINIMUM_EMISSION_RATE ? MINIMUM_EMISSION_RATE : newEmissionRate; if (newEmissionRate >= foxPerBlock) { return; } massUpdatePools(); lastReductionPeriodIndex = currentIndex; uint256 previousEmissionRate = foxPerBlock; foxPerBlock = newEmissionRate; emit EmissionRateUpdated(msg.sender, previousEmissionRate, newEmissionRate); } function updateEmissionRate() public onlyOwner { require(block.number > startBlock, "updateEmissionRate: Can only be called after mining starts"); require(foxPerBlock > MINIMUM_EMISSION_RATE, "updateEmissionRate: Emission rate has reached the minimum threshold"); uint256 currentIndex = block.number.sub(startBlock).div(EMISSION_REDUCTION_PERIOD_BLOCKS); if (currentIndex <= lastReductionPeriodIndex) { return; } uint256 newEmissionRate = foxPerBlock; for (uint256 index = lastReductionPeriodIndex; index < currentIndex; ++index) { newEmissionRate = newEmissionRate.mul(1e4 - EMISSION_REDUCTION_RATE_PER_PERIOD).div(1e4); } newEmissionRate = newEmissionRate < MINIMUM_EMISSION_RATE ? MINIMUM_EMISSION_RATE : newEmissionRate; if (newEmissionRate >= foxPerBlock) { return; } massUpdatePools(); lastReductionPeriodIndex = currentIndex; uint256 previousEmissionRate = foxPerBlock; foxPerBlock = newEmissionRate; emit EmissionRateUpdated(msg.sender, previousEmissionRate, newEmissionRate); } }
5,694,075
[ 1, 15301, 30, 2660, 11689, 444, 1957, 29084, 1887, 471, 2348, 1278, 29084, 312, 557, 304, 6228, 316, 25003, 471, 443, 1724, 3807, 434, 1517, 729, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 13453, 39, 580, 74, 353, 14223, 6914, 16, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 5948, 52, 3462, 364, 467, 5948, 52, 3462, 31, 203, 7010, 203, 203, 203, 565, 1958, 25003, 288, 203, 565, 289, 203, 203, 565, 1958, 8828, 966, 288, 203, 565, 289, 203, 203, 203, 202, 203, 203, 203, 565, 871, 4019, 538, 305, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 4231, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 3423, 9446, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 4231, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 512, 6592, 75, 2075, 1190, 9446, 12, 2867, 8808, 729, 16, 2254, 5034, 8808, 4231, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 512, 3951, 4727, 7381, 12, 2867, 8808, 4894, 16, 2254, 5034, 2416, 6275, 16, 2254, 5034, 394, 6275, 1769, 203, 565, 871, 3941, 29084, 799, 3951, 16507, 350, 12, 2867, 8808, 729, 16, 1758, 8808, 14502, 16, 2254, 5034, 1543, 19710, 6275, 1769, 203, 565, 871, 3603, 1768, 7381, 12, 2867, 8808, 729, 16, 2254, 5034, 394, 1685, 1768, 1769, 203, 203, 565, 3885, 12, 203, 3639, 478, 2409, 1345, 389, 13873, 16, 203, 3639, 2254, 5034, 389, 1937, 1768, 203, 565, 478, 2409, 1345, 1071, 284, 2409, 31, 203, 565, 1758, 1071, 4461, 1887, 31, 203, 565, 1758, 1071, 14036, 1887, 31, 203, 565, 2254, 5034, 1071, 284, 2409, 2173, 1768, 31, 203, 565, 2254, 5034, 1071, 5381, 605, 673, 3378, 67, 24683, 2053, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "../interfaces/IController.sol"; import "../interfaces/IAccount.sol"; import "../interfaces/IVault.sol"; import "../interfaces/ISavingApplication.sol"; /** * @notice Application to save assets from account to vaults to * earn yield and rewards. */ contract SavingApplication is Initializable, ISavingApplication { using SafeERC20Upgradeable for IERC20Upgradeable; using SafeMathUpgradeable for uint256; event GovernanceUpdated(address indexed oldGovernance, address indexed newGovernance); event StrategistUpdated(address indexed oldStrategist, address indexed newStrategist); event ControllerUpdated(address indexed oldController, address indexed newController); event AutoSavingUpdated(address indexed account, address indexed token, bool indexed allowed); event AutoSavingThresholdUpdated(address indexed token, uint256 oldValue, uint256 newValue); event Deposited(address indexed account, uint256 indexed vaultId, address token, uint256 amount); event Withdrawn(address indexed account, uint256 indexed vaultId, address token, uint256 amount); event Claimed(address indexed account, uint256 indexed vaultId, address token, uint256 amount); event Exited(address indexed account, uint256 indexed vaultId); // Account ==> Token ==> Auto saving mapping(address => mapping(address => bool)) public autoSaving; // Token ==> Auto saving threshold mapping(address => uint256) public autoSavingThreshold; address public override controller; address public override governance; address public strategist; uint256[50] private __gap; /** * @dev Initializes the saving application. Can be called only once. */ function initialize(address _controller) public initializer { require(_controller != address(0x0), "controller not set"); controller = _controller; governance = msg.sender; strategist = msg.sender; } modifier onlyGovernance() { require(msg.sender == governance, "not governance"); _; } modifier onlyStrategist() { require(msg.sender == governance || msg.sender == strategist, "not strategist"); _; } /** * @dev Updates the govenance address. * Only governance can set a new governance. The governance can be renounced * by setting a zero address. */ function setGovernance(address _governance) public onlyGovernance { address oldGovernance = governance; governance = _governance; emit GovernanceUpdated(oldGovernance, _governance); } /** * @dev Updates the strategist address. Only governance and strategist can update strategist. * Each vault has its own strategist to perform daily permissioned opertions. * Vault and its strategies managed share the same strategist. */ function setStrategist(address _strategist) public override onlyStrategist { address oldStrategist = strategist; strategist = _strategist; emit StrategistUpdated(oldStrategist, _strategist); } /** * @dev Updates the controller address. * Only governance can set a new controller. */ function setController(address _controller) public onlyGovernance { require(_controller != address(0x0), "controller not set"); address oldController = address(controller); controller = _controller; emit ControllerUpdated(oldController, _controller); } function _validateAccount(IAccount _account) internal view { require(_account.owner() == msg.sender, "not owner"); require(_account.isOperator(address(this)), "not operator"); } /** * @dev Updates auto saving policy on account. When auto saving is enabled on * an account on a token, strategist can help to deposit account's token to its vault. * @param _account Account to enable auto saving. * @param _token The token to enable auto saving. * @param _allowed Whether auto saving is allowed. */ function setAutoSaving(address _account, address _token, bool _allowed) public { _validateAccount(IAccount(_account)); autoSaving[_account][_token] = _allowed; emit AutoSavingUpdated(_account, _token, _allowed); } /** * @dev Updates auto saving threshold for a token. If the token balance of an account is * below the threshold, strategist won't help to deposit the account's token even if auto saving * is enabled on the account for that token. * @param _token The token to set auto saving threshold. * @param _value The new auto saving threshold to that token. */ function setAutoSavingThreshold(address _token, uint256 _value) public onlyStrategist { uint256 oldValue = autoSavingThreshold[_token]; autoSavingThreshold[_token] = _value; emit AutoSavingThresholdUpdated(_token, oldValue, _value); } /** * @dev Deposit token into rewarded vault. * @param _account The account address used to deposit. * @param _vaultId ID of the vault to deposit. * @param _amount Amount of token to deposit. * @param _claimRewards Whether to claim rewards at the same time. */ function deposit(address _account, uint256 _vaultId, uint256 _amount, bool _claimRewards) external { IVault vault = IVault(IController(controller).vaults(_vaultId)); require(address(vault) != address(0x0), "no vault"); require(_amount > 0, "zero amount"); IAccount account = IAccount(_account); _validateAccount(account); address token = vault.token(); account.invoke(token, 0, abi.encodeWithSignature("approve(address,uint256)", address(vault), _amount)); account.invoke(address(vault), 0, abi.encodeWithSignature("deposit(uint256)", _amount)); emit Deposited(_account, _vaultId, token, _amount); if (_claimRewards) { _claimAllRewards(_account, _vaultId, address(vault)); } } /** * @dev Withdraws token out of RewardedVault. * @param _account The account address used to withdraw. * @param _vaultId ID of the vault to withdraw. * @param _amount Amount of token to withdraw. * @param _claimRewards Whether to claim rewards at the same time. */ function withdraw(address _account, uint256 _vaultId, uint256 _amount, bool _claimRewards) external { IVault vault = IVault(IController(controller).vaults(_vaultId)); require(address(vault) != address(0x0), "no vault"); require(_amount > 0, "zero amount"); IAccount account = IAccount(_account); _validateAccount(account); address token = IVault(vault).token(); // Important: Need to convert token amount to vault share! uint256 totalBalance = vault.balance(); uint256 totalSupply = IERC20Upgradeable(address(vault)).totalSupply(); uint256 shares = _amount.mul(totalSupply).div(totalBalance); bytes memory methodData = abi.encodeWithSignature("withdraw(uint256)", shares); account.invoke(address(vault), 0, methodData); emit Withdrawn(_account, _vaultId, token, _amount); if (_claimRewards) { _claimAllRewards(_account, _vaultId, address(vault)); } } /** * @dev Exit the vault and claims all rewards. * @param _account The account address used to exit. * @param _vaultId ID of the vault to exit. */ function exit(address _account, uint256 _vaultId) external { IVault vault = IVault(IController(controller).vaults(_vaultId)); require(address(vault) != address(0x0), "no vault"); IAccount account = IAccount(_account); _validateAccount(account); bytes memory methodData = abi.encodeWithSignature("exit()"); account.invoke(address(vault), 0, methodData); emit Exited(_account, _vaultId); } /** * @dev Claims rewards from RewardedVault. * @param _account The account address used to claim rewards. * @param _vaultId ID of the vault to claim rewards. */ function claimRewards(address _account, uint256 _vaultId) public { address vault = IController(controller).vaults(_vaultId); require(vault != address(0x0), "no vault"); IAccount account = IAccount(_account); _validateAccount(account); _claimAllRewards(_account, _vaultId, vault); } /** * @dev Claims rewards from RewardedVault. * @param _account The account address used to claim rewards. * @param _vaultIds IDs of the vault to claim rewards. */ function claimRewardsFromVaults(address _account, uint256[] memory _vaultIds) public { IAccount account = IAccount(_account); _validateAccount(account); for (uint256 i = 0; i < _vaultIds.length; i++) { address vault = IController(controller).vaults(_vaultIds[i]); require(vault != address(0x0), "no vault"); _claimAllRewards(_account, _vaultIds[i], vault); } } /** * @dev Internal method to claims rewards. Account and vault parameters should be already validated. */ function _claimAllRewards(address _account, uint256 _vaultId, address _vault) internal { address rewardToken = IController(controller).rewardToken(); bytes memory methodData = abi.encodeWithSignature("claimReward()"); bytes memory methodResult = IAccount(_account).invoke(_vault, 0, methodData); uint256 claimAmount = abi.decode(methodResult, (uint256)); emit Claimed(_account, _vaultId, rewardToken, claimAmount); } /** * @dev Deposits into vault on behalf of the accounts provided. This can be only called by strategist. * @param _accounts Accounts to deposit token from. * @param _vaultId ID of the target vault. */ function depositForAccounts(address[] memory _accounts, uint256 _vaultId) public override onlyStrategist { IVault vault = IVault(IController(controller).vaults(_vaultId)); require(address(vault) != address(0x0), "no vault"); address token = vault.token(); // If the account's balance is below the threshold, no op. uint256 threshold = autoSavingThreshold[token]; for (uint256 i = 0; i < _accounts.length; i++) { IAccount account = IAccount(_accounts[i]); require(account.isOperator(address(this)), "not operator"); require(autoSaving[_accounts[i]][token], "not allowed"); uint256 amount = IERC20Upgradeable(token).balanceOf(_accounts[i]); // No op if the account's balance is under threshold. if (amount < threshold) continue; account.approveToken(token, address(vault), amount); bytes memory methodData = abi.encodeWithSignature("deposit(uint256)", amount); account.invoke(address(vault), 0, methodData); emit Deposited(_accounts[i], _vaultId, token, amount); } } }
* @dev Deposits into vault on behalf of the accounts provided. This can be only called by strategist. @param _accounts Accounts to deposit token from. @param _vaultId ID of the target vault./ If the account's balance is below the threshold, no op. No op if the account's balance is under threshold.
function depositForAccounts(address[] memory _accounts, uint256 _vaultId) public override onlyStrategist { IVault vault = IVault(IController(controller).vaults(_vaultId)); require(address(vault) != address(0x0), "no vault"); address token = vault.token(); uint256 threshold = autoSavingThreshold[token]; for (uint256 i = 0; i < _accounts.length; i++) { IAccount account = IAccount(_accounts[i]); require(account.isOperator(address(this)), "not operator"); require(autoSaving[_accounts[i]][token], "not allowed"); uint256 amount = IERC20Upgradeable(token).balanceOf(_accounts[i]); if (amount < threshold) continue; account.approveToken(token, address(vault), amount); bytes memory methodData = abi.encodeWithSignature("deposit(uint256)", amount); account.invoke(address(vault), 0, methodData); emit Deposited(_accounts[i], _vaultId, token, amount); } }
5,347,669
[ 1, 758, 917, 1282, 1368, 9229, 603, 12433, 6186, 434, 326, 9484, 2112, 18, 1220, 848, 506, 1338, 2566, 635, 609, 1287, 376, 18, 225, 389, 13739, 30849, 358, 443, 1724, 1147, 628, 18, 225, 389, 26983, 548, 1599, 434, 326, 1018, 9229, 18, 19, 971, 326, 2236, 1807, 11013, 353, 5712, 326, 5573, 16, 1158, 1061, 18, 2631, 1061, 309, 326, 2236, 1807, 11013, 353, 3613, 5573, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 1290, 13971, 12, 2867, 8526, 3778, 389, 13739, 16, 2254, 5034, 389, 26983, 548, 13, 1071, 3849, 1338, 1585, 1287, 376, 288, 203, 3639, 467, 12003, 9229, 273, 467, 12003, 12, 45, 2933, 12, 5723, 2934, 26983, 87, 24899, 26983, 548, 10019, 203, 3639, 2583, 12, 2867, 12, 26983, 13, 480, 1758, 12, 20, 92, 20, 3631, 315, 2135, 9229, 8863, 203, 3639, 1758, 1147, 273, 9229, 18, 2316, 5621, 203, 3639, 2254, 5034, 5573, 273, 3656, 24660, 7614, 63, 2316, 15533, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 13739, 18, 2469, 31, 277, 27245, 288, 203, 5411, 467, 3032, 2236, 273, 467, 3032, 24899, 13739, 63, 77, 19226, 203, 5411, 2583, 12, 4631, 18, 291, 5592, 12, 2867, 12, 2211, 13, 3631, 315, 902, 3726, 8863, 203, 5411, 2583, 12, 6079, 24660, 63, 67, 13739, 63, 77, 65, 6362, 2316, 6487, 315, 902, 2935, 8863, 203, 203, 5411, 2254, 5034, 3844, 273, 467, 654, 39, 3462, 10784, 429, 12, 2316, 2934, 12296, 951, 24899, 13739, 63, 77, 19226, 203, 5411, 309, 261, 8949, 411, 5573, 13, 1324, 31, 203, 5411, 2236, 18, 12908, 537, 1345, 12, 2316, 16, 1758, 12, 26983, 3631, 3844, 1769, 203, 203, 5411, 1731, 3778, 707, 751, 273, 24126, 18, 3015, 1190, 5374, 2932, 323, 1724, 12, 11890, 5034, 2225, 16, 3844, 1769, 203, 5411, 2236, 18, 14407, 12, 2867, 12, 26983, 3631, 374, 16, 707, 751, 1769, 203, 203, 5411, 3626, 4019, 538, 16261, 24899, 13739, 63, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./interface/IScore.sol"; import "./interface/INFT.sol"; contract NFTMarket is ReentrancyGuard { using Counters for Counters.Counter; address payable public owner; address payable public score; // Score contract uint256 public buyingPoints = 100; // percentage of price to be alloted as the score uint256 public listingFee = 30; // 3% -> (30 / 1000) Counters.Counter private _currentId; struct Listing { uint256 listingId; address nft; uint256 tokenId; address payable owner; address payable seller; uint256 price; bool sold; bool onSale; } mapping(uint256 => Listing) public saleListings; mapping(address => mapping(uint256 => uint256)) royalties; event TokenListed( uint256 indexed listingId, address nft, uint256 tokenId, address payable indexed seller, uint256 price ); event TokenSold( uint256 indexed listingId, address nft, uint256 tokenId, address payable owner, address payable indexed seller, uint256 price ); event SaleCancelled( uint256 indexed listingId, address nft, uint256 tokenId ); constructor() { owner = payable(msg.sender); } // Set the address of score contract. // This needs to be done before any other actions on the contract. function setScoreContract(address scoreAddress) public onlyOwner { require(msg.sender == owner); score = payable(scoreAddress); } function listToken( address nftContract, uint256 tokenId, uint256 price ) external nonReentrant { require(INFT(nftContract).ownerOf(tokenId) == msg.sender, "NOT_OWNER"); _currentId.increment(); uint256 current = _currentId.current(); address payable seller = payable(msg.sender); saleListings[current] = Listing( current, nftContract, tokenId, payable(address(0)), seller, price, false, true ); INFT(nftContract).transferFrom(msg.sender, address(this), tokenId); IScore(score).updateScore(msg.sender, 1 ether); emit TokenListed(current, nftContract, tokenId, seller, price); } function buyToken(address nftContract, uint256 listingId) external payable nonReentrant tokenOnSale(listingId) { uint256 price = saleListings[listingId].price; uint256 tokenId = saleListings[listingId].tokenId; require(msg.value == price, "VALUE_NEQ_PRICE"); // check if amount sent is equal to the price of NFT INFT(nftContract).transferFrom(address(this), msg.sender, tokenId); // send NFT to buyer saleListings[listingId].owner = payable(msg.sender); saleListings[listingId].sold = true; saleListings[listingId].onSale = false; uint256 listingFeeAmount = (price * listingFee) / 1000; (address reciever, uint256 royalty) = INFT(nftContract).royaltyInfo( tokenId, price ); // handle royalties if (reciever == address(0)) { saleListings[listingId].seller.transfer( msg.value - listingFeeAmount ); } else { payable(reciever).transfer(royalty); saleListings[listingId].seller.transfer( msg.value - listingFeeAmount - royalty ); } // send the protocol fee payable(owner).transfer(listingFeeAmount / 2); payable(score).transfer(listingFeeAmount / 2); // Update scores for buyer and seller IScore(score).updateScore(msg.sender, (price * buyingPoints) / 1000); IScore(score).updateScore( saleListings[listingId].seller, (price * buyingPoints) / 1000 ); emit TokenSold( listingId, saleListings[listingId].nft, tokenId, owner, saleListings[listingId].seller, price ); } function cancelSale(address nftContract, uint256 listingId) external nonReentrant tokenOnSale(listingId) { require(msg.sender == saleListings[listingId].seller, "NOT_SELLER"); saleListings[listingId].onSale = false; address payable seller = saleListings[listingId].seller; uint256 tokenId = saleListings[listingId].tokenId; INFT(nftContract).transferFrom(address(this), seller, tokenId); emit SaleCancelled(listingId, saleListings[listingId].nft, tokenId); } function getListingById(uint256 listingId) public view returns (Listing memory) { return saleListings[listingId]; } // Fetches all the listings function getAllListings() public view returns (Listing[] memory) { uint256 current = _currentId.current(); Listing[] memory listings = new Listing[](current); for (uint256 i = 0; i < current; i++) { listings[i] = saleListings[i + 1]; } return listings; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier tokenOnSale(uint256 listingId) { require(saleListings[listingId].onSale == true, "NOT_ON_SALE"); _; } }
check if amount sent is equal to the price of NFT
require(msg.value == price, "VALUE_NEQ_PRICE");
1,800,709
[ 1, 1893, 309, 3844, 3271, 353, 3959, 358, 326, 6205, 434, 423, 4464, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 3576, 18, 1132, 422, 6205, 16, 315, 4051, 67, 5407, 53, 67, 7698, 1441, 8863, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // 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 Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract Lending is Ownable, Pausable { using SafeMath for uint256; uint256 public minContribAmount = 0.1 ether; // 0.01 ether enum LendingState {AcceptingContributions, AwaitingReturn, ProjectNotFunded, ContributionReturned} mapping(address => Investor) public investors; uint256 public fundingStartTime; // Start time of contribution period in UNIX time uint256 public fundingEndTime; // End time of contribution period in UNIX time uint256 public totalContributed; bool public capReached; LendingState public state; address[] public investorsKeys; uint256 public lendingInterestRatePercentage; uint256 public totalLendingAmount; uint256 public lendingDays; uint256 public initialFiatPerEthRate; uint256 public totalLendingFiatAmount; address public borrower; uint256 public borrowerReturnDate; uint256 public borrowerReturnFiatAmount; uint256 public borrowerReturnFiatPerEthRate; uint256 public borrowerReturnAmount; struct Investor { uint amount; bool isCompensated; } // events event onCapReached(uint endTime); event onContribution(uint totalContributed, address indexed investor, uint amount, uint investorsCount); event onCompensated(address indexed contributor, uint amount); event excessContributionReturned(address indexed contributor, uint amount); event StateChange(uint state); function Lending(uint _fundingStartTime, uint _fundingEndTime, address _borrower, uint _lendingInterestRatePercentage, uint _totalLendingAmount, uint256 _lendingDays) public { fundingStartTime = _fundingStartTime; fundingEndTime = _fundingEndTime; borrower = _borrower; // 115 lendingInterestRatePercentage = _lendingInterestRatePercentage; totalLendingAmount = _totalLendingAmount; //90 days for version 0.1 lendingDays = _lendingDays; state = LendingState.AcceptingContributions; StateChange(uint(state)); } function() public payable whenNotPaused { if(state == LendingState.AwaitingReturn){ returnBorroweedEth(); } else{ contributeWithAddress(msg.sender); } } function isContribPeriodRunning() public constant returns(bool){ return fundingStartTime <= now && fundingEndTime > now && !capReached; } // @notice Function to participate in contribution period // Amounts from the same address should be added up // If cap is reached, end time should be modified // Funds should be transferred into multisig wallet // @param contributor Address function contributeWithAddress(address contributor) public payable whenNotPaused { require(msg.value >= minContribAmount); require(isContribPeriodRunning()); uint contribValue = msg.value; uint excessContribValue = 0; uint oldTotalContributed = totalContributed; totalContributed = oldTotalContributed.add(contribValue); uint newTotalContributed = totalContributed; // cap was reached if (newTotalContributed >= totalLendingAmount && oldTotalContributed < totalLendingAmount) { capReached = true; fundingEndTime = now; onCapReached(fundingEndTime); // Everything above hard cap will be sent back to contributor excessContribValue = newTotalContributed.sub(totalLendingAmount); contribValue = contribValue.sub(excessContribValue); totalContributed = totalLendingAmount; } if (investors[contributor].amount == 0) { investorsKeys.push(contributor); } investors[contributor].amount = investors[contributor].amount.add(contribValue); if (excessContribValue > 0) { msg.sender.transfer(excessContribValue); excessContributionReturned(msg.sender, excessContribValue); } onContribution(newTotalContributed, contributor, contribValue, investorsKeys.length); } function enableReturnContribution() external onlyOwner { require(totalContributed < totalLendingAmount); require(now > fundingEndTime); state = LendingState.ProjectNotFunded; StateChange(uint(state)); } // @notice Function to participate in contribution period // Amounts from the same address should be added up // If cap is reached, end time should be modified // Funds should be transferred into multisig wallet // @param contributor Address function finishContributionPeriod(uint256 _initialFiatPerEthRate) onlyOwner { require(capReached == true); initialFiatPerEthRate = _initialFiatPerEthRate; borrower.transfer(totalContributed); state = LendingState.AwaitingReturn; StateChange(uint(state)); totalLendingFiatAmount = totalLendingAmount.mul(initialFiatPerEthRate); borrowerReturnFiatAmount = totalLendingFiatAmount.mul(lendingInterestRatePercentage).div(100); } function reclaimContribution(address beneficiary) external { require(state == LendingState.ProjectNotFunded); uint contribution = investors[beneficiary].amount; require(contribution > 0); beneficiary.transfer(contribution); } function establishBorrowerReturnFiatPerEthRate(uint256 _borrowerReturnFiatPerEthRate) external onlyOwner{ require(state == LendingState.AwaitingReturn); borrowerReturnFiatPerEthRate = _borrowerReturnFiatPerEthRate; borrowerReturnAmount = borrowerReturnFiatAmount.div(borrowerReturnFiatPerEthRate); } function returnBorroweedEth() payable public { require(state == LendingState.AwaitingReturn); require(borrowerReturnFiatPerEthRate > 0); require(msg.value == borrowerReturnAmount); state = LendingState.ContributionReturned; StateChange(uint(state)); } function reclaimContributionWithInterest(address beneficiary) external { require(state == LendingState.ContributionReturned); uint contribution = investors[beneficiary].amount.mul(initialFiatPerEthRate).mul(lendingInterestRatePercentage).div(borrowerReturnFiatPerEthRate).div(100); require(contribution > 0); beneficiary.transfer(contribution); } function selfKill() external onlyOwner { selfdestruct(owner); } }
End time of contribution period in UNIX time
uint256 public fundingEndTime;
1,512,315
[ 1, 1638, 813, 434, 24880, 3879, 316, 23160, 813, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 22058, 25255, 31, 4766, 3639, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/8453/0x5Ba641A1Fa1E6A7D033c9f6A8108d52B92b78257/sources/contracts/HATVaultsRegistry.sol
* @notice See {IHATVaultsRegistry-getSafetyPeriod}. */
function getSafetyPeriod() external view returns (uint256) { return generalParameters.safetyPeriod; }
11,548,687
[ 1, 9704, 288, 45, 44, 789, 12003, 87, 4243, 17, 588, 26946, 14369, 5027, 5496, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1322, 1727, 14369, 5027, 1435, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 7470, 2402, 18, 87, 1727, 14369, 5027, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x818bab157DA988549F570E6E71aC8C6C68719B26/sources/DeadBears.sol
* the Metadata extension. Built to optimize for lower gas during batch mints. Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). Assumes that an owner cannot have more than 264 - 1 (max value of uint64) of supply. Assumes that the maximum token id cannot exceed 2256 - 1 (max value of uint256)./ Mask of an entry in packed address data. The bit position of `numberMinted` in packed address data. The bit position of `numberBurned` in packed address data. The bit position of `aux` in packed address data. Mask of all 256 bits in packed address data except the 64 bits for `aux`. The bit position of `startTimestamp` in packed ownership. The bit mask of the `burned` bit in packed ownership. The bit position of the `nextInitialized` bit in packed ownership. The bit mask of the `nextInitialized` bit in packed ownership. The tokenId of the next token to be minted. The number of tokens burned. Token name Token symbol Mapping from token ID to ownership details An empty struct value does not necessarily mean the token is unowned. See `_packedOwnershipOf` implementation for details. Bits Layout: - [0..159] `addr` - [160..223] `startTimestamp` - [224] `burned` - [225] `nextInitialized` Mapping owner address to address data. Bits Layout: - [0..63] `balance` - [64..127] `numberMinted` - [128..191] `numberBurned` - [192..255] `aux` Mapping from token ID to approved address. Mapping from owner to operator approvals
contract ERC721A is IERC721A { uint256 private constant BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1; uint256 private constant BITPOS_NUMBER_MINTED = 64; uint256 private constant BITPOS_NUMBER_BURNED = 128; uint256 private constant BITPOS_AUX = 192; uint256 private constant BITMASK_AUX_COMPLEMENT = (1 << 192) - 1; uint256 private constant BITPOS_START_TIMESTAMP = 160; uint256 private constant BITMASK_BURNED = 1 << 224; uint256 private constant BITPOS_NEXT_INITIALIZED = 225; uint256 private constant BITMASK_NEXT_INITIALIZED = 1 << 225; uint256 private _currentIndex; uint256 private _burnCounter; string private _name; string private _symbol; mapping(uint256 => uint256) private _packedOwnerships; mapping(address => uint256) private _packedAddressData; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; function totalSupply() external view returns (uint256); function supportsInterface(bytes4 interfaceId) external view returns (bool); event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function setApprovalForAll(address operator, bool _approved) external; function getApproved(uint256 tokenId) external view returns (address operator); function isApprovedForAll(address owner, address operator) external view returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); } pragma solidity ^0.8.4; } constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } function _startTokenId() internal view virtual returns (uint256) { return 0; } function _nextTokenId() internal view returns (uint256) { return _currentIndex; } function totalSupply() public view override returns (uint256) { unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } function totalSupply() public view override returns (uint256) { unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } function _totalMinted() internal view returns (uint256) { unchecked { return _currentIndex - _startTokenId(); } } function _totalMinted() internal view returns (uint256) { unchecked { return _currentIndex - _startTokenId(); } } function _totalBurned() internal view returns (uint256) { return _burnCounter; } function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return } function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return _packedAddressData[owner] & BITMASK_ADDRESS_DATA_ENTRY; } function _numberMinted(address owner) internal view returns (uint256) { return (_packedAddressData[owner] >> BITPOS_NUMBER_MINTED) & BITMASK_ADDRESS_DATA_ENTRY; } function _numberBurned(address owner) internal view returns (uint256) { return (_packedAddressData[owner] >> BITPOS_NUMBER_BURNED) & BITMASK_ADDRESS_DATA_ENTRY; } function _getAux(address owner) internal view returns (uint64) { return uint64(_packedAddressData[owner] >> BITPOS_AUX); } function _setAux(address owner, uint64 aux) internal { uint256 packed = _packedAddressData[owner]; uint256 auxCasted; auxCasted := aux } packed = (packed & BITMASK_AUX_COMPLEMENT) | (auxCasted << BITPOS_AUX); _packedAddressData[owner] = packed; }
16,090,541
[ 1, 5787, 6912, 2710, 18, 27376, 358, 10979, 364, 2612, 16189, 4982, 2581, 312, 28142, 18, 25374, 2734, 87, 854, 695, 6979, 6261, 312, 474, 329, 5023, 622, 389, 1937, 1345, 548, 1435, 261, 7606, 358, 374, 16, 425, 18, 75, 18, 374, 16, 404, 16, 576, 16, 890, 838, 2934, 25374, 716, 392, 3410, 2780, 1240, 1898, 2353, 576, 1105, 300, 404, 261, 1896, 460, 434, 2254, 1105, 13, 434, 14467, 18, 25374, 716, 326, 4207, 1147, 612, 2780, 9943, 576, 5034, 300, 404, 261, 1896, 460, 434, 2254, 5034, 2934, 19, 16698, 434, 392, 1241, 316, 12456, 1758, 501, 18, 1021, 2831, 1754, 434, 1375, 2696, 49, 474, 329, 68, 316, 12456, 1758, 501, 18, 1021, 2831, 1754, 434, 1375, 2696, 38, 321, 329, 68, 316, 12456, 1758, 501, 18, 1021, 2831, 1754, 434, 1375, 18196, 68, 316, 12456, 1758, 501, 18, 16698, 434, 777, 8303, 4125, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 4232, 39, 27, 5340, 37, 353, 467, 654, 39, 27, 5340, 37, 288, 203, 565, 2254, 5034, 3238, 5381, 20469, 11704, 67, 15140, 67, 4883, 67, 19083, 273, 261, 21, 2296, 5178, 13, 300, 404, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 20469, 7057, 67, 9931, 67, 6236, 6404, 273, 5178, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 20469, 7057, 67, 9931, 67, 38, 8521, 2056, 273, 8038, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 20469, 7057, 67, 14237, 60, 273, 20217, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 20469, 11704, 67, 14237, 60, 67, 10057, 7618, 273, 261, 21, 2296, 20217, 13, 300, 404, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 20469, 7057, 67, 7570, 67, 17201, 273, 25430, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 20469, 11704, 67, 38, 8521, 2056, 273, 404, 2296, 576, 3247, 31, 203, 377, 203, 565, 2254, 5034, 3238, 5381, 20469, 7057, 67, 25539, 67, 12919, 25991, 273, 28298, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 20469, 11704, 67, 25539, 67, 12919, 25991, 273, 404, 2296, 28298, 31, 203, 203, 565, 2254, 5034, 3238, 389, 2972, 1016, 31, 203, 203, 565, 2254, 5034, 3238, 389, 70, 321, 4789, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 203, 565, 533, 3238, 389, 7175, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 3238, 389, 2920, 329, 5460, 12565, 87, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 2920, 329, 1887, 2 ]
pragma solidity 0.4.21; // Tipbot, Crypto For Everyone // Contract Owner - Tipbot - 0x72BA45c9e729f13CD2F6AA4B410f83bE1410E982 // Official Website - http://www.Tipbot.io // Official Twitter - http://www.twitter.com/officialtipbot // Official Reddit - http://www.reddit.com/r/officialtipbot // Official Telegram - http://www.t.me/officialtipbot/ // Contract Developed By - Tipbot LTD 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); uint256 c = a / b; // assert(a == b * c + a % b); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); owner = newOwner; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract tipbotreg { uint256 public stakeCommence; uint256 public stakeMinAge; uint256 public stakeMaxAge; function mint() public returns (bool); function coinAge() public payable returns (uint256); function annualInterest() public view returns (uint256); event Mint(address indexed _address, uint _reward); } // Initial Configuration contract tipbot is ERC20,tipbotreg,Ownable { using SafeMath for uint256; string public name = "tipbot"; string public symbol = "TIP"; uint public decimals = 18; uint public stakeCommence; //Proof Of Stake Start Timestamp uint public stakeMinAge = 3 days; // Minimum Age For Coin Age: 3 days uint public stakeMaxAge = 90 days; // Maximimum age for coin age: 90 days uint public maxMintPoS = 10**17; // Proof Of Stake default interest equates to 10% annually uint public chainStartTime; // The timestamp in which the chain starts uint public chainStartBlock; //The block number in which the chain starts uint public totalSupply; uint public maxTIPSupply; uint public initialTIPsupply; struct transferInStruct{ uint256 amount; uint64 time; } mapping(address => uint256) balances; mapping(address => mapping (address => uint256)) allowed; mapping(address => transferInStruct[]) transferIns; event Burn(address indexed burner, uint256 value); modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4); _; } modifier canTIPMint() { require(totalSupply < maxTIPSupply); _; } function tipbot() public { // 104 Billion Token Initial Supply initialTIPsupply = 104000000000000000000000000000; // 375 Billion Maximum Token Supply. maxTIPSupply = 375000000000000000000000000000; chainStartTime = block.timestamp; chainStartBlock = block.number; balances[msg.sender] = initialTIPsupply; totalSupply = initialTIPsupply; } // Transfer Function function transfer(address _to, uint256 _value) public onlyPayloadSize(2 * 32) returns (bool) { if(msg.sender == _to) return mint(); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender]; uint64 _now = uint64(block.timestamp); transferIns[msg.sender].push(transferInStruct(uint256(balances[msg.sender]),_now)); transferIns[_to].push(transferInStruct(uint256(_value),_now)); return true; } // Balance Function function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } // Transfer Function function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3 * 32) returns (bool) { require(_to != address(0)); uint256 _allowance = allowed[_from][msg.sender]; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); if(transferIns[_from].length > 0) delete transferIns[_from]; uint64 _now = uint64(block.timestamp); transferIns[_from].push(transferInStruct(uint256(balances[_from]),_now)); transferIns[_to].push(transferInStruct(uint256(_value),_now)); return true; } // PoS must be manually triggered by the contract creator using a UNIX timestamp. It is advisable to set the timestamp 15 minutes ahead of time to prevent failure function ownerSetStakeCommence(uint timestamp) public onlyOwner { require((stakeCommence <= 0) && (timestamp >= chainStartTime)); stakeCommence = timestamp; } //approve function function approve(address _spender, uint256 _value) public returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } // Mint Function function mint() public canTIPMint returns (bool) { if(balances[msg.sender] <= 0) return false; if(transferIns[msg.sender].length <= 0) return false; uint reward = getPoSReward(msg.sender); if(reward <= 0) return false; totalSupply = totalSupply.add(reward); balances[msg.sender] = balances[msg.sender].add(reward); delete transferIns[msg.sender]; transferIns[msg.sender].push(transferInStruct(uint256(balances[msg.sender]),uint64(block.timestamp))); emit Mint(msg.sender, reward); return true; } function getBlockNumber() public view returns (uint blockNumber) { blockNumber = block.number.sub(chainStartBlock); } // Coin Age Function function coinAge() public payable returns (uint myCoinAge) { myCoinAge = getCoinAge(msg.sender,block.timestamp); } // Annual Interest Function function annualInterest() public view returns(uint interest) { uint _now = block.timestamp; interest = maxMintPoS; if((_now.sub(stakeCommence)).div(365 days) == 0) { interest = (770 * maxMintPoS).div(100); } else if((_now.sub(stakeCommence)).div(365 days) == 1){ interest = (435 * maxMintPoS).div(100); } } // Stake Reward Function function getPoSReward(address _address) internal view returns (uint) { require( (block.timestamp >= stakeCommence) && (stakeCommence > 0) ); uint _now = block.timestamp; uint _coinAge = getCoinAge(_address, _now); if(_coinAge <= 0) return 0; uint interest = maxMintPoS; if((_now.sub(stakeCommence)).div(365 days) == 0) { interest = (770 * maxMintPoS).div(100); } else if((_now.sub(stakeCommence)).div(365 days) == 1){ // 2nd year effective annual interest rate is 50% interest = (435 * maxMintPoS).div(100); } return (_coinAge * interest).div(365 * (10**decimals)); } function getCoinAge(address _address, uint _now) internal view returns (uint _coinAge) { if(transferIns[_address].length <= 0) return 0; for (uint i = 0; i < transferIns[_address].length; i++){ if( _now < uint(transferIns[_address][i].time).add(stakeMinAge) ) continue; uint nCoinSeconds = _now.sub(uint(transferIns[_address][i].time)); if( nCoinSeconds > stakeMaxAge ) nCoinSeconds = stakeMaxAge; _coinAge = _coinAge.add(uint(transferIns[_address][i].amount) * nCoinSeconds.div(1 days)); } } // Batch Transfer Function function batchTransfer(address[] _recipients, uint[] _values) public onlyOwner returns (bool) { require( _recipients.length > 0 && _recipients.length == _values.length); uint total = 0; for(uint i = 0; i < _values.length; i++){ total = total.add(_values[i]); } require(total <= balances[msg.sender]); uint64 _now = uint64(block.timestamp); for(uint j = 0; j < _recipients.length; j++){ balances[_recipients[j]] = balances[_recipients[j]].add(_values[j]); transferIns[_recipients[j]].push(transferInStruct(uint256(_values[j]),_now)); emit Transfer(msg.sender, _recipients[j], _values[j]); } balances[msg.sender] = balances[msg.sender].sub(total); if(transferIns[msg.sender].length > 0) delete transferIns[msg.sender]; if(balances[msg.sender] > 0) transferIns[msg.sender].push(transferInStruct(uint256(balances[msg.sender]),_now)); return true; } // Batch Token Function function TokenBurn(uint _value) public onlyOwner { require(_value > 0); balances[msg.sender] = balances[msg.sender].sub(_value); delete transferIns[msg.sender]; transferIns[msg.sender].push(transferInStruct(uint256(balances[msg.sender]),uint64(block.timestamp))); totalSupply = totalSupply.sub(_value); initialTIPsupply = initialTIPsupply.sub(_value); maxTIPSupply = maxTIPSupply.sub(_value*10); emit Burn(msg.sender, _value); } }
Proof Of Stake default interest equates to 10% annually
uint public maxMintPoS = 10**17;
1,509,200
[ 1, 20439, 8031, 934, 911, 805, 16513, 1298, 815, 358, 1728, 9, 8226, 3452, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 1071, 943, 49, 474, 29198, 55, 273, 1728, 636, 4033, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import '@openzeppelin/contracts/utils/Address.sol'; import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; /// @title simple voting + project proposal dapp /// @author Taehoon Kim contract Voting is ReentrancyGuard{ /// @notice implements both project suggestion and voting /// @notice imports Openzeppelin libraries as safety measures. /// @notice For this specific usage, SafeMath might have been not that necessary using Address for address; using SafeMath for uint256; using SafeMath for int256; /// @notice 'Project' struct variable definition. /// @notice stores both the description of the project and vote results struct Project{ string description; uint256 total_votes; // total votes = likes + dislikes + unsure uint256 likes; uint256 dislikes; uint256 unsure; } ///@notice public variables mapping(uint256 => mapping(address => bool)) public Proj_to_voted; // mapping var. to check whether a user voted for the project(proposal) address public Owner; // owner of the contract mapping(uint256 => Project) public Projects; // project id -> project mapping(address => uint256) public Proposed; // counting how many projects/proposals were suggested by a user uint256 public Project_num; // variable to track the number of proposals suggested (from all users) uint256 public Proposal_limit; // per-person limit for suggesting new proposals ///@notice initialization, sets 1) the owner, 2) per-person proposal limit 3) starting number of proposals (zero..) constructor(){ Owner = msg.sender; Proposal_limit=3; Project_num = 0; } //modifiers ///@notice checking if msg. sender is the owner modifier isOwner(){ require(Owner == msg.sender, "you need to be the owner to execute this function"); _; } ///@notice checking if msg. sender has already voted for the proposal ///@param proj_id id of the project modifier not_voted_for(uint256 proj_id){ require(Proj_to_voted[proj_id][msg.sender] ==false, "you've already voted for this project"); _; } ///@notice checking if msg.sender hasn't gone over the proposal limit ///@param add address of the msg.sender modifier less_than_limit(address add){ require(Proposed[add]<= Proposal_limit-1, "exceeding the upper limit for number of proposable projects"); _; } /// @notice checking if msg.sender is trying to vote for non-existing projects. /// @param proj_id id alias of the project to vote modifier existing_proj(uint256 proj_id){ require(proj_id <= Project_num-1, "project id exceeds the number of existing projects!"); _; } //events ///@notice logging if a project was successfully proposed(submitted...) ///@notice input parameters follow the struct definition of 'Project' variable. event registered_project(uint256 project_num, string description, uint256 total_votes, uint256 likes, uint256 dislikes, uint256 unsure); ///@notice logging when there is an increase in the number of proposed projects ///@param project_num integer value that tracks the number of projects event increased_proj_num(uint256 project_num); ///@notice logging if there is an increase in the number of proposed projects per user. ///@param proposed_num integer value that tracks the number of proposals per user event increased_proj_proposed(uint256 proposed_num); ///@notice logging if the voting was successfully done ///@param proj_id, project id and @param add msg.sender address event Voted(uint256 proj_id, address add); ///@notice logging the change in the upper limit for the number of proposals that can be suggested per person ///@param limit_val new integer value for the limit event changed_proposal_limit(uint256 limit_val); ///@notice logging if the voting was possible for that user (similar to the above "Voted" event) ///@notice only difference being that this event gets triggered right after voting function is triggered. ///@param proj_id id and @param add msg.sender address event logging_vote(uint256 proj_id, address add); //functions ///@notice main function to add project / proposal ///@param description string input to describe the project / proposal function add_project(string memory description) public less_than_limit(msg.sender) nonReentrant{ Projects[Project_num] = Project(description, 0,0,0,0); emit registered_project(Project_num, description, 0,0,0,0); Project_num++; //increment by 1 emit increased_proj_num(Project_num); Proposed[msg.sender]++; emit increased_proj_proposed(Proposed[msg.sender]); } ///@notice main function to cast a vote ///@param proj_id project id and @param vote_value vote values (1: like, 0 : indifferent, -1 : dislike) function vote(uint256 proj_id, int256 vote_value) public existing_proj(proj_id) not_voted_for(proj_id) nonReentrant{ Proj_to_voted[proj_id][msg.sender] = true; emit logging_vote(proj_id, msg.sender); Projects[proj_id].total_votes++; if(vote_value==-1){ Projects[proj_id].dislikes++; } else if(vote_value==1){ Projects[proj_id].likes++; } else if(vote_value==0){ Projects[proj_id].unsure++; } emit Voted(proj_id, msg.sender); } ///@notice function to change the upper limit (number of per-person proposable projects) ///@notice can only be triggered by the owner of the contract ///@param limit_val integer for the new limit ///@return the changed limit function change_proposal_limit(uint256 limit_val) public isOwner() returns (uint256){ Proposal_limit = limit_val; emit changed_proposal_limit(limit_val); return Proposal_limit; } ///@notice function to get number of currently existing projects ///@return number of existing projects function get_project_num() public view returns (uint256){ return Project_num; } ///@notice function to get current limit (per-person proposable number of projects) ///@return current upper limit function get_proposal_limit() public view returns (uint256){ return Proposal_limit; } }
variable to track the number of proposals suggested (from all users)
uint256 public Project_num;
7,222,700
[ 1, 6105, 358, 3298, 326, 1300, 434, 450, 22536, 22168, 261, 2080, 777, 3677, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 5420, 67, 2107, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2020 Swap Holdings Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.5.12; pragma experimental ABIEncoderV2; import "@airswap/swap/contracts/interfaces/ISwap.sol"; import "@airswap/delegate/contracts/interfaces/IDelegate.sol"; import "@airswap/tokens/contracts/interfaces/IWETH.sol"; /** * @title Wrapper: Send and receive ether for WETH trades */ contract Wrapper { // The Swap contract to settle trades ISwap public swapContract; // The WETH contract to wrap ether IWETH public wethContract; /** * @notice Contract Constructor * @param wrapperSwapContract address * @param wrapperWethContract address */ constructor(address wrapperSwapContract, address wrapperWethContract) public { swapContract = ISwap(wrapperSwapContract); wethContract = IWETH(wrapperWethContract); } /** * @notice Required when withdrawing from WETH * @dev During unwraps, WETH.withdraw transfers ether to msg.sender (this contract) */ function() external payable { // Ensure the message sender is the WETH contract. if (msg.sender != address(wethContract)) { revert("DO_NOT_SEND_ETHER"); } } /** * @notice Send an Order to be forwarded to Swap * @dev Sender must authorize this contract on the swapContract * @dev Sender must approve this contract on the wethContract * @param order Types.Order The Order */ function swap(Types.Order calldata order) external payable { // Ensure msg.sender is sender wallet. require( order.sender.wallet == msg.sender, "MSG_SENDER_MUST_BE_ORDER_SENDER" ); // Ensure that the signature is present. // The signature will be explicitly checked in Swap. require(order.signature.v != 0, "SIGNATURE_MUST_BE_SENT"); // Wraps ETH to WETH when the sender provides ETH and the order is WETH _wrapEther(order.sender); // Perform the swap. swapContract.swap(order); // Unwraps WETH to ETH when the sender receives WETH _unwrapEther(order.sender.wallet, order.signer.token, order.signer.amount); } /** * @notice Send an Order to be forwarded to a Delegate * @dev Sender must authorize the Delegate contract on the swapContract * @dev Sender must approve this contract on the wethContract * @dev Delegate's tradeWallet must be order.sender - checked in Delegate * @param order Types.Order The Order * @param delegate IDelegate The Delegate to provide the order to */ function provideDelegateOrder(Types.Order calldata order, IDelegate delegate) external payable { // Ensure that the signature is present. // The signature will be explicitly checked in Swap. require(order.signature.v != 0, "SIGNATURE_MUST_BE_SENT"); // Wraps ETH to WETH when the signer provides ETH and the order is WETH _wrapEther(order.signer); // Provide the order to the Delegate. delegate.provideOrder(order); // Unwraps WETH to ETH when the signer receives WETH _unwrapEther(order.signer.wallet, order.sender.token, order.sender.amount); } /** * @notice Wraps ETH to WETH when a trade requires it * @param party Types.Party The side of the trade that may need wrapping */ function _wrapEther(Types.Party memory party) internal { // Check whether ether needs wrapping if (party.token == address(wethContract)) { // Ensure message value is param. require(party.amount == msg.value, "VALUE_MUST_BE_SENT"); // Wrap (deposit) the ether. wethContract.deposit.value(msg.value)(); // Transfer the WETH from the wrapper to party. // Return value not checked - WETH throws on error and does not return false wethContract.transfer(party.wallet, party.amount); } else { // Ensure no unexpected ether is sent. require(msg.value == 0, "VALUE_MUST_BE_ZERO"); } } /** * @notice Unwraps WETH to ETH when a trade requires it * @dev The unwrapping only succeeds if recipientWallet has approved transferFrom * @param recipientWallet address The trade recipient, who may have received WETH * @param receivingToken address The token address the recipient received * @param amount uint256 The amount of token the recipient received */ function _unwrapEther( address recipientWallet, address receivingToken, uint256 amount ) internal { // Check whether ether needs unwrapping if (receivingToken == address(wethContract)) { // Transfer weth from the recipient to the wrapper. wethContract.transferFrom(recipientWallet, address(this), amount); // Unwrap (withdraw) the ether. wethContract.withdraw(amount); // Transfer ether to the recipient. // solium-disable-next-line security/no-call-value (bool success, ) = recipientWallet.call.value(amount)(""); require(success, "ETH_RETURN_FAILED"); } } }
* @notice Send an Order to be forwarded to a Delegate @dev Sender must authorize the Delegate contract on the swapContract @dev Sender must approve this contract on the wethContract @dev Delegate's tradeWallet must be order.sender - checked in Delegate @param order Types.Order The Order @param delegate IDelegate The Delegate to provide the order to/ Ensure that the signature is present. The signature will be explicitly checked in Swap. Wraps ETH to WETH when the signer provides ETH and the order is WETH Provide the order to the Delegate. Unwraps WETH to ETH when the signer receives WETH
function provideDelegateOrder(Types.Order calldata order, IDelegate delegate) external payable { require(order.signature.v != 0, "SIGNATURE_MUST_BE_SENT"); _wrapEther(order.signer); delegate.provideOrder(order); _unwrapEther(order.signer.wallet, order.sender.token, order.sender.amount); }
14,067,533
[ 1, 3826, 392, 4347, 358, 506, 19683, 358, 279, 27687, 225, 15044, 1297, 12229, 326, 27687, 6835, 603, 326, 7720, 8924, 225, 15044, 1297, 6617, 537, 333, 6835, 603, 326, 341, 546, 8924, 225, 27687, 1807, 18542, 16936, 1297, 506, 1353, 18, 15330, 300, 5950, 316, 27687, 225, 1353, 7658, 18, 2448, 1021, 4347, 225, 7152, 1599, 292, 4784, 1021, 27687, 358, 5615, 326, 1353, 358, 19, 7693, 716, 326, 3372, 353, 3430, 18, 1021, 3372, 903, 506, 8122, 5950, 316, 12738, 18, 678, 7506, 512, 2455, 358, 678, 1584, 44, 1347, 326, 10363, 8121, 512, 2455, 471, 326, 1353, 353, 678, 1584, 44, 26569, 326, 1353, 358, 326, 27687, 18, 1351, 91, 7506, 678, 1584, 44, 358, 512, 2455, 1347, 326, 10363, 17024, 678, 1584, 44, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 5615, 9586, 2448, 12, 2016, 18, 2448, 745, 892, 1353, 16, 1599, 292, 4784, 7152, 13, 203, 565, 3903, 203, 565, 8843, 429, 203, 225, 288, 203, 565, 2583, 12, 1019, 18, 8195, 18, 90, 480, 374, 16, 315, 26587, 67, 49, 5996, 67, 5948, 67, 17418, 8863, 203, 203, 565, 389, 4113, 41, 1136, 12, 1019, 18, 2977, 264, 1769, 203, 203, 565, 7152, 18, 685, 6768, 2448, 12, 1019, 1769, 203, 203, 565, 389, 318, 4113, 41, 1136, 12, 1019, 18, 2977, 264, 18, 19177, 16, 1353, 18, 15330, 18, 2316, 16, 1353, 18, 15330, 18, 8949, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x8252f8C3B1e0b85f26c93908A8224D10C6a2105f/sources/contracts/GeneticChain721.sol
* Get total gallery has minted./
function gallryMinted() public view returns (uint256) { return _state._gallery; }
4,045,763
[ 1, 967, 2078, 13624, 711, 312, 474, 329, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 314, 454, 1176, 49, 474, 329, 1435, 203, 3639, 1071, 1476, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 327, 389, 2019, 6315, 21454, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x3f5505f41342E3c8e92C8e47d366713Cf609263a/sources/contracts/interfaces/BazaarStorage.sol
Address of the global royalty engine being used.
IRoyaltyEngineV1 public royaltyEngine;
1,956,050
[ 1, 1887, 434, 326, 2552, 721, 93, 15006, 4073, 3832, 1399, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 15908, 13372, 15006, 4410, 58, 21, 1071, 721, 93, 15006, 4410, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/100/0x2b64d24a180b4247F765FFA832113473Fb938237/sources/contracts/MiniChefV2.sol
@param _reward The REWARD token contract address.
constructor(IERC20 _reward) public { REWARD = _reward; }
14,268,825
[ 1, 67, 266, 2913, 1021, 2438, 21343, 1147, 6835, 1758, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 45, 654, 39, 3462, 389, 266, 2913, 13, 1071, 288, 203, 3639, 2438, 21343, 273, 389, 266, 2913, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: None pragma solidity ^0.8.8; // ####BPPG#&&&&############BGPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP5 // ##BPYP5YGGGBBB#######BBGGGGGBGPPPPPGPPPPPPPPPPPPPPPPPPPPPPPPPGGPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP5555555555555555555555555555555555555PPPPPPPPPPPPPPPPP5 // BBG?J#GP&B5G#@@@@@@@@@@@@@@@@&BGPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP5PPPPPPPPPPPPPPPPPPPPP5YYYJYYYYJJJJJJJJJJJJJJYYYYYYYYYYY555555555YYYYY55PPPPP5 // &&B?Y##B##BYB#&@@@@@@@@@@@@@@@@&BGPPPPPPPPPPPPPPPPPPB#PPP5555555YYY55PPP55555555PGGBBGPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP55YJJPPPP5 // &&B?Y###&#B5PBGG#@@@@@@@@@@@@@@@@&BGPPPPPPPPPPPPPPPPGG5555555555YYYJJJJJJJJ?JJJ????JYPBBPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPGGPPPPPPPPPPPPPPPPP5?YPPP5 // #&B?5#BB##B5Y5PP5G#@@@@@@@@@@@&&&&@&BGPPPPPPPPPPGGPP5YYJJJJJJJJJJJJJ????JJ?77JJJJJJJ???YBBPPPPPPPPPPPPPPPPPGPPP5PPPPPPPPPPPPGGPPPPPPPPPPPPPPPPP5??5PP5 // ~!P?5BBB##BBBYJ5PPB5B&@@&&@@@@@@@@@@@@#GPPPPPPPB5JJJJJJ????????JJJ?7777?JJJ??JJJJJJJJJJ7?GBPPPPPPPPPPPPPPPPPPP5PPPPPPPPPPPPPPPPP5PPPPGBPPPPPPPPJJY5PP5 // #7.!G&####BYG&BYYYP55B#&@@@@@@@@@@@@@@@@#GPPPPBY?JJJJJJ???????JJJJJ?????JJJJJJJJJJJJJJJJ?7PBPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPGP?Y55PP5 // PY???JP#@#B5PPGBBPYJ5PGGB&@@@@@@@@@@@@@@@@#GG#YJJJJJJJJJJ???JJJJJJ???????JJJJJJJJYJJYJJJ55?5GPPPPPPPPPPPPPPPP5PPPPPGBPPPPPPPPPPPPPPPPPPPPPPPPBG?555PP5 // !!!????!Y&&BGBGP5B#GYY5PPPG&@@@@@@@@@@@@@@&B#GP5YYJJJJJJJJJJJJJJJJJJ?JJJJYYJJJJJJYYYYY5PPPPYPGPPPPPPPPPPPPPP5PPPPPPPPPPPPPPPPPP5PPPPPPPPPPPPPPY?555PP5 // ^^^!???P?~Y&&###BP5G#PJY5P5PP#@@@@@@@@@@@@###BGGPPP55YYJJJ?JJJJJJYYYJJJJJYJ????JJJJY5PPPPPB#GGYPPPPPPPPPPP555PPPPPPPPPPPPPPPPPP5PPPPPPPPPPPPPPY?555PP5 // ^^^!??~^?5J~5&&###BG5GBPYY5P55G&@@@@@@@@@&######BBGGGPP5PP555YYY555PYYYYYJ?JYY5P5JJ555PPPB####Y7?????????JJ?????????77??????YJ?????????77????????????7 // ^^^!??~^^^55!!J#&&###55GBB#5Y5PGG#@@@@@@@@&&#######B#BBGGBGPPPGGP5PPGGGY7!!JPGP5YYJYYYPPP####&G??J?JJ???YGGY??????J?~~7J???JGGJ?J????J?~!????J??J??JJ? // ^^^!?7^^^^^!?PJ!?#&###GP5G#BYJ5PP5G#@@@@@&&@&######BB###B#GPPPBBG5555?YJ??J?YP?!!?YJJJGGG####&#J??J??JJ????????????JJJJ?????????J?????JJJ???J???J??JJ? // J7^~??^^^^^::^75Y!J#&#[email protected]@@&@@@&######B###GGB#GPGGPPPP5J?JPPG5J55YY5P5PPGBB#####&YJ?J??J???????????????????????J??J????5BJ????J???77JJJ? // :?5J??^^^^^^:.:^75J7?G&####G5PBB5JY5P55B&&&@@@&#####B###BGB##BPPPPP55P5YYY5JJ75GPPPPPPPGB#####&BY??JJ????????????????????????J??J????JYJ????J??????JJ? // ^::7???^^^^!!~:.!GJ5Y~7P&&BGYP5P#BG#B5PBB&&@@@@#####B####B#####GPPYJ5PP5Y555YJ5GPPPPPPG#######&&#Y7!7J??????????????????????????J???????????J??????JJ? // ??!^??5P!^^!!!!~~!::?5Y77G&#GG#G5PB&PJYP5&&&@@@&####B#####B######GGPPPPP55Y5PGPPPPPPPG########&&&B??????????????????????J???????J?????????????J????JJ? // 777???^^Y5~!!!!!!!^..^~J5?7G&#B##BP5GB5YYB&&&@@@####B#####B########BGPPPPPPPP5GGPPPPG#########&&&&P7?J??????????????JJJ?????????J?????????????J????JJ? // 7777??7~.!557!!!7P7!^.::~YY?7YB##B#[email protected]&&&&&&####################BBGPPPPPY5GPGGB##BBBBBBB#&&&&#Y7J????????????????????????J????????JJ????J?????JJ? // 7777????7~:!JPY7!!!!JY^:.!YJP7~JB&#&[email protected]&&@@@&#######################BBGGPPPPPPPPPP55GBBB#&##&@&G7?J?JJ?????????YJ???????5Y??J??????77J??J??????JJ? // 777?????7?7!!^7GJ!!!JJ!!~?Y:~Y5J!J#&B5#B5P&&#&&@@&###########BBBBBGGPPPPP55555555555555GBBBB#&##&@&#J7??????JJYY55P#GPPPPP5YPY!?JJJJJJJ7?JJJJ??????JJ? // 777?????7777?7^^?PJ!!!!!!!~:.:^?PJ~?#&##[email protected]&&@&&&&#&&&&&&#&###BBBBBBGP555555555555555PGBBBB#&###&@@&B7?Y5PGGGPP555P55PP5YY5G#BGJ?JJJJJJJJ?JJJ??????JJ? // 7?77???7777777?7^^JPY!!!!!!!~:.:^!YY!JB&#[email protected]&@@@@@@@&&&&##&&&&&##BBBBBBGPP55555555555PBBBBBB#&###&&@&&####BBBGPPPP5PPPGGGGPYY##P^^^^^^^^^^^^^^~?!!?~^^^ // .^!7?777J?7?77?5PJ~:JPJ?!!^^~!~:::^7Y5!?B#@&@&@@@@@@@@@&#####&&&#BBBBBBBBGGPPPPPPPGBBBBBBBB&&&&&&&@@@@#GGGGGGBBB#BGGGPPPPBBB57:::::::~7::::::~?~~?^::: // ?..:!7??5?7~77?PPP?~~^!PP!:^^~!!~^.:^!YY7?B&&&@@@@@@&&&&&######&&##BBBBBBGBBBBBBBBBBBBBBBB#######&&&&&&&&####GP5YY5PPGPP5J!^!Y::^::::!?::::::~?~!?~::: // ^.~^.~!7777!7!!7?57??7~^75P7^!!!!!~::^!JBPB&@@@@@&&&&&@@@&&&&##&#&&#BBBBBGBBBBBBBBBBBBB#####&&&@@@@&#BGPYJJJJJY55JJ7~~^::::::^:::::::::::::::~?^!?^::: // :~?::~J?777777J77!777~:!5J77?J5PGGBB#BB&&@@@&@@@@@@@@@@&&&&##&#####BBBGBB####&&&&@@@&&@@&##BP5J??77?J5P5YJ7~^:::::::::::::::::::::::::::::~?^!?^::: // ^?!^.:~7?7777!!777?JJYJY#BBBBBBBBBBB##&&@@@@@@@@@@@@&&&&###B#####&&&&#&&&&&&&##BBGP5YJJ?7??JJYYPB#&Y~^::::::::::::::::::::::::::::::::::::?~!?^::: // ^ ^7 ?B~.^7???77~^5GGBBBBBBGBBBBBBB#&&&&&&&&&&&####[email protected]@G:::::::::::::::::::::!7::::::::::::::^^^:!?^::: // ~7 .: .^^^!?JP?J###BBBBBBBBBBBBBBBBBBBGGPPP555YYYYJJJJJJ?????77777??JJ5PGGGGP5Y55YYJJ7 ^[email protected]@G::::::::::::::::::::::::::::::::::::^~^::^7^::: // !! :^^^J&J7JP#&&&&&&&##BGGPPPP5YYJJJJJJ?????77777!!7?77??JYY555YJ?!~^:....??????7 [email protected]&Y^::::::::::::::::::::::::::::::::::::::7??7:::: // !~ :. .^::!777?JJJJJJJJJJJJJJ?J5Y?????YP5??~^^~~!!7?75J~~~::.. . . .??????7 :[email protected]#::::::^::^^:::::::::::::::::::::::::::::7??!:::: // 7: .Y^ :~: .~7?7777!777777777!^[email protected]??:7??7!^77 :?. . . 7?????7 [email protected]::::::::::::::::::::::::::::::::::::::::!??~:::: // . . . .^!~7777?777!!7777?7~:[email protected]@B7!7&&&@@@@@#B#GYJ7^: . .. .??????7 ^[email protected]#^:::::::::::::::::::::::::::::::::::::::~?7::::: // :! .J.~?77777?7^777777??:^B77&@&?: ...:^?5PGGB#&&@@&BY7:. . ^???????... !#@&!!!!!~!~!!!!!!!77!!!!!!!~!~!!7!~!7!777!~7J?!!!!! // ^? .:^^~7777777!!77?Y??7!:~GJ7?&@#: !??77??!.^!7J#@&! . .??5G7:!YJ : .~7#@@#GP5Y5B&BPBBPP5P5GBGBG5GBB#&#B#BB#GPGGBGP5GGPGBG // ^?. .^^^~7?77777!!77777J?~::JG?!?J&@#. .. :?57!??~ .P&#^ . . :J&&GP#@!:PJ 7J&@@@PG5G##G5PPPG555G5GBPBGY5BG#&BPG#5PPY5YYPGPJGG#P // ^?. .^^:7???7777!!7!777?7~^[email protected]@#^ .. !P&@@@@#5: .. :&&J ... ?&@@@@@@@@Y .7?#@#@@&#GPGGGGBGPPPYGPGBGGG55BBBBBGBG5PP5555P5J5GGBP // ~?: :^^^!?Y?7777!!777!7?7^~YYY77!!!J&@@@@7. [email protected]@@#G&@@@G^ .. #@5 [email protected]@@@5Y&@@@[email protected][email protected]@@5PPGPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPGJ?5PPPP // ~?: :^^^!7?77777!!7777??7^^[email protected]@&@@5: [email protected]@@B7:[email protected]@@@B . [email protected] [email protected]@@G ~&@@@@7:[email protected]:[email protected]@&YPPPPPPPPGBPPPPPPPPPP5PPPPPPPPPPPPPPPJ?5PPPP // !?^ .^^:^!??7?J7!!77777?7!^:?B?!?7!!!!~7&@[email protected]#G7 .#@@@[email protected]@@@&. . [email protected] .. [email protected]@@P:[email protected]@@@&JJJ??#B^&@@B?5PPPPYP5PGY5PGGGPPPP5PPBPGGGGBBGBBPGY?YGP55 // 7?~^:..~7?777?Y777777?7!:~?5P7!!Y7!!^:[email protected]@[email protected]&B?^ [email protected]@@&[email protected]@@@@7 . [email protected] .. [email protected]@@@#@@@@Y^::^??&P^@@@P?YYP55JGGB#YY#BB#PPPYJPGY5#B#GP&@B55B5?5BBJ? // 7?!:.77?77777!77!77?7!^~5P?!!!!!!~~..:^7&@B^B&&J~ [email protected]@@@@@#G7 .. [email protected] .JG#@@&BY^ . ~?J&[email protected]@@P?JPPPPP555PPPGGBGPPPPPPPP555GBBGGBBBGJ?5P5P5 // .^??^~??7777!!77777?7~:75Y?!!!!!!~:.^:^^[email protected]@[email protected]@5^ . !5PP57: .. [email protected]&: !77JJ?. [email protected][email protected]@@Y?5PPPPPGPPPPPPPPPPPPPPPPPPPP555PPPPPGJ?PBGPP // ~~^?????JJ?!!777777!~:755!!!!!!!~:.:^^^7YG&PP&&&@@5^ :?????!. .. [email protected]&: :?????. !?Y#@&&#B5GGPP5555PPPPPPGGBGPGGGGGGBGBYJJPPGP55J?G&&P5 // .:!??77YBBY77777?7:.^JG!!!!!!!~^..^^~7YG###&BPB#@@B^ 7????! ~&&^ ^^7??: . !?G&#B5PG5B#[email protected]&YYP#G5BGBB#B#PP5#5P5BYBPYPJ?5PPYG // !????777777777?7^:YYY?!!!!!!~:.::^~?PGB##B###[email protected]@@~ :????! ^&&^ !??.... 7?G#5PPYY55P5Y5PPGGG5Y5PY555G55PG5P5PBPJPG5PPGG??PGPPP // ?????7777777?7^~7PY!!!!!!!^:.:^^~?5B##B####BPJJ5&@@J .???: :@@? .. ~?~ . . .?J&#B#####B##BB####BB#B#############B#BB####B#G??B###G // 7????7777?7!^:YP?!!!!!!!~:.:^^~?P#&#B####BPJJY5PB&@#. :!~ . ..?Y^ . ~?.. .. :[email protected]########BB################B####B&&#######P?JB###B // 7????77?7^.:~5P!!55?!!~^::?!:75B&#&&#GBB5JYBBYYG#&@@7 . . . ..^ .: . . [email protected]&#BB######BBBB#####BB#####&&BB#####@@BB#####P?JBB##B // 77????7^.7J55J!!!!7!::.::^~?5B###B###G5JY5PPPGG#&&@@B. .~. . . :: . :?. . ..?&####BBBBBB###BB##############BB#######BB#####5?5####B // 77???^:^YP!!!!!!!~^..^^^~?PB#######B5JYPPPPPB#&@@##@@7 ...^^.?G!....YY...:?B7::.!B^.:. .~G&B#####BBBBBBBB###############BB##############Y?P####B // ??7??JPJ!^^!!!!~:.::^^~75B#B#####B5YY5P5PPG#&@@@@&[email protected]@#~ ^7PBBB#@BBBBB&@###B#@@##&&@&&#&?: :G&B#############################BB#####BB#######5JG####B // ~::??PG^^^^!!~^^..^~!JG##B####BG5JYBPJ5GB#&@@@@@@@&#&@G! ~B&&&@@&#&&B&@&##BB&&[email protected] .5&GG##########&#########BB#######BB##############Y?GB###B // .!5???7^^^^~:.:::^J5G#######B5JY55PGP5B#&@@@@@@@@@&#[email protected]@B?: .:[email protected]::[email protected]:.YB . ^#! ^[email protected]###################BB########B##############Y?BB###B // Y?!?7^^^^^^::^^^!5G######BBPYJ5PPPPGB#@@@@@@@@@@@@&@@@@@&Y^ :P! PJ ^~ :J~ [email protected]&B################################B#####BB#######Y?B####B // ^^~?7^^^^^^^^^~JG########PYJ5PPPPGB#@@@@@@@@@@@@@@@&&#&@@@B!. .^. ^. . . .! .:[email protected]@####BB################BB######BBB#BB#####BB######5?G####B // !^~?7^^^^^^^7YB##&####BPYYGGPPGBB&@@@@@@@@@@@@@@@@@###BB&@@@#Y~ . .^[email protected]@########B####B############BB####&#BBB###BB####B###5?GBBB#B // 7^~?!^^^^!?YB#######G5YYYP&&&##&@@@@@@@@@@@@@@@@&BPB#BBGGBB#@@@BJ^. . :!J#@&BB##BBBBBB#B########BBB########B###BBB#B#BB#B####B#P?BBB##B // ^^~?!^^~75P#######B5J55PPPB&#&@@@@@@@@@@@@@@@@&BP5GGP555555PB#&B&@#57: .^7YB&&#GGBBBGGGGGBBBBBBBBBBBBBBBGBBBBBBBGGBBGGBBBBBBBBBBBBB5JGBBBBG // ^^~?!~JPBBB#####G5JJ5PPPPB#&@@@@@@@@@@@@@@@@&G5555555555PGGGP&@BYJY#@&#P5J?J7!?JY5GB&&&@#GBBBBBBBB#BBBBBBBBBBGBBBBBBBBBBBBBBBBBBGBBBBBBBBBBBBB5?PBBBBG // ^^~?JG&G#BB###GYJJ5Y5PGG#&@@@@@@@@@@@@@@@@#BB55555555PPPBBG5J#@&J^ .:^?PGB#&&&&&&BPP7:[email protected]@&BBBBBBBB#BGBBBBBBBBGBBBBBBBGGBBBBBBBBBGBBBBBBBBBBBBBP?YBBBBG // ~7Y?P##B#BBBPYJYY555BB#&@@@@@@@@@@@@@@@@#PGGG5555555G#[email protected]@5?~ ...:::.. :[email protected]@#BBBBBBBBGPGBBBBBBBBBBBBBBBGGB&BBBBBBBGBGPBBBBBBBBBBG?JBBBBG // PGB?PB##&#BYJYPPPPGG#&&@@@@@@@@@@@@@@@#P55P555555PPGBGGGB#B&@@G??~ [email protected]&#BGGBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBGBBBBBBBBBBBBBG?JBBBBG // GGP?P###&#B55PPPGB#@@@&@@@@@@@@@@@@@#P5555555Y5Y5PPPG#&&@@@@&P???~ .?#@@@#BGGGBGPGBGBBBBBBBBBBBBBBBBBBBBBBBBGBBBBBBBBBBBBBGJJGBBBG // BB5?P#B#@#BPPPGB#@@@@@&@@@@@@@@@@&#PYY5PGGGBBBBBBB#&@@@@&#B5J!^:^ :5&@@@@&#GPPPGGGGGGGGBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB5?PBBBG // GBP?5##&@@&BBB&@@@@@@&@@@@@@@@@@&B#BB#@@@@@@@@@@@@&&#GP5J?!^. .!YP&@@@@&#BBGP5Y55555PPPPPPPPGGGGGGGGGBBBBBBBBBBBBBBBG?YBBBG // B#BGB###&&&#&@@@@@@@@&@@@@@&@@@@@@@@@&&&#BP5JYYYYJJ?7!~^:. :!?YP#&@@@@@@@@@@@@&&&#BBBBBGGBBBBGGBBBBBBBBBBBBBBBYJBBBG // ##########&@@@@@@@@@@&&&@@@@&#G5YYYJJJJ?77!!!~~^::.. :~7J5PGB###B55PPGB&&&@@@@@@@&#BGBBBBBBBBBBBBBBGBBBG // BBBBBBBB#&@&&&&&&&&&@@@@@BPYJ?????7!~^:.. ... ..:~!?J55G&@&GGGGGGGGGGGGGGGGGGGG import "./Ownable.sol"; import "./Address.sol"; import "./ECDSA.sol"; import "./SafeCast.sol"; import "./ERC721.sol"; import "./Treasury.sol"; import "./ERC2981.sol"; contract CryptoQueenz is Ownable, ERC721, ERC2981, Treasury { using Address for address; using SafeCast for uint256; using ECDSA for bytes32; using Strings for uint256; // EVENTS **************************************************** event StartingIndexSet(uint256 _value); event DutchAuctionConfigUpdated(); event PresaleConfigUpdated(); event ProvenanceHashUpdated(bytes32 _hash); event WhitelistSignerUpdated(address _signer); event baseURISet(string _uri); event DummyURIUpdated(string _uri); event NFTRevealTimeUpdated(uint256 NFTRevealTime); // MEMBERS **************************************************** struct DutchAuctionConfig { uint32 startTime; uint32 stepInterval; uint256 startPrice; uint256 bottomPrice; uint256 priceStep; } struct PresaleConfig { uint32 startTime; uint32 endTime; uint32 supplyLimit; uint256 mintPrice; } PresaleConfig public presaleConfig; DutchAuctionConfig public dutchAuctionConfig; uint256 public immutable MAX_OWNER_RESERVE; uint256 public immutable CRYPTO_QUEENZ_SUPPLY; // Number of currently supplied tokens uint256 public totalSupply = 0; // Number of currently minted tokens uint256 public presaleMintedTotal; uint256 public randomizedStartIndex; uint256 public NFTRevealTime; string public dummyURI; string public baseURI; address public whitelistSigner; // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) public _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) public _ownedTokensIndex; mapping(address => uint256) public presaleMinted; mapping(address => uint256) public presaleMintedFree; bytes32 public PROVENANCE_HASH; bytes32 private DOMAIN_SEPARATOR; bytes32 private constant PRESALE_TYPEHASH = keccak256("presale(address buyer,uint256 limit)"); bytes32 private constant FREEMINT_TYPEHASH = keccak256("freeMint(address buyer,uint256 limit)"); address[] private mintPayees = [ 0xaF019dE18D30c5e0c5e1596ebf81B793648B9356 ]; uint256[] private mintShares = [100]; Treasury public royaltyRecipient; // CONSTRUCTOR ************************************************** constructor(string memory initialDummyURI, bytes32 provenanceHash, address whitelistSignerAddress, uint256 _MAX_OWNER_RESERVE, uint256 _CRYPTO_QUEENZ_SUPPLY ) ERC721("CryptoQueenz by Boy George", "QUEENZ") Treasury(mintPayees, mintShares) { //Sets the owner's reserved token supply MAX_OWNER_RESERVE = _MAX_OWNER_RESERVE; //Sets the max supply CRYPTO_QUEENZ_SUPPLY = _CRYPTO_QUEENZ_SUPPLY; dummyURI = initialDummyURI; NFTRevealTime = 1646337600; // 03 March 8pm GMT PROVENANCE_HASH = provenanceHash; emit ProvenanceHashUpdated(provenanceHash); whitelistSigner = whitelistSignerAddress; emit WhitelistSignerUpdated(whitelistSignerAddress); presaleConfig = PresaleConfig({ startTime: 1646164800, // 01 March 8pm GMT endTime: 1646251199, // 02 March 7:59:59pm GMT mintPrice: 0.13 ether, supplyLimit: 7800 }); dutchAuctionConfig = DutchAuctionConfig({ startTime: 1646251200, // 02 March 8pm GMT stepInterval: 180, // 3 minutes startPrice: 1.3 ether, bottomPrice: 0.13 ether, priceStep: 0.1 ether }); address[] memory royaltyPayees = new address[](1); royaltyPayees[0] = 0xaF019dE18D30c5e0c5e1596ebf81B793648B9356; uint256[] memory royaltyShares = new uint256[](1); royaltyShares[0] = 100; royaltyRecipient = new Treasury(royaltyPayees, royaltyShares); _setRoyalties(address(royaltyRecipient), 700); // 7% royalties uint256 chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ), keccak256(bytes("CryptoQueenz")), keccak256(bytes("1")), chainId, address(this) ) ); } // PUBLIC METHODS **************************************************** /// @notice Allows users to buy during presale, only whitelisted addresses may call this function. /// Whitelisting is enforced by requiring a signature from the whitelistSigner address /// @dev Whitelist signing is performed off chain, via the CryptoQueenz website backend /// @param signature signed data authenticating the validity of this transaction /// @param numberOfTokens number of NFTs to buy /// @param approvedLimit the total number of NFTs this address is permitted to buy during presale, this number is also encoded in the signature function buyPresale( bytes calldata signature, uint256 numberOfTokens, uint256 approvedLimit ) external payable{ require(numberOfTokens > 0, "Should mint atleast 1 NFT"); // Checking total limit require((totalSupply + numberOfTokens) <= CRYPTO_QUEENZ_SUPPLY, "Total Supply limit reached"); PresaleConfig memory _config = presaleConfig; require(block.timestamp >= _config.startTime && block.timestamp < _config.endTime, "Presale not active"); require(whitelistSigner != address(0), "Whitelist signer not set"); require((presaleMintedTotal + numberOfTokens) <= _config.supplyLimit, "Presale Supply limit reached"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(PRESALE_TYPEHASH, msg.sender, approvedLimit)) ) ); address signer = digest.recover(signature); require(signer != address(0) && signer == whitelistSigner,"Invalid signature"); require((presaleMinted[msg.sender] + numberOfTokens) <= approvedLimit, "Mint limit exceeded"); require(msg.value == (_config.mintPrice * numberOfTokens), "Incorrect ETH provided"); presaleMinted[msg.sender] = presaleMinted[msg.sender] + numberOfTokens; mint(msg.sender, numberOfTokens); presaleMintedTotal += numberOfTokens; } /// @notice Allows users to buy during presale for free, only whitelisted addresses may call this function. /// Whitelisting is enforced by requiring a signature from the whitelistSigner address /// @dev Whitelist signing is performed off chain, via the CryptoQueenz website backend /// @param signature signed data authenticating the validity of this transaction /// @param numberOfTokens number of NFTs to buy /// @param approvedLimit the total number of NFTs this address is permitted to buy during presale, this number is also encoded in the signature function buyPresaleFree( bytes calldata signature, uint256 numberOfTokens, uint256 approvedLimit ) external payable{ require(numberOfTokens > 0, "Should mint atleast 1 NFT"); require((totalSupply + numberOfTokens) <= CRYPTO_QUEENZ_SUPPLY, "Total Supply limit reached"); PresaleConfig memory _config = presaleConfig; require(block.timestamp >= _config.startTime && block.timestamp < _config.endTime,"Presale not active"); require(whitelistSigner != address(0), "Whitelist signer has not been set"); require((presaleMintedTotal + numberOfTokens) <= _config.supplyLimit, "Presale Supply limit reached"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(FREEMINT_TYPEHASH, msg.sender, approvedLimit)) ) ); address signer = digest.recover(signature); require(signer != address(0) && signer == whitelistSigner, "Invalid signature"); require((presaleMintedFree[msg.sender] + numberOfTokens) <= approvedLimit,"Mint limit exceeded"); presaleMintedFree[msg.sender] = presaleMintedFree[msg.sender] + numberOfTokens; mint(msg.sender, numberOfTokens); presaleMintedTotal += numberOfTokens; } /// @notice Allows users to buy during public sale, pricing follows a dutch auction format and a constant set price after the dutch auction ends /// @dev Preventing contract buys has some downsides, but it seems to be what the NFT market generally wants as a bot mitigation measure /// @param numberOfTokens the number of NFTs to buy function buyPublic(uint256 numberOfTokens) external payable { require(numberOfTokens > 0, "Should mint atleast 1 NFT"); require(totalSupply + numberOfTokens <= CRYPTO_QUEENZ_SUPPLY, "Total supply maxed out"); require(block.timestamp >= dutchAuctionConfig.startTime, "Public sale not active"); // disallow contracts from buying require( (!msg.sender.isContract() && msg.sender == tx.origin), "Contract buys not allowed" ); uint256 mintPrice = getCurrentAuctionPrice() * numberOfTokens; require(msg.value >= mintPrice, "Insufficient payment"); // refund if customer paid more than the cost to mint if (msg.value > mintPrice) { Address.sendValue(payable(msg.sender), msg.value - mintPrice); } mint(msg.sender, numberOfTokens); } /// @notice Gets an array of tokenIds owned by a wallet /// @param wallet wallet address to query contents for /// @return an array of tokenIds owned by wallett function tokensOwnedBy(address wallet) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(wallet); uint256[] memory ownedTokenIds = new uint256[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { ownedTokenIds[i] = _ownedTokens[wallet][i]; } return ownedTokenIds; } /// @inheritdoc ERC165 function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC2981) returns (bool) { return super.supportsInterface(interfaceId); } //Returns the number of remaining tokens available for mint function totalLeftToMint() view external returns(uint256){ return CRYPTO_QUEENZ_SUPPLY - totalSupply; } /** Batch transfers NFTs to users @param to : Array of to addresses @param tokenIds : Array of corresponding token ids @return true if batch transfer succeeds */ function batchTransfer(address[] memory to, uint256[] memory tokenIds) external returns(bool){ require(to.length > 0, "Minimum one entry"); require(to.length == tokenIds.length, "Unequal length of to addresses and number of tokens"); require(tokenIds.length <= balanceOf(msg.sender),"Not enough tokens owned"); for(uint256 i = 0; i < to.length; i++){ safeTransferFrom( msg.sender, to[i], tokenIds[i] ); } return true; } // OWNER METHODS ********************************************************* /// @notice Allows the contract owner to reserve NFTs for team members or promotional purposes /// @dev This should be called before presale or public sales start, as only the first MAX_OWNER_RESERVE tokens can be reserved /// @param to address for the reserved NFTs to be minted to /// @param numberOfTokens number of NFTs to reserve function reserve(address[] memory to, uint256[] memory numberOfTokens) external onlyOwner { require(to.length > 0, "Minimum one entry"); require(to.length == numberOfTokens.length, "Unequal length of to addresses and number of tokens"); uint256 totalNumber; uint256 i; for(i = 0; i < numberOfTokens.length; i++){ totalNumber += numberOfTokens[i]; } require((totalSupply + totalNumber) <= MAX_OWNER_RESERVE,"Exceeds owner reserve limit"); for(i = 0; i < to.length; i++){ mint(to[i], numberOfTokens[i]); } } /// @notice Allows the contract owner to update config for the public dutch auction function configureDutchAuction( uint256 startTime, uint256 stepInterval, uint256 startPrice, uint256 bottomPrice, uint256 priceStep ) external onlyOwner { uint32 _startTime = startTime.toUint32(); uint32 _stepInterval = stepInterval.toUint32(); require(0 < bottomPrice, "Invalid bottom price"); require(0 < stepInterval, "0 step interval"); require(bottomPrice < startPrice, "Start price must be greater than bottom price"); require(0 < priceStep && priceStep < startPrice, "Invalid price step"); dutchAuctionConfig.startTime = _startTime; dutchAuctionConfig.stepInterval = _stepInterval; dutchAuctionConfig.startPrice = startPrice; dutchAuctionConfig.bottomPrice = bottomPrice; dutchAuctionConfig.priceStep = priceStep; emit DutchAuctionConfigUpdated(); } /// @notice Allows the contract owner to update start and end time for the presale function configurePresale(uint256 startTime, uint256 endTime, uint256 mintPrice, uint256 supplyLimit) external onlyOwner { uint32 _startTime = startTime.toUint32(); uint32 _endTime = endTime.toUint32(); uint32 _supplyLimit = supplyLimit.toUint32(); require(0 < _startTime, "Invalid time"); require(_endTime > _startTime, "Invalid time"); require(mintPrice > 0, "Invalid mint price"); require(supplyLimit <= CRYPTO_QUEENZ_SUPPLY, "Invalid supply limit"); presaleConfig.startTime = _startTime; presaleConfig.endTime = _endTime; presaleConfig.mintPrice = mintPrice; presaleConfig.supplyLimit = _supplyLimit; emit PresaleConfigUpdated(); } /// @notice Gets the current price for the duction auction, based on current block timestamp, will return a set price value after dutch auction ends /// @dev Dutch auction parameters configured via dutchAuctionConfig /// @return currentPrice Current mint price per NFT function getCurrentAuctionPrice() public view returns (uint256 currentPrice) { DutchAuctionConfig memory _config = dutchAuctionConfig; uint256 timestamp = block.timestamp; if (timestamp < _config.startTime) { currentPrice = _config.startPrice; } else { uint256 elapsedIntervals = (timestamp - _config.startTime) /_config.stepInterval; if(_config.startPrice > (elapsedIntervals * _config.priceStep) && ((_config.startPrice - (elapsedIntervals * _config.priceStep)) >= _config.bottomPrice)) currentPrice =_config.startPrice - (elapsedIntervals * _config.priceStep); else{ currentPrice = _config.bottomPrice; } } return currentPrice; } function setNFTRevealTime(uint256 newNFTRevealTime) external onlyOwner{ NFTRevealTime = newNFTRevealTime; emit NFTRevealTimeUpdated(newNFTRevealTime); } /// @notice Allows the owner to roll a pseudo-random number once, which will be used as the starting index for the token metadata. /// This is used to prove randomness and fairness in the metadata distribution, in conjunction with the PROVENANCE_HASH /// @dev The starting index can only be set once, only after all NFTs are minted, and only if the PROVENANCE_HASH has been set function rollStartIndex() external onlyOwner { require(PROVENANCE_HASH != 0, "Provenance hash not set"); require(randomizedStartIndex == 0, "Index already set"); require(block.timestamp >= NFTRevealTime, "NFT Reveal time not reached yet"); uint256 number = uint256( keccak256( abi.encodePacked( blockhash(block.number - 1), block.coinbase, block.difficulty, block.timestamp ) ) ); randomizedStartIndex = (number % CRYPTO_QUEENZ_SUPPLY) + 1; emit StartingIndexSet(randomizedStartIndex); } /** @param provenanceHash : The new provenance hash Sets the provenance hash, if the randomizedStartIndex hasn't been rolled yet */ function setProvenance(bytes32 provenanceHash) external onlyOwner { require(randomizedStartIndex == 0, "Starting index already set"); emit ProvenanceHashUpdated(provenanceHash); PROVENANCE_HASH = provenanceHash; } // Calculated the provenance hash of the base URI provided function calculateProvenanceHash(string calldata _baseURI) public pure returns(bytes32) { return keccak256(abi.encode(_baseURI)); } /** @param _baseURI : The base URI string @return Boolean value true/false if the provenance hash of the base uri matches with the set PROVENANCE_HASH Verifies whether the input base URI's hash matches with the set PROVENANCE_HASH */ function verifyProvenanceHash(string calldata _baseURI) view public returns(bool) { require(calculateProvenanceHash(_baseURI) == PROVENANCE_HASH, "Doesn't match with the provenance hash"); return true; } /** @param _baseURI : The base URI string @return Boolean value true/false if base URI was successfully set Verifies whether the input base URI's hash matches with the set PROVENANCE_HASH and sets the base URI */ function setBaseURI(string calldata _baseURI) external onlyOwner returns(bool) { require(randomizedStartIndex != 0, "Please roll the start index first"); require(verifyProvenanceHash(_baseURI), "Verification of provenance hash failed"); baseURI = _baseURI; emit baseURISet(_baseURI); return true; } /** @param theDummyURI : The dummy base URI string Sets the dummy base URI. This URI will be used by all tokens until the startIndex has been randomized and base URI is set */ function setDummyURL(string memory theDummyURI) external onlyOwner{ dummyURI = theDummyURI; emit DummyURIUpdated(theDummyURI); } /** @param tokenId : The token id Fetches the token URI of token id = tokenId. It will return dummy URI if the base URI has not been set. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, (((tokenId + randomizedStartIndex) % CRYPTO_QUEENZ_SUPPLY) + 1).toString(), ".json") ) : dummyURI; } /** @param newWhitelistSigner : The token id Sets a new whitelist signer address. This address will be used to verify signatures in buyPresale and buyPresaleFree. */ function setWhitelistSigner(address newWhitelistSigner) external onlyOwner { emit WhitelistSignerUpdated(newWhitelistSigner); whitelistSigner = newWhitelistSigner; } // PRIVATE/INTERNAL METHODS **************************************************** function mint(address to, uint256 numberOfTokens) private { uint256 newId = totalSupply; for (uint256 i = 0; i < numberOfTokens; i++) { newId += 1; _safeMint(to, newId); } totalSupply = newId; } // ************************************************************************************************************************ // The following methods are borrowed from OpenZeppelin's ERC721Enumerable contract, to make it easier to query a wallet's // contents without incurring the extra storage gas costs of the full ERC721Enumerable extension // ************************************************************************************************************************ /** * @dev Private function to add a token to ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from != address(0)) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to != address(0)) { _addTokenToOwnerEnumeration(to, tokenId); } } }
Number of currently supplied tokens
uint256 public totalSupply = 0;
534,716
[ 1, 1854, 434, 4551, 4580, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 5034, 1071, 2078, 3088, 1283, 273, 374, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x2F7b2A88c6eD2AfE44D8c947CBf661C66575BeB9/sources/_thirdweb-dev/contracts/base/ERC1155Drop.sol
@dev Runs before every token transfer / mint / burn.
function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] -= amounts[i]; } } }
860,284
[ 1, 9361, 1865, 3614, 1147, 7412, 342, 312, 474, 342, 18305, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 3726, 16, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 8526, 3778, 3258, 16, 203, 3639, 2254, 5034, 8526, 3778, 30980, 16, 203, 3639, 1731, 3778, 501, 203, 565, 262, 2713, 5024, 3849, 288, 203, 3639, 2240, 6315, 5771, 1345, 5912, 12, 9497, 16, 628, 16, 358, 16, 3258, 16, 30980, 16, 501, 1769, 203, 203, 3639, 309, 261, 2080, 422, 1758, 12, 20, 3719, 288, 203, 5411, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 3258, 18, 2469, 31, 965, 77, 13, 288, 203, 7734, 2078, 3088, 1283, 63, 2232, 63, 77, 13563, 1011, 30980, 63, 77, 15533, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 309, 261, 869, 422, 1758, 12, 20, 3719, 288, 203, 5411, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 3258, 18, 2469, 31, 965, 77, 13, 288, 203, 7734, 2078, 3088, 1283, 63, 2232, 63, 77, 13563, 3947, 30980, 63, 77, 15533, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/10/0xA5e6EFdA500FD0BCEd87B2cd8Af1c81c0cc9D556/sources/MultiSigWallet.sol
@dev Allows to add a new owner. Transaction has to be sent by wallet. @param owner Address of new owner.
function addOwner(address owner) external onlyWallet ownerDoesNotExist(owner) notNull(owner) validRequirement(owners.length + 1, required) { isOwner[owner] = true; owners.push(owner); emit OwnerAddition(owner); }
3,779,797
[ 1, 19132, 358, 527, 279, 394, 3410, 18, 5947, 711, 358, 506, 3271, 635, 9230, 18, 225, 3410, 5267, 434, 394, 3410, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 5541, 12, 2867, 3410, 13, 203, 3639, 3903, 203, 3639, 1338, 16936, 203, 3639, 3410, 15264, 12, 8443, 13, 203, 3639, 7713, 12, 8443, 13, 203, 3639, 923, 18599, 12, 995, 414, 18, 2469, 397, 404, 16, 1931, 13, 203, 565, 288, 203, 3639, 353, 5541, 63, 8443, 65, 273, 638, 31, 203, 3639, 25937, 18, 6206, 12, 8443, 1769, 203, 3639, 3626, 16837, 30296, 12, 8443, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x1facbCfd122C1F871496a59a70D743D7b757B69b/sources/Banana.sol
Anti-bot and anti-whale mappings and variables exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract Banana is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; address public constant deadAddress = address(0xdead); bool private swapping; address public revWallet; address public treasuryWallet; address public teamWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = true; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyRevFee; uint256 public buyTreasuryFee; uint256 public buyLiquidityFee; uint256 public buyTeamFee; uint256 public sellTotalFees; uint256 public sellRevFee; uint256 public sellTreasuryFee; uint256 public sellLiquidityFee; uint256 public sellTeamFee; uint256 public tokensForRev; uint256 public tokensForTreasury; uint256 public tokensForLiquidity; uint256 public tokensForTeam; mapping(address => bool) private _isExcludedFromFees; mapping(address => bool) public _isExcludedMaxTransactionAmount; mapping(address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router( address indexed newAddress, address indexed oldAddress ); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); constructor() ERC20("Banana", "BANANA") { 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 totalSupply = 10_000_000 * 1e18; maxTransactionAmount = 100_000 * 1e18; maxWallet = 100_000 * 1e18; swapTokensAtAmount = (totalSupply * 10) / 10000; uint256 _buyRevFee = 2; uint256 _buyTreasuryFee = 1; uint256 _buyLiquidityFee = 0; uint256 _buyTeamFee = 1; uint256 _sellRevFee = 2; uint256 _sellTreasuryFee = 1; uint256 _sellLiquidityFee = 0; uint256 _sellTeamFee = 1; buyRevFee = _buyRevFee; buyTreasuryFee = _buyTreasuryFee; buyLiquidityFee = _buyLiquidityFee; buyTeamFee = _buyTeamFee; buyTotalFees = buyRevFee + buyTreasuryFee + buyLiquidityFee + buyTeamFee; sellRevFee = _sellRevFee; sellTreasuryFee = _sellTreasuryFee; sellLiquidityFee = _sellLiquidityFee; sellTeamFee = _sellTeamFee; sellTotalFees = sellRevFee + sellTreasuryFee + sellLiquidityFee + sellTeamFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromFees(0xC4A0C91Ca415887174b63d76c132284b2E7Ff8B6, true); excludeFromFees(0xF7A3285664BdfAeA0b52B0EcA30cdC99C86EC98B, true); excludeFromFees(0x1C0435144EC9E27a0Adbd51732849191Fd898f92, true); excludeFromFees(0x37AF2967fB932B5291Efe053ba98c78b9B540e60, true); excludeFromFees(0x30AF1239A4995e8be511176981e66ec39c29E89f, true); excludeFromFees(0x74B29E90005D29f1Fa9069697fF87Ea8e33F0580, true); excludeFromFees(0x1aC69aFABB3D4416dA019369980921002E04dEAa, true); excludeFromFees(0x3846180aC8fc4c86CC0586f3d670D543d1a2cb1F, true); excludeFromFees(0x2e67Db3906d7765ff6A663Cf0b47eD29326903e1, true); excludeFromFees(0x64568fb777d17D1fce7bB02e845b087Fb23aa01b, true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxTransaction(0xC4A0C91Ca415887174b63d76c132284b2E7Ff8B6, true); excludeFromMaxTransaction(0xF7A3285664BdfAeA0b52B0EcA30cdC99C86EC98B, true); excludeFromMaxTransaction(0x1C0435144EC9E27a0Adbd51732849191Fd898f92, true); excludeFromMaxTransaction(0x37AF2967fB932B5291Efe053ba98c78b9B540e60, true); excludeFromMaxTransaction(0x30AF1239A4995e8be511176981e66ec39c29E89f, true); excludeFromMaxTransaction(0x74B29E90005D29f1Fa9069697fF87Ea8e33F0580, true); excludeFromMaxTransaction(0x1aC69aFABB3D4416dA019369980921002E04dEAa, true); excludeFromMaxTransaction(0x3846180aC8fc4c86CC0586f3d670D543d1a2cb1F, true); excludeFromMaxTransaction(0x2e67Db3906d7765ff6A663Cf0b47eD29326903e1, true); excludeFromMaxTransaction(0x64568fb777d17D1fce7bB02e845b087Fb23aa01b, true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply); } receive() external payable {} function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; } function removeLimits() external onlyOwner returns (bool) { limitsInEffect = false; return true; } function disableTransferDelay() external onlyOwner returns (bool) { transferDelayEnabled = false; return true; } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) { require( newAmount >= (totalSupply() * 1) / 100000, "Swap amount cannot be lower than 0.001% total supply." ); require( newAmount <= (totalSupply() * 5) / 1000, "Swap amount cannot be higher than 0.5% total supply." ); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxTransactionAmount lower than 0.5%" ); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require( newNum >= ((totalSupply() * 5) / 1000) / 1e18, "Cannot set maxWallet lower than 0.5%" ); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateSwapEnabled(bool enabled) external onlyOwner { swapEnabled = enabled; } function updateBuyFees( uint256 _revFee, uint256 _treasuryFee, uint256 _liquidityFee, uint256 _teamFee ) external onlyOwner { require((_revFee + _treasuryFee + _liquidityFee ) <= 4, "Max BuyFee 4%"); buyRevFee = _revFee; buyTreasuryFee = _treasuryFee; buyLiquidityFee = _liquidityFee; buyTeamFee = _teamFee; buyTotalFees = buyRevFee + buyTreasuryFee + buyLiquidityFee + buyTeamFee; } function updateSellFees( uint256 _revFee, uint256 _treasuryFee, uint256 _liquidityFee, uint256 _teamFee ) external onlyOwner { require((_revFee + _treasuryFee + _liquidityFee ) <= 4, "Max SellFee 4%"); sellRevFee = _revFee; sellTreasuryFee = _treasuryFee; sellLiquidityFee = _liquidityFee; sellTeamFee = _teamFee; sellTotalFees = sellRevFee + sellTreasuryFee + sellLiquidityFee + sellTeamFee; } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require( pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs" ); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function isExcludedFromFees(address account) public view returns (bool) { return _isExcludedFromFees[account]; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForRev += (fees * sellRevFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForRev += (fees * buyRevFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForRev += (fees * sellRevFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForRev += (fees * buyRevFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForRev += (fees * sellRevFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForRev += (fees * buyRevFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForRev += (fees * sellRevFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForRev += (fees * buyRevFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForRev += (fees * sellRevFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForRev += (fees * buyRevFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForRev += (fees * sellRevFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForRev += (fees * buyRevFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForRev += (fees * sellRevFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForRev += (fees * buyRevFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } if ( function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForRev += (fees * sellRevFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForRev += (fees * buyRevFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } else if ( function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForRev += (fees * sellRevFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForRev += (fees * buyRevFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } } else if (!_isExcludedMaxTransactionAmount[to]) { function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForRev += (fees * sellRevFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForRev += (fees * buyRevFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForRev += (fees * sellRevFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForRev += (fees * buyRevFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForRev += (fees * sellRevFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForRev += (fees * buyRevFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForRev += (fees * sellRevFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForRev += (fees * buyRevFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForRev += (fees * sellRevFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForRev += (fees * buyRevFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } if (transferDelayEnabled) { if ( to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair) ) { require( _holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed." ); _holderLastTransferTimestamp[tx.origin] = block.number; } } automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to] ) { require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from] ) { require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount." ); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded" ); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellTotalFees > 0) { fees = amount.mul(sellTotalFees).div(100); tokensForRev += (fees * sellRevFee) / sellTotalFees; tokensForLiquidity += (fees * sellLiquidityFee) / sellTotalFees; tokensForTeam += (fees * sellTeamFee) / sellTotalFees; tokensForTreasury += (fees * sellTreasuryFee) / sellTotalFees; } else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForRev += (fees * buyRevFee) / buyTotalFees; tokensForLiquidity += (fees * buyLiquidityFee) / buyTotalFees; tokensForTeam += (fees * buyTeamFee) / buyTotalFees; tokensForTreasury += (fees * buyTreasuryFee) / buyTotalFees; } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, teamWallet, block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForRev + tokensForLiquidity + tokensForTreasury + tokensForTeam; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForRev = ethBalance.mul(tokensForRev).div(totalTokensToSwap); uint256 ethForTreasury = ethBalance.mul(tokensForTreasury).div(totalTokensToSwap); uint256 ethForTeam = ethBalance.mul(tokensForTeam).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForRev - ethForTreasury - ethForTeam; tokensForLiquidity = 0; tokensForRev = 0; tokensForTreasury = 0; tokensForTeam = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForRev + tokensForLiquidity + tokensForTreasury + tokensForTeam; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForRev = ethBalance.mul(tokensForRev).div(totalTokensToSwap); uint256 ethForTreasury = ethBalance.mul(tokensForTreasury).div(totalTokensToSwap); uint256 ethForTeam = ethBalance.mul(tokensForTeam).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForRev - ethForTreasury - ethForTeam; tokensForLiquidity = 0; tokensForRev = 0; tokensForTreasury = 0; tokensForTeam = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForRev + tokensForLiquidity + tokensForTreasury + tokensForTeam; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForRev = ethBalance.mul(tokensForRev).div(totalTokensToSwap); uint256 ethForTreasury = ethBalance.mul(tokensForTreasury).div(totalTokensToSwap); uint256 ethForTeam = ethBalance.mul(tokensForTeam).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForRev - ethForTreasury - ethForTeam; tokensForLiquidity = 0; tokensForRev = 0; tokensForTreasury = 0; tokensForTeam = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } uint256 liquidityTokens = (contractBalance * tokensForLiquidity) / totalTokensToSwap / 2; (success, ) = address(teamWallet).call{value: ethForTeam}(""); (success, ) = address(treasuryWallet).call{value: ethForTreasury}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForRev + tokensForLiquidity + tokensForTreasury + tokensForTeam; bool success; if (contractBalance == 0 || totalTokensToSwap == 0) { return; } if (contractBalance > swapTokensAtAmount * 20) { contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForRev = ethBalance.mul(tokensForRev).div(totalTokensToSwap); uint256 ethForTreasury = ethBalance.mul(tokensForTreasury).div(totalTokensToSwap); uint256 ethForTeam = ethBalance.mul(tokensForTeam).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForRev - ethForTreasury - ethForTeam; tokensForLiquidity = 0; tokensForRev = 0; tokensForTreasury = 0; tokensForTeam = 0; if (liquidityTokens > 0 && ethForLiquidity > 0) { addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify( amountToSwapForETH, ethForLiquidity, tokensForLiquidity ); } } (success, ) = address(revWallet).call{value: address(this).balance}(""); }
15,560,579
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 431, 17704, 1317, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 605, 304, 13848, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 565, 1758, 1071, 5381, 8363, 1887, 273, 1758, 12, 20, 92, 22097, 1769, 203, 203, 565, 1426, 3238, 7720, 1382, 31, 203, 203, 565, 1758, 1071, 5588, 16936, 31, 203, 565, 1758, 1071, 9787, 345, 22498, 16936, 31, 203, 565, 1758, 1071, 5927, 16936, 31, 203, 203, 565, 2254, 5034, 1071, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 203, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 638, 31, 203, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 203, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 30143, 10070, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 56, 266, 345, 22498, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 8689, 14667, 31, 203, 203, 565, 2254, 5034, 1071, 357, 80, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 357, 80, 10070, 14667, 31, 203, 565, 2254, 5034, 1071, 357, 80, 56, 266, 2 ]
pragma solidity 0.4.24; /** * @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; } } interface AccountRegistryInterface { function accountIdForAddress(address _address) public view returns (uint256); function addressBelongsToAccount(address _address) public view returns (bool); function createNewAccount(address _newUser) external; function addAddressToAccount( address _newAddress, address _sender ) external; function removeAddressFromAccount(address _addressToRemove) external; } /** * @title Bloom account registry * @notice Account Registry implements the Bloom ID data structures * and the low-level account administration functions. * The account administration functions are not publicly accessible. * Account Registry Logic implements the public functions which access the functions in Account Registry. */ contract AccountRegistry is Ownable, AccountRegistryInterface{ address public accountRegistryLogic; /** * @notice The AccountRegistry constructor configures the account registry logic implementation * and creates an account for the user who deployed the contract. * @dev The owner is also set as the original registryAdmin, who has the privilege to * create accounts outside of the normal invitation flow. * @param _accountRegistryLogic Address of deployed Account Registry Logic implementation */ constructor( address _accountRegistryLogic ) public { accountRegistryLogic = _accountRegistryLogic; } event AccountRegistryLogicChanged(address oldRegistryLogic, address newRegistryLogic); /** * @dev Zero address not allowed */ modifier nonZero(address _address) { require(_address != 0); _; } modifier onlyAccountRegistryLogic() { require(msg.sender == accountRegistryLogic); _; } // Counter to generate unique account Ids uint256 numAccounts; mapping(address => uint256) public accountByAddress; /** * @notice Change the address of the registry logic which has exclusive write control over this contract * @dev Restricted to AccountRegistry owner and new admin address cannot be 0x0 * @param _newRegistryLogic Address of new registry logic implementation */ function setRegistryLogic(address _newRegistryLogic) public onlyOwner nonZero(_newRegistryLogic) { address _oldRegistryLogic = accountRegistryLogic; accountRegistryLogic = _newRegistryLogic; emit AccountRegistryLogicChanged(_oldRegistryLogic, accountRegistryLogic); } /** * @notice Retreive account ID associated with a user's address * @param _address Address to look up * @return account id as uint256 if exists, otherwise reverts */ function accountIdForAddress(address _address) public view returns (uint256) { require(addressBelongsToAccount(_address)); return accountByAddress[_address]; } /** * @notice Check if an address is associated with any user account * @dev Check if address is associated with any user by cross validating * the accountByAddress with addressByAccount * @param _address Address to check * @return true if address has been assigned to user. otherwise reverts */ function addressBelongsToAccount(address _address) public view returns (bool) { return accountByAddress[_address] > 0; } /** * @notice Create an account for a user and emit an event * @param _newUser Address of the new user */ function createNewAccount(address _newUser) external onlyAccountRegistryLogic nonZero(_newUser) { require(!addressBelongsToAccount(_newUser)); numAccounts++; accountByAddress[_newUser] = numAccounts; } /** * @notice Add an address to an existing id * @param _newAddress Address to add to account * @param _sender User requesting this action */ function addAddressToAccount( address _newAddress, address _sender ) external onlyAccountRegistryLogic nonZero(_newAddress) { // check if address belongs to someone else require(!addressBelongsToAccount(_newAddress)); accountByAddress[_newAddress] = accountIdForAddress(_sender); } /** * @notice Remove an address from an id * @param _addressToRemove Address to remove from account */ function removeAddressFromAccount( address _addressToRemove ) external onlyAccountRegistryLogic { delete accountByAddress[_addressToRemove]; } }
* @notice Check if an address is associated with any user account @dev Check if address is associated with any user by cross validating the accountByAddress with addressByAccount @param _address Address to check @return true if address has been assigned to user. otherwise reverts/
function addressBelongsToAccount(address _address) public view returns (bool) { return accountByAddress[_address] > 0; }
7,305,196
[ 1, 1564, 309, 392, 1758, 353, 3627, 598, 1281, 729, 2236, 225, 2073, 309, 1758, 353, 3627, 598, 1281, 729, 635, 6828, 18075, 225, 326, 2236, 858, 1887, 598, 1758, 858, 3032, 225, 389, 2867, 5267, 358, 866, 327, 638, 309, 1758, 711, 2118, 6958, 358, 729, 18, 3541, 15226, 87, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 1758, 18097, 27192, 3032, 12, 2867, 389, 2867, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 565, 327, 2236, 858, 1887, 63, 67, 2867, 65, 405, 374, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x98b7893C5717aF41d3e351c6e3445Be02a062A90/sources/contracts/MapleLoanStorage.sol
@title MapleLoanStorage defines the storage layout of MapleLoan. Roles Assets Loan Term Parameters Rates Requested Amounts State Refinance Establishment fees Pool V2 dependencies Triggered defaults
abstract contract MapleLoanStorage { pragma solidity 0.8.7; }
3,924,861
[ 1, 863, 298, 1504, 304, 3245, 11164, 326, 2502, 3511, 434, 1635, 298, 1504, 304, 18, 19576, 26284, 3176, 304, 6820, 7012, 534, 815, 25829, 16811, 87, 3287, 868, 926, 1359, 17787, 23385, 475, 1656, 281, 8828, 776, 22, 5030, 11321, 329, 3467, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 1635, 298, 1504, 304, 3245, 288, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 27, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0xF617152555038b91EBF1B7C44c1c2D85270d9033/sources/browser/PayableRPS.sol
* @dev returns bet to players funds @param player address of the player @param bet bet/
function _returnBet(address player, uint256 bet) internal returns(bool) { funds[player] = funds[player].add(bet); }
16,220,657
[ 1, 6154, 2701, 358, 18115, 284, 19156, 225, 7291, 1758, 434, 326, 7291, 225, 2701, 2701, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2463, 38, 278, 12, 2867, 7291, 16, 2254, 5034, 2701, 13, 2713, 1135, 12, 6430, 13, 288, 203, 3639, 284, 19156, 63, 14872, 65, 273, 284, 19156, 63, 14872, 8009, 1289, 12, 70, 278, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xD4b02ef9A66C8F4B4583B4C7B8b504609b6a5d85/sources/MemeDogeTV.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("MemeDogeTV", "MDTV") { 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 = 1; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 4; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 1; 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);
2,818,450
[ 1, 10157, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 4232, 39, 3462, 2932, 3545, 73, 40, 717, 73, 15579, 3113, 315, 6188, 15579, 7923, 288, 203, 7010, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 20, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 1769, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 1435, 2934, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 203, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 404, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 8870, 14667, 273, 374, 31, 203, 2 ]
./partial_match/1/0xaAE423d666713f01C8c5cD2Ac1edcee079DC5a97/sources/LockDexMaster.sol
map epoch -> amount withdrawable
mapping (uint64 => uint256) releaseMap;
2,650,424
[ 1, 1458, 7632, 317, 3844, 598, 9446, 429, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2874, 261, 11890, 1105, 516, 2254, 5034, 13, 3992, 863, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/288/0xD64c3186A9C6ae6c1E92A110F76ab86F4C6295F9/sources/contracts/Ola/Core/LendingNetwork/versions/0.04/ComptrollerV0_04.sol
Check liquidation factor <= 0.9
Exp memory highLimit = Exp({mantissa: liquidationFactorMaxMantissa});
7,106,078
[ 1, 1564, 4501, 26595, 367, 5578, 1648, 374, 18, 29, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 7784, 3778, 3551, 3039, 273, 7784, 12590, 81, 970, 21269, 30, 4501, 26595, 367, 6837, 2747, 49, 970, 21269, 22938, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x79471Bb4CbB351a17Fa1EadB5B77AA76795c423a/sources/contracts/wereWulfz.sol
don't count the amount left to be minted for team
uint256 remainingSupply = totalMaxSupply - reservedAmount;
8,426,657
[ 1, 19752, 1404, 1056, 326, 3844, 2002, 358, 506, 312, 474, 329, 364, 5927, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 4463, 3088, 1283, 273, 2078, 2747, 3088, 1283, 300, 8735, 6275, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x251FAe8f687545BDD462Ba4FCDd7581051740463/sources/contracts/libraries/LibDiamond.sol
bubble up error @solidity memory-safe-assembly
function initializeDiamondCut(address _init, bytes memory _calldata) internal { if (_init == address(0)) { return; } enforceHasContractCode(_init, "LibDiamondCut: _init address has no code"); (bool success, bytes memory error) = _init.delegatecall(_calldata); if (!success) { if (error.length > 0) { assembly { let returndata_size := mload(error) revert(add(32, error), returndata_size) } revert("InitializationFunctionReverted(address, bytes)"); } } }
15,757,914
[ 1, 70, 14787, 731, 555, 632, 30205, 560, 3778, 17, 4626, 17, 28050, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4046, 14521, 301, 1434, 15812, 12, 2867, 389, 2738, 16, 1731, 3778, 389, 1991, 892, 13, 2713, 288, 203, 3639, 309, 261, 67, 2738, 422, 1758, 12, 20, 3719, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 12980, 5582, 8924, 1085, 24899, 2738, 16, 315, 5664, 14521, 301, 1434, 15812, 30, 389, 2738, 1758, 711, 1158, 981, 8863, 203, 3639, 261, 6430, 2216, 16, 1731, 3778, 555, 13, 273, 389, 2738, 18, 22216, 1991, 24899, 1991, 892, 1769, 203, 3639, 309, 16051, 4768, 13, 288, 203, 5411, 309, 261, 1636, 18, 2469, 405, 374, 13, 288, 203, 7734, 19931, 288, 203, 10792, 2231, 327, 892, 67, 1467, 519, 312, 945, 12, 1636, 13, 203, 10792, 15226, 12, 1289, 12, 1578, 16, 555, 3631, 327, 892, 67, 1467, 13, 203, 7734, 289, 203, 7734, 15226, 2932, 17701, 2083, 426, 25631, 12, 2867, 16, 1731, 2225, 1769, 203, 5411, 289, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* * MIT License * =========== */ // File: @openzeppelin/contracts/math/Math.sol pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { 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; } } // File: @openzeppelin/contracts/GSN/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: @openzeppelin/contracts/ownership/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 private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @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; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external ; function mint(address account, uint amount) external; /** * @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; /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * 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. */ 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. // 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 != 0x0 && codehash != accountHash); } /** * @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"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.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: contracts/IRewardDistributionRecipient.sol pragma solidity ^0.5.0; contract IRewardDistributionRecipient is Ownable { address rewardDistribution; function notifyRewardAmount(uint256 reward) external; modifier onlyRewardDistribution() { require(_msgSender() == rewardDistribution, "Caller is not reward distribution"); _; } function setRewardDistribution(address _rewardDistribution) external onlyOwner { rewardDistribution = _rewardDistribution; } } pragma solidity ^0.5.0; contract TokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public y = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7); //usdt uint256 private _totalSupply; mapping(address => uint256) private _balances; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function stake(uint256 amount) public { _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); y.transferFrom(msg.sender, address(this), amount); } function withdraw(uint256 amount) public { _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); y.transfer(msg.sender,amount); } } contract UsdtPoolReward is TokenWrapper, IRewardDistributionRecipient { IERC20 public trufCoin = IERC20(0x851C368D81076BAc2a1D09f004E5b23008a4F17D); uint256 public constant DURATION = 10 days; uint256 public initreward = 100000*1e18; uint256 public starttime ; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } constructor(uint256 _startTime) public{ starttime = _startTime; periodFinish = _startTime; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (totalSupply() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(totalSupply()) ); } function earned(address account) public view returns (uint256) { return balanceOf(account) .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } // stake visibility is public as overriding LPTokenWrapper's stake() function function stake(uint256 amount) public updateReward(msg.sender) checkhalve checkStart{ require(amount > 0, "Cannot stake 0"); super.stake(amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public updateReward(msg.sender) checkhalve checkStart{ require(amount > 0, "Cannot withdraw 0"); super.withdraw(amount); emit Withdrawn(msg.sender, amount); } function exit() external { withdraw(balanceOf(msg.sender)); getReward(); } function getReward() public updateReward(msg.sender) checkhalve checkStart{ uint256 reward = earned(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; require(trufCoin.balanceOf(address(this)) >0,"getReward: total truf is zero"); if(trufCoin.balanceOf(address(this)) <= reward){ reward = trufCoin.balanceOf(address(this)); } trufCoin.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } modifier checkhalve() { if (block.timestamp >= periodFinish && periodFinish == starttime) { rewardRate = initreward.div(DURATION); periodFinish = starttime.add(DURATION); emit RewardAdded(initreward); } _; } modifier checkStart(){ require(block.timestamp > starttime,"not start"); _; } function notifyRewardAmount(uint256 reward) external onlyRewardDistribution updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(DURATION); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(DURATION); } //jfi.mint(address(this),reward); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(DURATION); emit RewardAdded(reward); } }
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include the optional functions; to access them see {ERC20Detailed}./
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external ; function mint(address account, uint amount) external; 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; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); }
6,553,133
[ 1, 1358, 434, 326, 4232, 39, 3462, 4529, 487, 2553, 316, 326, 512, 2579, 18, 9637, 486, 2341, 326, 3129, 4186, 31, 358, 2006, 2182, 2621, 288, 654, 39, 3462, 40, 6372, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 654, 39, 3462, 288, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 3903, 274, 203, 565, 445, 312, 474, 12, 2867, 2236, 16, 2254, 3844, 13, 3903, 31, 203, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 7412, 1265, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 3903, 31, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.22; /// @title ERC-721に準拠した契約のインタフェース contract ERC721 { // イベント event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); // 必要なメソッド function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) external view returns (address _owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) public; function transferFrom(address _from, address _to, uint256 _tokenId) public; function totalSupply() public view returns (uint); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. * 契約が一時停止されている場合にのみアクションを許可する */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * 契約が一時停止されていない場合にのみアクションを許可する */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state * 一時停止するために所有者によって呼び出され、停止状態をトリガする */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state * ポーズをとるためにオーナーが呼び出し、通常の状態に戻ります */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } contract RocsCoreRe { function getRoc(uint _tokenId) public returns ( uint rocId, string dna, uint marketsFlg); function getRocIdToTokenId(uint _rocId) public view returns (uint); function getRocIndexToOwner(uint _rocId) public view returns (address); } contract ItemsBase is Pausable { // ハント代 uint public huntingPrice = 5 finney; function setHuntingPrice(uint256 price) public onlyOwner { huntingPrice = price; } // ERC721 event Transfer(address from, address to, uint tokenId); event ItemTransfer(address from, address to, uint tokenId); // Itemの作成 event ItemCreated(address owner, uint tokenId, uint ticketId); event HuntingCreated(uint huntingId, uint rocId); /// @dev Itemの構造体 struct Item { uint itemId; uint8 marketsFlg; uint rocId; uint8 equipmentFlg; } Item[] public items; // itemIdとtokenIdのマッピング mapping(uint => uint) public itemIndex; // itemIdからtokenIdを取得 function getItemIdToTokenId(uint _itemId) public view returns (uint) { return itemIndex[_itemId]; } /// @dev itemの所有するアドレスへのマッピング mapping (uint => address) public itemIndexToOwner; // @dev itemの所有者アドレスから所有するトークン数へのマッピング mapping (address => uint) public itemOwnershipTokenCount; /// @dev itemの呼び出しが承認されたアドレスへのマッピング mapping (uint => address) public itemIndexToApproved; /// @dev 特定のitem所有権をアドレスに割り当てます。 function _transfer(address _from, address _to, uint256 _tokenId) internal { itemOwnershipTokenCount[_to]++; itemOwnershipTokenCount[_from]--; itemIndexToOwner[_tokenId] = _to; // イベント開始 emit ItemTransfer(_from, _to, _tokenId); } address public rocCoreAddress; RocsCoreRe rocCore; function setRocCoreAddress(address _rocCoreAddress) public onlyOwner { rocCoreAddress = _rocCoreAddress; rocCore = RocsCoreRe(rocCoreAddress); } function getRocCoreAddress() external view onlyOwner returns ( address ) { return rocCore; } /// @dev Huntingの構造体 struct Hunting { uint huntingId; } // Huntingのmapping rocHuntingIndex[rocId][tokenId] = Hunting mapping(uint => mapping (uint => Hunting)) public rocHuntingIndex; /// @notice Huntingを作成して保存する内部メソッド。 /// @param _rocId /// @param _huntingId function _createRocHunting( uint _rocId, uint _huntingId ) internal returns (bool) { Hunting memory _hunting = Hunting({ huntingId: _huntingId }); rocHuntingIndex[_rocId][_huntingId] = _hunting; // HuntingCreatedイベント emit HuntingCreated(_huntingId, _rocId); return true; } } /// @title Item所有権を管理するコントラクト /// @dev OpenZeppelinのERC721ドラフト実装に準拠 contract ItemsOwnership is ItemsBase, ERC721 { /// @notice ERC721で定義されている、置き換え不可能なトークンの名前と記号。 string public constant name = "CryptoFeatherItems"; string public constant symbol = "CCHI"; bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('totalSupply()')); /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// この契約によって実装された標準化されたインタフェースでtrueを返します。 function supportsInterface(bytes4 _interfaceID) external view returns (bool) { // DEBUG ONLY //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } /// @dev 特定のアドレスに指定されたitemの現在の所有者であるかどうかをチェックします。 /// @param _claimant /// @param _tokenId function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return itemIndexToOwner[_tokenId] == _claimant; } /// @dev 特定のアドレスに指定されたitemが存在するかどうかをチェックします。 /// @param _claimant the address we are confirming kitten is approved for. /// @param _tokenId kitten id, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return itemIndexToApproved[_tokenId] == _claimant; } /// @dev 以前の承認を上書きして、transferFrom()に対して承認されたアドレスをマークします。 function _approve(uint256 _tokenId, address _approved) internal { itemIndexToApproved[_tokenId] = _approved; } // 指定されたアドレスのitem数を取得します。 function balanceOf(address _owner) public view returns (uint256 count) { return itemOwnershipTokenCount[_owner]; } /// @notice itemの所有者を変更します。 /// @dev ERC-721への準拠に必要 function transfer(address _to, uint256 _tokenId) public whenNotPaused { // 安全チェック require(_to != address(0)); // 自分のitemしか送ることはできません。 require(_owns(msg.sender, _tokenId)); // 所有権の再割り当て、保留中の承認のクリア、転送イベントの送信 _transfer(msg.sender, _to, _tokenId); } /// @notice transferFrom()を介して別のアドレスに特定のitemを転送する権利を与えます。 /// @dev ERC-721への準拠に必要 function approve(address _to, uint256 _tokenId) external whenNotPaused { // 所有者のみが譲渡承認を認めることができます。 require(_owns(msg.sender, _tokenId)); // 承認を登録します(以前の承認を置き換えます)。 _approve(_tokenId, _to); // 承認イベントを発行する。 emit Approval(msg.sender, _to, _tokenId); } /// @notice item所有者の変更を行います。を転送します。そのアドレスには、以前の所有者から転送承認が与えられています。 /// @dev ERC-721への準拠に必要 function transferFrom(address _from, address _to, uint256 _tokenId) public whenNotPaused { // 安全チェック。 require(_to != address(0)); // 承認と有効な所有権の確認 require(_approvedFor(msg.sender, _tokenId)); require(_owns(_from, _tokenId)); // 所有権を再割り当てします(保留中の承認をクリアし、転送イベントを発行します)。 _transfer(_from, _to, _tokenId); } /// @notice 現在存在するitemの総数を返します。 /// @dev ERC-721への準拠に必要です。 function totalSupply() public view returns (uint) { return items.length - 1; } /// @notice 指定されたitemの現在所有権が割り当てられているアドレスを返します。 /// @dev ERC-721への準拠に必要です。 function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = itemIndexToOwner[_tokenId]; require(owner != address(0)); } /// @dev この契約に所有権を割り当て、NFTを強制終了します。 /// @param _owner /// @param _tokenId function _escrow(address _owner, uint256 _tokenId) internal { // it will throw if transfer fails transferFrom(_owner, this, _tokenId); } } /// @title Itemに関する管理を行うコントラクト contract ItemsBreeding is ItemsOwnership { /// @notice Itemを作成して保存。 /// @param _itemId /// @param _marketsFlg /// @param _rocId /// @param _equipmentFlg /// @param _owner function _createItem( uint _itemId, uint _marketsFlg, uint _rocId, uint _equipmentFlg, address _owner ) internal returns (uint) { Item memory _item = Item({ itemId: _itemId, marketsFlg: uint8(_marketsFlg), rocId: _rocId, equipmentFlg: uint8(_equipmentFlg) }); uint newItemId = items.push(_item) - 1; // 同一のトークンIDが発生した場合は実行を停止します require(newItemId == uint(newItemId)); // RocCreatedイベント emit ItemCreated(_owner, newItemId, _itemId); // これにより所有権が割り当てられ、ERC721ドラフトごとに転送イベントが発行されます itemIndex[_itemId] = newItemId; _transfer(0, _owner, newItemId); return newItemId; } /// @notice アイテムの装備状態を更新します。 /// @param _reItems /// @param _inItems /// @param _rocId function equipmentItem( uint[] _reItems, uint[] _inItems, uint _rocId ) external whenNotPaused returns(bool) { uint checkTokenId = rocCore.getRocIdToTokenId(_rocId); uint i; uint itemTokenId; Item memory item; // 解除 for (i = 0; i < _reItems.length; i++) { itemTokenId = getItemIdToTokenId(_reItems[i]); // itemのパラメータチェック item = items[itemTokenId]; // マーケットへの出品中か確認してください。 require(uint(item.marketsFlg) == 0); // アイテム装着中か確認してください。 require(uint(item.equipmentFlg) == 1); // 装着チックが同一か確認してください。 require(uint(item.rocId) == _rocId); // 装備解除 items[itemTokenId].rocId = 0; items[itemTokenId].equipmentFlg = 0; // アイテムのオーナーが違えばチックのオーナーをセットしなおします。 address itemOwner = itemIndexToOwner[itemTokenId]; address checkOwner = rocCore.getRocIndexToOwner(checkTokenId); if (itemOwner != checkOwner) { itemIndexToOwner[itemTokenId] = checkOwner; } } // 装着 for (i = 0; i < _inItems.length; i++) { itemTokenId = getItemIdToTokenId(_inItems[i]); // itemのパラメータチェック item = items[itemTokenId]; // itemのオーナーである事 require(_owns(msg.sender, itemTokenId)); // マーケットへの出品中か確認してください。 require(uint(item.marketsFlg) == 0); // アイテム未装備か確認してください。 require(uint(item.equipmentFlg) == 0); // 装備処理 items[itemTokenId].rocId = _rocId; items[itemTokenId].equipmentFlg = 1; } return true; } /// @notice 消費した事で削除の処理を行います。 /// @param _itemId function usedItem( uint _itemId ) external whenNotPaused returns(bool) { uint itemTokenId = getItemIdToTokenId(_itemId); Item memory item = items[itemTokenId]; // itemのオーナーである事 require(_owns(msg.sender, itemTokenId)); // マーケットへの出品中か確認してください。 require(uint(item.marketsFlg) == 0); // アイテム未装備か確認してください。 require(uint(item.equipmentFlg) == 0); delete itemIndex[_itemId]; delete items[itemTokenId]; delete itemIndexToOwner[itemTokenId]; return true; } /// @notice Huntingの処理を行います。 /// @param _rocId /// @param _huntingId /// @param _items function processHunting( uint _rocId, uint _huntingId, uint[] _items ) external payable whenNotPaused returns(bool) { require(msg.value >= huntingPrice); uint checkTokenId = rocCore.getRocIdToTokenId(_rocId); uint marketsFlg; ( , , marketsFlg) = rocCore.getRoc(checkTokenId); // markets中か確認してください。 require(marketsFlg == 0); bool createHunting = false; // Hunting処理 require(_huntingId > 0); createHunting = _createRocHunting( _rocId, _huntingId ); uint i; for (i = 0; i < _items.length; i++) { _createItem( _items[i], 0, 0, 0, msg.sender ); } // 超過分を買い手に返す uint256 bidExcess = msg.value - huntingPrice; msg.sender.transfer(bidExcess); return createHunting; } /// @notice Itemを作成します。イベント用 /// @param _items /// @param _owners function createItems( uint[] _items, address[] _owners ) external onlyOwner returns (uint) { uint i; uint createItemId; for (i = 0; i < _items.length; i++) { createItemId = _createItem( _items[i], 0, 0, 0, _owners[i] ); } return createItemId; } } /// @title ItemのMarketに関する処理 contract ItemsMarkets is ItemsBreeding { event ItemMarketsCreated(uint256 tokenId, uint128 marketsPrice); event ItemMarketsSuccessful(uint256 tokenId, uint128 marketsPriceice, address buyer); event ItemMarketsCancelled(uint256 tokenId); // ERC721 event Transfer(address from, address to, uint tokenId); // NFT上のMarket struct ItemMarkets { // 登録時のNFT売手 address seller; // Marketの価格 uint128 marketsPrice; } // トークンIDから対応するマーケットへの出品にマップします。 mapping (uint256 => ItemMarkets) tokenIdToItemMarkets; // マーケットへの出品の手数料を設定 uint256 public ownerCut = 0; function setOwnerCut(uint256 _cut) public onlyOwner { require(_cut <= 10000); ownerCut = _cut; } /// @notice Itemマーケットへの出品を作成し、開始します。 /// @param _itemId /// @param _marketsPrice function createItemSaleMarkets( uint256 _itemId, uint256 _marketsPrice ) external whenNotPaused { require(_marketsPrice == uint256(uint128(_marketsPrice))); // チェック用のtokenIdをセット uint itemTokenId = getItemIdToTokenId(_itemId); // itemのオーナーである事 require(_owns(msg.sender, itemTokenId)); // itemのパラメータチェック Item memory item = items[itemTokenId]; // マーケットへの出品中か確認してください。 require(uint(item.marketsFlg) == 0); // 装備中か確認してください。 require(uint(item.rocId) == 0); require(uint(item.equipmentFlg) == 0); // 承認 _approve(itemTokenId, msg.sender); // マーケットへの出品セット _escrow(msg.sender, itemTokenId); ItemMarkets memory itemMarkets = ItemMarkets( msg.sender, uint128(_marketsPrice) ); // マーケットへの出品FLGをセット items[itemTokenId].marketsFlg = 1; _itemAddMarkets(itemTokenId, itemMarkets); } /// @dev マーケットへの出品を公開マーケットへの出品のリストに追加します。 /// また、ItemMarketsCreatedイベントを発生させます。 /// @param _tokenId The ID of the token to be put on markets. /// @param _markets Markets to add. function _itemAddMarkets(uint256 _tokenId, ItemMarkets _markets) internal { tokenIdToItemMarkets[_tokenId] = _markets; emit ItemMarketsCreated( uint256(_tokenId), uint128(_markets.marketsPrice) ); } /// @dev マーケットへの出品を公開マーケットへの出品のリストから削除します。 /// @param _tokenId function _itemRemoveMarkets(uint256 _tokenId) internal { delete tokenIdToItemMarkets[_tokenId]; } /// @dev 無条件にマーケットへの出品を取り消します。 /// @param _tokenId function _itemCancelMarkets(uint256 _tokenId) internal { _itemRemoveMarkets(_tokenId); emit ItemMarketsCancelled(_tokenId); } /// @dev まだ獲得されていないマーケットへの出品をキャンセルします。 /// 元の所有者にNFTを返します。 /// @notice これは、契約が一時停止している間に呼び出すことができる状態変更関数です。 /// @param _itemId function itemCancelMarkets(uint _itemId) external { uint itemTokenId = getItemIdToTokenId(_itemId); ItemMarkets storage markets = tokenIdToItemMarkets[itemTokenId]; address seller = markets.seller; require(msg.sender == seller); _itemCancelMarkets(itemTokenId); itemIndexToOwner[itemTokenId] = seller; items[itemTokenId].marketsFlg = 0; } /// @dev 契約が一時停止されたときにマーケットへの出品をキャンセルします。 /// 所有者だけがこれを行うことができ、NFTは売り手に返されます。 /// 緊急時にのみ使用してください。 /// @param _itemId function itemCancelMarketsWhenPaused(uint _itemId) whenPaused onlyOwner external { uint itemTokenId = getItemIdToTokenId(_itemId); ItemMarkets storage markets = tokenIdToItemMarkets[itemTokenId]; address seller = markets.seller; _itemCancelMarkets(itemTokenId); itemIndexToOwner[itemTokenId] = seller; items[itemTokenId].marketsFlg = 0; } /// @dev マーケットへの出品入札 /// 十分な量のEtherが供給されればNFTの所有権を移転する。 /// @param _itemId function itemBid(uint _itemId) external payable whenNotPaused { uint itemTokenId = getItemIdToTokenId(_itemId); // マーケットへの出品構造体への参照を取得する ItemMarkets storage markets = tokenIdToItemMarkets[itemTokenId]; uint128 sellingPrice = uint128(markets.marketsPrice); // 入札額が価格以上である事を確認する。 // msg.valueはweiの数 require(msg.value >= sellingPrice); // マーケットへの出品構造体が削除される前に、販売者への参照を取得します。 address seller = markets.seller; // マーケットへの出品を削除します。 _itemRemoveMarkets(itemTokenId); if (sellingPrice > 0) { // 競売人のカットを計算します。 uint128 marketseerCut = uint128(_computeCut(sellingPrice)); uint128 sellerProceeds = sellingPrice - marketseerCut; // 売り手に送金する seller.transfer(sellerProceeds); } // 超過分を買い手に返す msg.sender.transfer(msg.value - sellingPrice); // イベント emit ItemMarketsSuccessful(itemTokenId, sellingPrice, msg.sender); _transfer(seller, msg.sender, itemTokenId); // マーケットへの出品FLGをセット items[itemTokenId].marketsFlg = 0; } /// @dev 手数料計算 /// @param _price function _computeCut(uint128 _price) internal view returns (uint) { return _price * ownerCut / 10000; } } /// @title CryptoFeather contract ItemsCore is ItemsMarkets { // コア契約が壊れてアップグレードが必要な場合に設定します address public newContractAddress; /// @dev 一時停止を無効にすると、契約を一時停止する前にすべての外部契約アドレスを設定する必要があります。 function unpause() public onlyOwner whenPaused { require(newContractAddress == address(0)); // 実際に契約を一時停止しないでください。 super.unpause(); } // @dev 利用可能な残高を取得できるようにします。 function withdrawBalance(uint _subtractFees) external onlyOwner { uint256 balance = address(this).balance; if (balance > _subtractFees) { owner.transfer(balance - _subtractFees); } } /// @notice tokenIdからItemに関するすべての関連情報を返します。 /// @param _tokenId function getItem(uint _tokenId) external view returns ( uint itemId, uint marketsFlg, uint rocId, uint equipmentFlg ) { Item memory item = items[_tokenId]; itemId = uint(item.itemId); marketsFlg = uint(item.marketsFlg); rocId = uint(item.rocId); equipmentFlg = uint(item.equipmentFlg); } /// @notice itemIdからItemに関するすべての関連情報を返します。 /// @param _itemId function getItemItemId(uint _itemId) external view returns ( uint itemId, uint marketsFlg, uint rocId, uint equipmentFlg ) { Item memory item = items[getItemIdToTokenId(_itemId)]; itemId = uint(item.itemId); marketsFlg = uint(item.marketsFlg); rocId = uint(item.rocId); equipmentFlg = uint(item.equipmentFlg); } /// @notice itemIdからMarkets情報を返します。 /// @param _itemId function getMarketsItemId(uint _itemId) external view returns ( address seller, uint marketsPrice ) { uint itemTokenId = getItemIdToTokenId(_itemId); ItemMarkets storage markets = tokenIdToItemMarkets[itemTokenId]; seller = markets.seller; marketsPrice = uint(markets.marketsPrice); } /// @notice itemIdからオーナー情報を返します。 /// @param _itemId function getItemIndexToOwner(uint _itemId) external view returns ( address owner ) { uint itemTokenId = getItemIdToTokenId(_itemId); owner = itemIndexToOwner[itemTokenId]; } /// @notice rocIdとhuntingIdからhuntingの存在チェック /// @param _rocId /// @param _huntingId function getHunting(uint _rocId, uint _huntingId) public view returns ( uint huntingId ) { Hunting memory hunting = rocHuntingIndex[_rocId][_huntingId]; huntingId = uint(hunting.huntingId); } /// @notice _rocIdからオーナー情報を返します。 /// @param _rocId function getRocOwnerItem(uint _rocId) external view returns ( address owner ) { uint checkTokenId = rocCore.getRocIdToTokenId(_rocId); owner = rocCore.getRocIndexToOwner(checkTokenId); } }
@title CryptoFeather コア契約が壊れてアップグレードが必要な場合に設定します
contract ItemsCore is ItemsMarkets { address public newContractAddress; function unpause() public onlyOwner whenPaused { require(newContractAddress == address(0)); super.unpause(); } function withdrawBalance(uint _subtractFees) external onlyOwner { uint256 balance = address(this).balance; if (balance > _subtractFees) { owner.transfer(balance - _subtractFees); } } function withdrawBalance(uint _subtractFees) external onlyOwner { uint256 balance = address(this).balance; if (balance > _subtractFees) { owner.transfer(balance - _subtractFees); } } function getItem(uint _tokenId) external view returns ( uint itemId, uint marketsFlg, uint rocId, uint equipmentFlg ) { Item memory item = items[_tokenId]; itemId = uint(item.itemId); marketsFlg = uint(item.marketsFlg); rocId = uint(item.rocId); equipmentFlg = uint(item.equipmentFlg); } function getItemItemId(uint _itemId) external view returns ( uint itemId, uint marketsFlg, uint rocId, uint equipmentFlg ) { Item memory item = items[getItemIdToTokenId(_itemId)]; itemId = uint(item.itemId); marketsFlg = uint(item.marketsFlg); rocId = uint(item.rocId); equipmentFlg = uint(item.equipmentFlg); } function getMarketsItemId(uint _itemId) external view returns ( address seller, uint marketsPrice ) { uint itemTokenId = getItemIdToTokenId(_itemId); ItemMarkets storage markets = tokenIdToItemMarkets[itemTokenId]; seller = markets.seller; marketsPrice = uint(markets.marketsPrice); } function getItemIndexToOwner(uint _itemId) external view returns ( address owner ) { uint itemTokenId = getItemIdToTokenId(_itemId); owner = itemIndexToOwner[itemTokenId]; } function getHunting(uint _rocId, uint _huntingId) public view returns ( uint huntingId ) { Hunting memory hunting = rocHuntingIndex[_rocId][_huntingId]; huntingId = uint(hunting.huntingId); } function getRocOwnerItem(uint _rocId) external view returns ( address owner ) { uint checkTokenId = rocCore.getRocIdToTokenId(_rocId); owner = rocCore.getRocIndexToOwner(checkTokenId); } }
6,367,338
[ 1, 18048, 2954, 4806, 225, 164, 229, 116, 164, 229, 100, 166, 103, 244, 168, 117, 231, 164, 228, 239, 166, 101, 237, 164, 229, 239, 164, 228, 104, 164, 229, 100, 164, 230, 230, 164, 230, 250, 164, 229, 113, 164, 230, 110, 164, 230, 125, 164, 230, 236, 164, 228, 239, 166, 128, 232, 169, 104, 228, 164, 228, 108, 166, 259, 117, 166, 243, 235, 164, 228, 109, 169, 106, 260, 166, 111, 253, 164, 228, 250, 164, 228, 127, 164, 228, 252, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 10240, 4670, 353, 10240, 3882, 2413, 288, 203, 203, 565, 1758, 1071, 394, 8924, 1887, 31, 203, 203, 565, 445, 640, 19476, 1435, 1071, 1338, 5541, 1347, 28590, 288, 203, 3639, 2583, 12, 2704, 8924, 1887, 422, 1758, 12, 20, 10019, 203, 3639, 2240, 18, 318, 19476, 5621, 203, 565, 289, 203, 203, 565, 445, 598, 9446, 13937, 12, 11890, 389, 1717, 1575, 2954, 281, 13, 3903, 1338, 5541, 288, 203, 3639, 2254, 5034, 11013, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 3639, 309, 261, 12296, 405, 389, 1717, 1575, 2954, 281, 13, 288, 203, 5411, 3410, 18, 13866, 12, 12296, 300, 389, 1717, 1575, 2954, 281, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 598, 9446, 13937, 12, 11890, 389, 1717, 1575, 2954, 281, 13, 3903, 1338, 5541, 288, 203, 3639, 2254, 5034, 11013, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 3639, 309, 261, 12296, 405, 389, 1717, 1575, 2954, 281, 13, 288, 203, 5411, 3410, 18, 13866, 12, 12296, 300, 389, 1717, 1575, 2954, 281, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 8143, 12, 11890, 389, 2316, 548, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 203, 3639, 2254, 18424, 16, 203, 3639, 2254, 2267, 2413, 2340, 75, 16, 203, 3639, 2254, 721, 71, 548, 16, 203, 3639, 2254, 1298, 11568, 2340, 75, 203, 565, 262, 288, 203, 3639, 4342, 3778, 761, 273, 1516, 63, 67, 2316, 548, 15533, 203, 3639, 18424, 273, 2254, 12, 1726, 18, 1726, 548, 2 ]
./partial_match/1/0xbc6a1af02c09fc1514B95eC98756ccAa95e8Af2e/sources/GEtherBridge.sol
* @dev Retrieves the current market liquidity for a given cToken. @param _ctoken The Compound cToken address. @return _marketAmount The underlying reserve token available market liquidity./
function _getMarketAmount(address _ctoken) internal view returns (uint256 _marketAmount) { return CToken(_ctoken).getCash(); }
2,651,025
[ 1, 6960, 326, 783, 13667, 4501, 372, 24237, 364, 279, 864, 276, 1345, 18, 225, 389, 299, 969, 1021, 21327, 276, 1345, 1758, 18, 327, 389, 27151, 6275, 1021, 6808, 20501, 1147, 2319, 15604, 13667, 4501, 372, 24237, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 389, 588, 3882, 278, 6275, 12, 2867, 389, 299, 969, 13, 2713, 1476, 1135, 261, 11890, 5034, 389, 27151, 6275, 13, 203, 202, 95, 203, 202, 202, 2463, 385, 1345, 24899, 299, 969, 2934, 588, 39, 961, 5621, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xcAa9c61CC9F8F1774a01543FACeB9c3c263489c0/sources/contracts/vaults/Vault.sol
@notice See {IERC4626-previewRedeem}
function previewRedeem(uint256 shares) public view returns (uint256) { return _convertToAssets( shares.mulDiv(10_000 - _withdrawalFees, 10_000), MathUpgradeable.Rounding.Down ); }
16,512,982
[ 1, 9704, 288, 45, 654, 39, 8749, 5558, 17, 12102, 426, 24903, 97, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10143, 426, 24903, 12, 11890, 5034, 24123, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 203, 5411, 389, 6283, 774, 10726, 12, 203, 7734, 24123, 18, 16411, 7244, 12, 2163, 67, 3784, 300, 389, 1918, 9446, 287, 2954, 281, 16, 1728, 67, 3784, 3631, 203, 7734, 2361, 10784, 429, 18, 11066, 310, 18, 4164, 203, 5411, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; /** * @author Kelvin Fichter (@kelvinfichter) * @notice * * # Overview * Normally, this contract acts as a simple wallet with a single owner. * However, the owner also specifies a list of "beneficiaries" who can attempt * to "recover" the wallet by taking over ownership of the contract. * * # Default Behavior * The owner of this contract can send transactions out of the contract by * providing a destination, a transaction value, and some transaction data. * This allows the wallet to carry out any transaction that a standard keypair * could. * * # Recovery Process * This wallet provides a mechanism for the funds in the wallet to be recovered * in the case that the owner's keys are no longer accessible. One may want to * use this functionality to ensure that funds can be accessed in the case of * the owner's death. The owner specifies a set of "beneficiaries" who can * attempt to recover the wallet. It's possible, however, that a beneficiary * could attempt to steal the funds in the wallet. In order to prevent theft, * the beneficiary must place a *bond* to start the recovery attempt and must * wait for a *timeout window* to pass. Within the timeout window, the owner * can cancel the recovery attempt and take the beneficiary's bond. Once the * timeout window has passed, anyone may finalize the recovery process and * transfer ownership of the wallet to the recovering beneficiary. */ contract DeadXWallet { /* * Public Variables */ address public owner; mapping (address => bool) public beneficiaries; // Recovery parameters. uint256 public recoveryBond; uint256 public recoveryTimeout; // Information about a recovery attempt. address payable public recoverer; uint256 public recoveryStart; /* * Events */ event RecoveryStarted(address indexed _beneficiary); event RecoveryFinalized(address indexed _beneficiary); event RecoveryCancelled(); /* * Modifiers */ /** * @dev [Modifier] * @notice Only allows the owner to call the tagged method. */ modifier onlyOwner() { require( msg.sender == owner, "Method can only be called by the owner." ); _; } /** * @dev [Modifier] * @notice Only allows beneficiaries to call the tagged method. */ modifier onlyBeneficiary() { require( beneficiaries[msg.sender], "Method can only be called by a beneficiary." ); _; } /** * @dev [Modifier] * @notice Only allows calls with a sufficient bond. */ modifier onlyWithBond() { require( msg.value == recoveryBond, "Method can only be called with a sufficient bond." ); _; } /** * @dev [Modifier] * @notice Only allows calls when recovery is not active. */ modifier onlyWhileNotRecovering() { require( !isRecovering(), "Method can only be called if there is no active recovery attempt." ); _; } /** * @dev [Modifier] * @notice Only allows calls when recovery is active. */ modifier onlyWhileRecovering() { require( isRecovering(), "Method can only be called if there is an active recovery attempt." ); _; } /** * @dev [Modifier] * @notice Only allows calls when the recovery timeout is completed. */ modifier onlyWhenTimeoutCompleted() { require( timeoutCompleted(), "Method can only be called if the recovery timeout is completed." ); _; } /* * Public Functions */ /** * @dev [Fallback] * @notice Allows anyone to send funds to this address. */ function () external payable { } /** * @dev [Constructor] * @notice Sets the contract creator as the contract's owner. */ constructor() public { owner = msg.sender; recoveryBond = 1 ether; recoveryTimeout = 30 days; } /** * @notice Checks whether the contract has an active recovery attempt. * @return `true` if the contract has a recovery attempt, `false` * otherwise. */ function isRecovering() public view returns (bool) { return recoverer != address(0); } /** * @notice Checks whether the recovery timeout has been completed. * @return `true` if the timeout is completed, `false` otherwise. */ function timeoutCompleted() public view returns (bool) { return ( isRecovering() && (block.timestamp > recoveryStart + recoveryTimeout) ); } /** * @notice Allows the owner to send any arbitrary transaction. * @param _destination Address to send the transaction to. * @param _value Amount to send to the address in wei. * @param _data Data to send along with the transaction. */ function transact( address _destination, uint256 _value, bytes memory _data ) public onlyOwner returns (bytes memory) { (bool success, bytes memory result) = _destination.call.value(_value)(_data); require(success, "Transaction execution failed."); return result; } /** * @notice Adds a beneficiary to the wallet. * @param _beneficiary Address of the beneficiary. */ function addBeneficiary(address _beneficiary) public onlyOwner { beneficiaries[_beneficiary] = true; } /** * @notice Removes a beneficiary from the wallet. * @param _beneficiary Address of the beneficiary */ function removeBeneficiary(address _beneficiary) public onlyOwner { beneficiaries[_beneficiary] = false; } /** * @notice Changes the required recovery bond amount. * @param _bond New bond amount. */ function setRecoveryBond(uint256 _bond) public onlyOwner { recoveryBond = _bond; } /** * @notice Changes the length of the recovery timeout period. * @param _timeout New timeout period. */ function setRecoveryTimeout(uint256 _timeout) public onlyOwner { recoveryTimeout = _timeout; } /** * @notice Allows a beneficiary to start the recovery process. */ function startRecovery() public payable onlyBeneficiary onlyWithBond onlyWhileNotRecovering { recoverer = msg.sender; recoveryStart = block.timestamp; emit RecoveryStarted(msg.sender); } /** * @notice Allows the owner to cancel a recovery attempt. * @dev We only need to reset `recoverer` because the recovery attempt * can't be finalized if `recoverer` is the zero address. Only way to * set `recoverer` again is to start another recovery attempt, which * also resets `recoveryStart`. */ function cancelRecovery() public onlyOwner { recoverer = address(0); emit RecoveryCancelled(); } /** * @notice Allows anyone to finalize the recovery process once the recovery * timeout window has passed. Sets `recoverer` as the new owner. */ function finalizeRecovery() public onlyWhileRecovering onlyWhenTimeoutCompleted { owner = recoverer; recoverer = address(0); emit RecoveryFinalized(owner); } }
* @author Kelvin Fichter (@kelvinfichter) @notice # Overview Normally, this contract acts as a simple wallet with a single owner. However, the owner also specifies a list of "beneficiaries" who can attempt to "recover" the wallet by taking over ownership of the contract. # Default Behavior The owner of this contract can send transactions out of the contract by providing a destination, a transaction value, and some transaction data. This allows the wallet to carry out any transaction that a standard keypair could. # Recovery Process This wallet provides a mechanism for the funds in the wallet to be recovered in the case that the owner's keys are no longer accessible. One may want to use this functionality to ensure that funds can be accessed in the case of the owner's death. The owner specifies a set of "beneficiaries" who can attempt to recover the wallet. It's possible, however, that a beneficiary could attempt to steal the funds in the wallet. In order to prevent theft, the beneficiary must place a bond to start the recovery attempt and must wait for a timeout window to pass. Within the timeout window, the owner can cancel the recovery attempt and take the beneficiary's bond. Once the timeout window has passed, anyone may finalize the recovery process and transfer ownership of the wallet to the recovering beneficiary./ Recovery parameters. Information about a recovery attempt.
contract DeadXWallet { address public owner; mapping (address => bool) public beneficiaries; uint256 public recoveryBond; uint256 public recoveryTimeout; address payable public recoverer; uint256 public recoveryStart; event RecoveryStarted(address indexed _beneficiary); event RecoveryFinalized(address indexed _beneficiary); event RecoveryCancelled(); modifier onlyOwner() { require( msg.sender == owner, "Method can only be called by the owner." ); _; } modifier onlyBeneficiary() { require( beneficiaries[msg.sender], "Method can only be called by a beneficiary." ); _; } modifier onlyWithBond() { require( msg.value == recoveryBond, "Method can only be called with a sufficient bond." ); _; } modifier onlyWhileNotRecovering() { require( !isRecovering(), "Method can only be called if there is no active recovery attempt." ); _; } modifier onlyWhileRecovering() { require( isRecovering(), "Method can only be called if there is an active recovery attempt." ); _; } modifier onlyWhenTimeoutCompleted() { require( timeoutCompleted(), "Method can only be called if the recovery timeout is completed." ); _; } function () external payable { } constructor() public { owner = msg.sender; recoveryBond = 1 ether; recoveryTimeout = 30 days; } function isRecovering() public view returns (bool) { return recoverer != address(0); } function timeoutCompleted() public view returns (bool) { return ( isRecovering() && (block.timestamp > recoveryStart + recoveryTimeout) ); } function transact( address _destination, uint256 _value, bytes memory _data ) public onlyOwner returns (bytes memory) { (bool success, bytes memory result) = _destination.call.value(_value)(_data); require(success, "Transaction execution failed."); return result; } function addBeneficiary(address _beneficiary) public onlyOwner { beneficiaries[_beneficiary] = true; } function removeBeneficiary(address _beneficiary) public onlyOwner { beneficiaries[_beneficiary] = false; } function setRecoveryBond(uint256 _bond) public onlyOwner { recoveryBond = _bond; } function setRecoveryTimeout(uint256 _timeout) public onlyOwner { recoveryTimeout = _timeout; } function startRecovery() public payable onlyBeneficiary onlyWithBond onlyWhileNotRecovering { recoverer = msg.sender; recoveryStart = block.timestamp; emit RecoveryStarted(msg.sender); } function cancelRecovery() public onlyOwner { recoverer = address(0); emit RecoveryCancelled(); } function finalizeRecovery() public onlyWhileRecovering onlyWhenTimeoutCompleted { owner = recoverer; recoverer = address(0); emit RecoveryFinalized(owner); } }
13,084,989
[ 1, 47, 292, 21529, 478, 1354, 387, 261, 36, 79, 292, 90, 10625, 1354, 387, 13, 282, 10752, 1945, 24773, 1230, 16, 333, 6835, 22668, 487, 279, 4143, 9230, 598, 279, 2202, 3410, 18, 10724, 16, 326, 3410, 2546, 11470, 279, 666, 434, 315, 70, 4009, 74, 14463, 5646, 6, 10354, 848, 4395, 358, 315, 266, 3165, 6, 326, 9230, 635, 13763, 1879, 23178, 434, 326, 6835, 18, 225, 2989, 28030, 1021, 3410, 434, 333, 6835, 848, 1366, 8938, 596, 434, 326, 6835, 635, 17721, 279, 2929, 16, 279, 2492, 460, 16, 471, 2690, 2492, 501, 18, 1220, 5360, 326, 9230, 358, 9331, 596, 1281, 2492, 716, 279, 4529, 25298, 3377, 18, 225, 23675, 4389, 1220, 9230, 8121, 279, 12860, 364, 326, 284, 19156, 316, 326, 9230, 358, 506, 24616, 316, 326, 648, 716, 326, 3410, 1807, 1311, 854, 1158, 7144, 12718, 18, 6942, 2026, 2545, 358, 999, 333, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 23967, 60, 16936, 288, 203, 203, 377, 203, 565, 1758, 1071, 3410, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 27641, 74, 14463, 5646, 31, 203, 203, 565, 2254, 5034, 1071, 11044, 9807, 31, 203, 565, 2254, 5034, 1071, 11044, 2694, 31, 203, 203, 565, 1758, 8843, 429, 1071, 5910, 264, 31, 203, 565, 2254, 5034, 1071, 11044, 1685, 31, 203, 203, 203, 203, 565, 871, 23675, 9217, 12, 2867, 8808, 389, 70, 4009, 74, 14463, 814, 1769, 203, 565, 871, 23675, 7951, 1235, 12, 2867, 8808, 389, 70, 4009, 74, 14463, 814, 1769, 203, 565, 871, 23675, 21890, 5621, 203, 203, 203, 203, 565, 9606, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 15330, 422, 3410, 16, 203, 5411, 315, 1305, 848, 1338, 506, 2566, 635, 326, 3410, 1199, 203, 3639, 11272, 203, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 38, 4009, 74, 14463, 814, 1435, 288, 203, 3639, 2583, 12, 203, 5411, 27641, 74, 14463, 5646, 63, 3576, 18, 15330, 6487, 203, 5411, 315, 1305, 848, 1338, 506, 2566, 635, 279, 27641, 74, 14463, 814, 1199, 203, 3639, 11272, 203, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 1190, 9807, 1435, 288, 203, 3639, 2583, 12, 203, 5411, 1234, 18, 1132, 422, 11044, 9807, 16, 203, 5411, 315, 1305, 848, 1338, 506, 2566, 598, 279, 18662, 8427, 1199, 203, 3639, 11272, 203, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 15151, 1248, 2 ]
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-upgradeable/math/SignedSafeMathUpgradeable.sol"; import "../interface/IOracle.sol"; import "../libraries/OrderData.sol"; import "../libraries/SafeMathExt.sol"; import "../libraries/Utils.sol"; import "./AMMModule.sol"; import "./LiquidityPoolModule.sol"; import "./MarginAccountModule.sol"; import "./PerpetualModule.sol"; import "../Type.sol"; library TradeModule { using SafeMathExt for int256; using SignedSafeMathUpgradeable for int256; using OrderData for uint32; using AMMModule for LiquidityPoolStorage; using LiquidityPoolModule for LiquidityPoolStorage; using MarginAccountModule for PerpetualStorage; using PerpetualModule for PerpetualStorage; using MarginAccountModule for MarginAccount; event Trade( uint256 perpetualIndex, address indexed trader, int256 position, int256 price, int256 fee, int256 lpFee ); event Liquidate( uint256 perpetualIndex, address indexed liquidator, address indexed trader, int256 amount, int256 price, int256 penalty, int256 penaltyToLP ); event TransferFeeToOperator(address indexed operator, int256 operatorFee); event TransferFeeToReferrer( uint256 perpetualIndex, address indexed trader, address indexed referrer, int256 referralRebate ); /** * @dev See `trade` in Perpetual.sol for details. * * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of the perpetual in liquidity pool. * @param trader The address of trader. * @param amount The amount of position to trader, positive for buying and negative for selling. * @param limitPrice The worst price the trader accepts. * @param referrer The address of referrer who will get rebate in the deal. * @param flags The flags of the trade, contains extra config for trading. * @return tradeAmount The amount of positions actually traded in the transaction. */ function trade( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader, int256 amount, int256 limitPrice, address referrer, uint32 flags ) public returns (int256 tradeAmount) { (int256 deltaCash, int256 deltaPosition) = preTrade( liquidityPool, perpetualIndex, trader, amount, limitPrice, flags ); doTrade(liquidityPool, perpetualIndex, trader, deltaCash, deltaPosition); (int256 lpFee, int256 totalFee) = postTrade( liquidityPool, perpetualIndex, trader, referrer, deltaCash, deltaPosition, flags ); emit Trade( perpetualIndex, trader, deltaPosition.neg(), deltaCash.wdiv(deltaPosition).abs(), totalFee, lpFee ); tradeAmount = deltaPosition.neg(); require( liquidityPool.isTraderMarginSafe(perpetualIndex, trader, tradeAmount), "trader margin unsafe" ); } function preTrade( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader, int256 amount, int256 limitPrice, uint32 flags ) internal returns (int256 deltaCash, int256 deltaPosition) { PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; require(!IOracle(perpetual.oracle).isMarketClosed(), "market is closed now"); // handle close only flag if (flags.isCloseOnly()) { amount = getMaxPositionToClose(perpetual.getPosition(trader), amount); require(amount != 0, "no amount to close"); } // query price from AMM (deltaCash, deltaPosition) = liquidityPool.queryTradeWithAMM( perpetualIndex, amount.neg(), false ); // check price if (!flags.isMarketOrder()) { int256 tradePrice = deltaCash.wdiv(deltaPosition).abs(); validatePrice(amount >= 0, tradePrice, limitPrice); } } function doTrade( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader, int256 deltaCash, int256 deltaPosition ) internal { PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; int256 deltaOpenInterest1 = perpetual.updateMargin(address(this), deltaPosition, deltaCash); int256 deltaOpenInterest2 = perpetual.updateMargin( trader, deltaPosition.neg(), deltaCash.neg() ); require(perpetual.openInterest >= 0, "negative open interest"); if (deltaOpenInterest1.add(deltaOpenInterest2) > 0) { // open interest will increase, check limit (int256 poolMargin, ) = liquidityPool.getPoolMargin(); require( perpetual.openInterest <= perpetual.maxOpenInterestRate.wfrac(poolMargin, perpetual.getIndexPrice()), "open interest exceeds limit" ); } } /** * @dev Execute the trade. If the trader has opened position in the trade, his account should be * initial margin safe after the trade. If not, his account should be margin safe * * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of pereptual storage. * @param trader The address of trader. * @param referrer The address of referrer who will get rebate from the deal. * @param deltaCash The amount of cash changes in a trade. * @param deltaPosition The amount of position changes in a trade. * @return lpFee The amount of fee for lp provider. * @return totalFee The total fee collected from the trader after the trade. */ function postTrade( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader, address referrer, int256 deltaCash, int256 deltaPosition, uint32 flags ) internal returns (int256 lpFee, int256 totalFee) { PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; // fees int256 operatorFee; int256 vaultFee; int256 referralRebate; { bool hasOpened = Utils.hasOpenedPosition( perpetual.getPosition(trader), deltaPosition.neg() ); (lpFee, operatorFee, vaultFee, referralRebate) = getFees( liquidityPool, perpetual, trader, referrer, deltaCash.abs(), hasOpened ); } totalFee = lpFee.add(operatorFee).add(vaultFee).add(referralRebate); perpetual.updateCash(trader, totalFee.neg()); // trader deposit/withdraw if (flags.useTargetLeverage()) { liquidityPool.adjustMarginLeverage( perpetualIndex, trader, deltaPosition.neg(), deltaCash.neg(), totalFee ); } // send fee transferFee( liquidityPool, perpetualIndex, trader, referrer, lpFee, operatorFee, vaultFee, referralRebate ); } /** * @dev Get the fees of the trade. If the margin of the trader is not enough for fee: * 1. If trader open position, the trade will be reverted. * 2. If trader close position, the fee will be decreasing in proportion according to * the margin left in the trader's account * The rebate of referral will only calculate the lpFee and operatorFee. * The vault fee will not be counted in. * * @param liquidityPool The reference of liquidity pool storage. * @param perpetual The reference of pereptual storage. * @param trader The address of trader. * @param referrer The address of referrer who will get rebate from the deal. * @param tradeValue The amount of trading value, measured by collateral, abs of deltaCash. * @return lpFee The amount of fee to the Liquidity provider. * @return operatorFee The amount of fee to the operator. * @return vaultFee The amount of fee to the vault. * @return referralRebate The amount of rebate of the refferral. */ function getFees( LiquidityPoolStorage storage liquidityPool, PerpetualStorage storage perpetual, address trader, address referrer, int256 tradeValue, bool hasOpened ) public view returns ( int256 lpFee, int256 operatorFee, int256 vaultFee, int256 referralRebate ) { require(tradeValue >= 0, "trade value is negative"); vaultFee = tradeValue.wmul(liquidityPool.getVaultFeeRate()); lpFee = tradeValue.wmul(perpetual.lpFeeRate); if (liquidityPool.getOperator() != address(0)) { operatorFee = tradeValue.wmul(perpetual.operatorFeeRate); } int256 totalFee = lpFee.add(operatorFee).add(vaultFee); int256 availableMargin = perpetual.getAvailableMargin(trader, perpetual.getMarkPrice()); if (!hasOpened) { if (availableMargin <= 0) { lpFee = 0; operatorFee = 0; vaultFee = 0; referralRebate = 0; } else if (totalFee > availableMargin) { // make sure the sum of fees < available margin int256 rate = availableMargin.wdiv(totalFee, Round.FLOOR); operatorFee = operatorFee.wmul(rate, Round.FLOOR); vaultFee = vaultFee.wmul(rate, Round.FLOOR); lpFee = availableMargin.sub(operatorFee).sub(vaultFee); } } if ( referrer != address(0) && perpetual.referralRebateRate > 0 && lpFee.add(operatorFee) > 0 ) { int256 lpFeeRebate = lpFee.wmul(perpetual.referralRebateRate); int256 operatorFeeRabate = operatorFee.wmul(perpetual.referralRebateRate); referralRebate = lpFeeRebate.add(operatorFeeRabate); lpFee = lpFee.sub(lpFeeRebate); operatorFee = operatorFee.sub(operatorFeeRabate); } } function transferFee( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader, address referrer, int256 lpFee, int256 operatorFee, int256 vaultFee, int256 referralRebate ) internal { PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; perpetual.updateCash(address(this), lpFee); liquidityPool.transferFromPerpetualToUser(perpetual.id, referrer, referralRebate); liquidityPool.transferFromPerpetualToUser(perpetual.id, liquidityPool.getVault(), vaultFee); address operator = liquidityPool.getOperator(); liquidityPool.transferFromPerpetualToUser(perpetual.id, operator, operatorFee); emit TransferFeeToOperator(operator, operatorFee); emit TransferFeeToReferrer(perpetual.id, trader, referrer, referralRebate); } /** * @dev See `liquidateByAMM` in Perpetual.sol for details. * * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of the perpetual in liquidity pool. * @param liquidator The address of the account calling the liquidation method. * @param trader The address of the liquidated account. * @return liquidatedAmount The amount of positions actually liquidated in the transaction. */ function liquidateByAMM( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address liquidator, address trader ) public returns (int256 liquidatedAmount) { PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; require( !perpetual.isMaintenanceMarginSafe(trader, perpetual.getMarkPrice()), "trader is safe" ); int256 position = perpetual.getPosition(trader); // 0. price / amount (int256 deltaCash, int256 deltaPosition) = liquidityPool.queryTradeWithAMM( perpetualIndex, position, true ); require(deltaPosition != 0, "insufficient liquidity"); // 2. trade int256 liquidatePrice = deltaCash.wdiv(deltaPosition).abs(); perpetual.updateMargin(address(this), deltaPosition, deltaCash); perpetual.updateMargin( trader, deltaPosition.neg(), deltaCash.add(perpetual.keeperGasReward).neg() ); require(perpetual.openInterest >= 0, "negative open interest"); liquidityPool.transferFromPerpetualToUser( perpetual.id, liquidator, perpetual.keeperGasReward ); // 3. penalty min(markPrice * liquidationPenaltyRate, margin / position) * deltaPosition (int256 penalty, int256 penaltyToLiquidator) = postLiquidate( liquidityPool, perpetual, address(this), trader, position, deltaPosition.neg() ); emit Liquidate( perpetualIndex, address(this), trader, deltaPosition.neg(), liquidatePrice, penalty, penaltyToLiquidator ); liquidatedAmount = deltaPosition.neg(); } /** * @dev See `liquidateByTrader` in Perpetual.sol for details. * * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of the perpetual in liquidity pool. * @param liquidator The address of the account calling the liquidation method. * @param trader The address of the liquidated account. * @param amount The amount of position to be taken from liquidated trader. * @param limitPrice The worst price liquidator accepts. * @return liquidatedAmount The amount of positions actually liquidated in the transaction. */ function liquidateByTrader( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address liquidator, address trader, int256 amount, int256 limitPrice ) public returns (int256 liquidatedAmount) { PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; int256 markPrice = perpetual.getMarkPrice(); require(!perpetual.isMaintenanceMarginSafe(trader, markPrice), "trader is safe"); // 0. price / amount validatePrice(amount >= 0, markPrice, limitPrice); int256 position = perpetual.getPosition(trader); int256 deltaPosition = getMaxPositionToClose(position, amount.neg()).neg(); int256 deltaCash = markPrice.wmul(deltaPosition).neg(); // 1. execute perpetual.updateMargin(liquidator, deltaPosition, deltaCash); perpetual.updateMargin(trader, deltaPosition.neg(), deltaCash.neg()); require(perpetual.openInterest >= 0, "negative open interest"); // 2. penalty min(markPrice * liquidationPenaltyRate, margin / position) * deltaPosition (int256 penalty, ) = postLiquidate( liquidityPool, perpetual, liquidator, trader, position, deltaPosition.neg() ); liquidatedAmount = deltaPosition.neg(); require( liquidityPool.isTraderMarginSafe(perpetualIndex, liquidator, liquidatedAmount), "liquidator margin unsafe" ); emit Liquidate(perpetualIndex, liquidator, trader, liquidatedAmount, markPrice, penalty, 0); } /** * @dev Handle liquidate penalty / fee. * * @param liquidityPool The reference of liquidity pool storage. * @param perpetual The reference of perpetual storage. * @param liquidator The address of the account calling the liquidation method. * @param trader The address of the liquidated account. * @param position The amount of position owned by trader before liquidation. * @param deltaPosition The amount of position to be taken from liquidated trader. * @return penalty The amount of positions actually liquidated in the transaction. * @return penaltyToLiquidator The amount of positions actually liquidated in the transaction. */ function postLiquidate( LiquidityPoolStorage storage liquidityPool, PerpetualStorage storage perpetual, address liquidator, address trader, int256 position, int256 deltaPosition ) public returns (int256 penalty, int256 penaltyToLiquidator) { int256 vaultFee = 0; { int256 markPrice = perpetual.getMarkPrice(); int256 remainingMargin = perpetual.getMargin(trader, markPrice); int256 liquidationValue = markPrice.wmul(deltaPosition).abs(); penalty = liquidationValue.wmul(perpetual.liquidationPenaltyRate).min( remainingMargin.wfrac(deltaPosition.abs(), position.abs()) ); remainingMargin = remainingMargin.sub(penalty); if (remainingMargin > 0) { vaultFee = liquidationValue.wmul(liquidityPool.getVaultFeeRate()).min( remainingMargin ); liquidityPool.transferFromPerpetualToUser( perpetual.id, liquidityPool.getVault(), vaultFee ); } } int256 penaltyToFund; bool isEmergency; if (penalty > 0) { penaltyToFund = penalty.wmul(perpetual.insuranceFundRate); penaltyToLiquidator = penalty.sub(penaltyToFund); } else { int256 totalInsuranceFund = liquidityPool.insuranceFund.add( liquidityPool.donatedInsuranceFund ); if (totalInsuranceFund.add(penalty) < 0) { // ensure donatedInsuranceFund >= 0 penalty = totalInsuranceFund.neg(); isEmergency = true; } penaltyToFund = penalty; penaltyToLiquidator = 0; } int256 penaltyToLP = liquidityPool.updateInsuranceFund(penaltyToFund); perpetual.updateCash(address(this), penaltyToLP); perpetual.updateCash(liquidator, penaltyToLiquidator); perpetual.updateCash(trader, penalty.add(vaultFee).neg()); if (penaltyToFund >= 0) { perpetual.decreaseTotalCollateral(penaltyToFund.sub(penaltyToLP)); } else { // penaltyToLP = 0 when penaltyToFund < 0 perpetual.increaseTotalCollateral(penaltyToFund.neg()); } if (isEmergency) { liquidityPool.setEmergencyState(perpetual.id); } } /** * @dev Get the max position amount of trader will be closed in the trade. * @param position Current position of trader. * @param amount The trading amount of position. * @return maxPositionToClose The max position amount of trader will be closed in the trade. */ function getMaxPositionToClose(int256 position, int256 amount) internal pure returns (int256 maxPositionToClose) { require(position != 0, "trader has no position to close"); require(!Utils.hasTheSameSign(position, amount), "trader must be close only"); maxPositionToClose = amount.abs() > position.abs() ? position.neg() : amount; } /** * @dev Check if the price is better than the limit price. * @param isLong True if the side is long. * @param price The price to be validate. * @param priceLimit The limit price. */ function validatePrice( bool isLong, int256 price, int256 priceLimit ) internal pure { require(price > 0, "price must be positive"); bool isPriceSatisfied = isLong ? price <= priceLimit : price >= priceLimit; require(isPriceSatisfied, "price exceeds limit"); } /** * @dev A readonly version of trade * * This function was written post-audit. So there's a lot of repeated logic here. * NOTE: max openInterest is NOT exact the same as trade(). In this function, poolMargin * will be smaller, so that the openInterst limit is also smaller (more strict). * @param liquidityPool The reference of liquidity pool storage. * @param perpetualIndex The index of the perpetual in liquidity pool. * @param trader The address of trader. * @param amount The amount of position to trader, positive for buying and negative for selling. * @param flags The flags of the trade, contains extra config for trading. * @return tradePrice The average fill price. * @return totalFee The total fee collected from the trader after the trade. * @return cost Deposit or withdraw to let effective leverage == targetLeverage if flags contain USE_TARGET_LEVERAGE. > 0 if deposit, < 0 if withdraw. */ function queryTrade( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader, int256 amount, address referrer, uint32 flags ) public returns ( int256 tradePrice, int256 totalFee, int256 cost ) { PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; MarginAccount memory account = perpetual.marginAccounts[trader]; // clone (int256 deltaCash, int256 deltaPosition) = preTrade( liquidityPool, perpetualIndex, trader, amount, amount > 0 ? type(int256).max : 0, flags ); tradePrice = deltaCash.wdiv(deltaPosition).abs(); readonlyDoTrade(liquidityPool, perpetual, account, deltaCash, deltaPosition); (totalFee, cost) = readonlyPostTrade( liquidityPool, perpetual, account, referrer, deltaCash, deltaPosition, flags ); } // A readonly version of doTrade. This function was written post-audit. So there's a lot of repeated logic here. // NOTE: max openInterest is NOT exact the same as trade(). In this function, poolMargin // will be smaller, so that the openInterst limit is also smaller (more strict). function readonlyDoTrade( LiquidityPoolStorage storage liquidityPool, PerpetualStorage storage perpetual, MarginAccount memory account, int256 deltaCash, int256 deltaPosition ) internal view { int256 deltaOpenInterest1; int256 deltaOpenInterest2; (, , deltaOpenInterest1) = readonlyUpdateMargin( perpetual, perpetual.marginAccounts[address(this)].cash, perpetual.marginAccounts[address(this)].position, deltaPosition, deltaCash ); (account.cash, account.position, deltaOpenInterest2) = readonlyUpdateMargin( perpetual, account.cash, account.position, deltaPosition.neg(), deltaCash.neg() ); int256 perpetualOpenInterest = perpetual.openInterest.add(deltaOpenInterest1).add( deltaOpenInterest2 ); require(perpetualOpenInterest >= 0, "negative open interest"); if (deltaOpenInterest1.add(deltaOpenInterest2) > 0) { // open interest will increase, check limit (int256 poolMargin, ) = liquidityPool.getPoolMargin(); // NOTE: this is a slight different from trade() require( perpetualOpenInterest <= perpetual.maxOpenInterestRate.wfrac(poolMargin, perpetual.getIndexPrice()), "open interest exceeds limit" ); } } // A readonly version of postTrade. This function was written post-audit. So there's a lot of repeated logic here. function readonlyPostTrade( LiquidityPoolStorage storage liquidityPool, PerpetualStorage storage perpetual, MarginAccount memory account, address referrer, int256 deltaCash, int256 deltaPosition, uint32 flags ) internal view returns (int256 totalFee, int256 adjustCollateral) { // fees int256 lpFee; int256 operatorFee; int256 vaultFee; int256 referralRebate; { bool hasOpened = Utils.hasOpenedPosition(account.position, deltaPosition.neg()); (lpFee, operatorFee, vaultFee, referralRebate) = readonlyGetFees( liquidityPool, perpetual, account, referrer, deltaCash.abs(), hasOpened ); } totalFee = lpFee.add(operatorFee).add(vaultFee).add(referralRebate); // was updateCash account.cash = account.cash.add(totalFee.neg()); // trader deposit/withdraw if (flags.useTargetLeverage()) { adjustCollateral = LiquidityPoolModule.readonlyAdjustMarginLeverage( perpetual, account, deltaPosition.neg(), deltaCash.neg(), totalFee ); } account.cash = account.cash.add(adjustCollateral); } // A readonly version of MarginAccountModule.updateMargin. This function was written post-audit. So there's a lot of repeated logic here. function readonlyUpdateMargin( PerpetualStorage storage perpetual, int256 oldCash, int256 oldPosition, int256 deltaPosition, int256 deltaCash ) internal view returns ( int256 newCash, int256 newPosition, int256 deltaOpenInterest ) { newPosition = oldPosition.add(deltaPosition); newCash = oldCash.add(deltaCash).add(perpetual.unitAccumulativeFunding.wmul(deltaPosition)); if (oldPosition > 0) { deltaOpenInterest = oldPosition.neg(); } if (newPosition > 0) { deltaOpenInterest = deltaOpenInterest.add(newPosition); } } // A readonly version of getFees. This function was written post-audit. So there's a lot of repeated logic here. function readonlyGetFees( LiquidityPoolStorage storage liquidityPool, PerpetualStorage storage perpetual, MarginAccount memory trader, address referrer, int256 tradeValue, bool hasOpened ) public view returns ( int256 lpFee, int256 operatorFee, int256 vaultFee, int256 referralRebate ) { require(tradeValue >= 0, "trade value is negative"); vaultFee = tradeValue.wmul(liquidityPool.getVaultFeeRate()); lpFee = tradeValue.wmul(perpetual.lpFeeRate); if (liquidityPool.getOperator() != address(0)) { operatorFee = tradeValue.wmul(perpetual.operatorFeeRate); } int256 totalFee = lpFee.add(operatorFee).add(vaultFee); int256 availableMargin = LiquidityPoolModule.readonlyGetAvailableMargin( perpetual, trader, perpetual.getMarkPrice() ); if (!hasOpened) { if (availableMargin <= 0) { lpFee = 0; operatorFee = 0; vaultFee = 0; referralRebate = 0; } else if (totalFee > availableMargin) { // make sure the sum of fees < available margin int256 rate = availableMargin.wdiv(totalFee, Round.FLOOR); operatorFee = operatorFee.wmul(rate, Round.FLOOR); vaultFee = vaultFee.wmul(rate, Round.FLOOR); lpFee = availableMargin.sub(operatorFee).sub(vaultFee); } } if ( referrer != address(0) && perpetual.referralRebateRate > 0 && lpFee.add(operatorFee) > 0 ) { int256 lpFeeRebate = lpFee.wmul(perpetual.referralRebateRate); int256 operatorFeeRabate = operatorFee.wmul(perpetual.referralRebateRate); referralRebate = lpFeeRebate.add(operatorFeeRabate); lpFee = lpFee.sub(lpFeeRebate); operatorFee = operatorFee.sub(operatorFeeRabate); } } }
open interest will increase, check limit
function doTrade( LiquidityPoolStorage storage liquidityPool, uint256 perpetualIndex, address trader, int256 deltaCash, int256 deltaPosition ) internal { PerpetualStorage storage perpetual = liquidityPool.perpetuals[perpetualIndex]; int256 deltaOpenInterest1 = perpetual.updateMargin(address(this), deltaPosition, deltaCash); int256 deltaOpenInterest2 = perpetual.updateMargin( trader, deltaPosition.neg(), deltaCash.neg() ); require(perpetual.openInterest >= 0, "negative open interest"); if (deltaOpenInterest1.add(deltaOpenInterest2) > 0) { (int256 poolMargin, ) = liquidityPool.getPoolMargin(); require( perpetual.openInterest <= perpetual.maxOpenInterestRate.wfrac(poolMargin, perpetual.getIndexPrice()), "open interest exceeds limit" ); } }
12,615,773
[ 1, 3190, 16513, 903, 10929, 16, 866, 1800, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 741, 22583, 12, 203, 3639, 511, 18988, 24237, 2864, 3245, 2502, 4501, 372, 24237, 2864, 16, 203, 3639, 2254, 5034, 1534, 6951, 1462, 1016, 16, 203, 3639, 1758, 1284, 765, 16, 203, 3639, 509, 5034, 3622, 39, 961, 16, 203, 3639, 509, 5034, 3622, 2555, 203, 565, 262, 2713, 288, 203, 3639, 5722, 6951, 1462, 3245, 2502, 1534, 6951, 1462, 273, 4501, 372, 24237, 2864, 18, 457, 6951, 12588, 63, 457, 6951, 1462, 1016, 15533, 203, 3639, 509, 5034, 3622, 3678, 29281, 21, 273, 1534, 6951, 1462, 18, 2725, 9524, 12, 2867, 12, 2211, 3631, 3622, 2555, 16, 3622, 39, 961, 1769, 203, 3639, 509, 5034, 3622, 3678, 29281, 22, 273, 1534, 6951, 1462, 18, 2725, 9524, 12, 203, 5411, 1284, 765, 16, 203, 5411, 3622, 2555, 18, 14518, 9334, 203, 5411, 3622, 39, 961, 18, 14518, 1435, 203, 3639, 11272, 203, 3639, 2583, 12, 457, 6951, 1462, 18, 3190, 29281, 1545, 374, 16, 315, 13258, 1696, 16513, 8863, 203, 3639, 309, 261, 9878, 3678, 29281, 21, 18, 1289, 12, 9878, 3678, 29281, 22, 13, 405, 374, 13, 288, 203, 5411, 261, 474, 5034, 2845, 9524, 16, 262, 273, 4501, 372, 24237, 2864, 18, 588, 2864, 9524, 5621, 203, 5411, 2583, 12, 203, 7734, 1534, 6951, 1462, 18, 3190, 29281, 1648, 203, 10792, 1534, 6951, 1462, 18, 1896, 3678, 29281, 4727, 18, 15581, 8836, 12, 6011, 9524, 16, 1534, 6951, 1462, 18, 588, 1016, 5147, 1435, 3631, 203, 7734, 315, 3190, 16513, 14399, 1800, 6, 203, 5411, 11272, 203, 3639, 289, 203, 2 ]
./partial_match/1/0x2473B05F32a5F0D6767c8b46C3A1d079D769b055/sources/Pacmoon.sol
only take fees on buys/sells, do not take on wallet transfers on sell on buy
function _transfer( address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if (amount == 0) { super._transfer(from, to, 0); return; } if (limitsInEffect) { if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ) { if (!tradingActive) { require( _isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active." ); } {require( amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {require( amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); require( amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if ( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if (takeFee) { if (automatedMarketMakerPairs[to] && sellMarketingFee > 0) { fees = amount.mul(sellMarketingFee).div(100); } else if (automatedMarketMakerPairs[from] && buyMarketingFee > 0) { fees = amount.mul(buyMarketingFee).div(100); } if (fees > 0) { super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); }
15,935,228
[ 1, 3700, 4862, 1656, 281, 603, 25666, 1900, 19, 87, 1165, 87, 16, 741, 486, 4862, 603, 9230, 29375, 603, 357, 80, 603, 30143, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 1758, 628, 16, 1758, 358, 16, 2254, 5034, 3844, 13, 2713, 3849, 288, 203, 3639, 2583, 12, 2080, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 628, 326, 3634, 1758, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 3462, 30, 7412, 358, 326, 3634, 1758, 8863, 7010, 203, 3639, 309, 261, 8949, 422, 374, 13, 288, 203, 5411, 2240, 6315, 13866, 12, 2080, 16, 358, 16, 374, 1769, 203, 5411, 327, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 14270, 382, 12477, 13, 288, 203, 5411, 309, 261, 203, 7734, 628, 480, 3410, 1435, 597, 203, 7734, 358, 480, 3410, 1435, 597, 203, 7734, 358, 480, 1758, 12, 20, 13, 597, 203, 7734, 358, 480, 1758, 12, 20, 92, 22097, 13, 597, 203, 7734, 401, 22270, 1382, 203, 5411, 262, 288, 203, 7734, 309, 16051, 313, 14968, 3896, 13, 288, 203, 10792, 2583, 12, 203, 13491, 389, 291, 16461, 1265, 2954, 281, 63, 2080, 65, 747, 389, 291, 16461, 1265, 2954, 281, 63, 869, 6487, 203, 13491, 315, 1609, 7459, 353, 486, 2695, 1199, 203, 10792, 11272, 203, 7734, 289, 203, 203, 10792, 288, 6528, 12, 3844, 1648, 943, 3342, 6275, 16, 203, 13491, 315, 38, 9835, 7412, 3844, 14399, 326, 943, 3342, 6275, 1199, 1769, 203, 5397, 2583, 12, 203, 13491, 3844, 397, 11013, 951, 12, 869, 13, 1648, 943, 16936, 16, 203, 13491, 315, 2747, 9230, 12428, 8863, 203, 7734, 289, 203, 10792, 18472, 690, 3882, 278, 2 ]
./partial_match/1/0xAF358B898E645189952a2c5Af6cD977450836ee6/sources/HashBet.sol
Set default house edge percent
function setDefaultHouseEdgePercent(uint _houseEdgePercent) external onlyOwner { require( _houseEdgePercent >= 1 && _houseEdgePercent <= 100, "houseEdgePercent must be a sane number" ); defaultHouseEdgePercent = _houseEdgePercent; }
9,256,002
[ 1, 694, 805, 23867, 3591, 5551, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 9277, 44, 3793, 6098, 8410, 12, 11890, 389, 13028, 6098, 8410, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 203, 5411, 389, 13028, 6098, 8410, 1545, 404, 597, 389, 13028, 6098, 8410, 1648, 2130, 16, 203, 5411, 315, 13028, 6098, 8410, 1297, 506, 279, 30426, 1300, 6, 203, 3639, 11272, 203, 3639, 805, 44, 3793, 6098, 8410, 273, 389, 13028, 6098, 8410, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x25C7C475934f40908523a36d5d7ea810D890b50F/sources/contracts/L1/Colosseum.sol
* @notice Validates and updates the lengths of segments. @param _segmentsLengths Lengths of segments./ _segmentsLengths length should be an even number in order to let challenger submit invalidity proof at the last turn.
function _setSegmentsLengths(uint256[] memory _segmentsLengths) private { require( _segmentsLengths.length % 2 == 0, "Colosseum: length of segments lengths cannot be odd number" ); uint256 sum = 1; for (uint256 i = 0; i < _segmentsLengths.length; ) { segmentsLengths[i] = _segmentsLengths[i]; sum = sum * (_segmentsLengths[i] - 1); unchecked { ++i; } } require(sum == L2_ORACLE_SUBMISSION_INTERVAL, "Colosseum: invalid segments lengths"); }
16,186,944
[ 1, 9594, 471, 4533, 326, 10917, 434, 5155, 18, 225, 389, 12838, 22406, 11311, 87, 434, 5155, 18, 19, 389, 12838, 22406, 769, 1410, 506, 392, 5456, 1300, 316, 1353, 358, 2231, 462, 7862, 693, 4879, 2057, 560, 14601, 622, 326, 1142, 7005, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 542, 7946, 22406, 12, 11890, 5034, 8526, 3778, 389, 12838, 22406, 13, 3238, 288, 203, 3639, 2583, 12, 203, 5411, 389, 12838, 22406, 18, 2469, 738, 576, 422, 374, 16, 203, 5411, 315, 914, 538, 307, 379, 30, 769, 434, 5155, 10917, 2780, 506, 14800, 1300, 6, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 2142, 273, 404, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 12838, 22406, 18, 2469, 31, 262, 288, 203, 5411, 5155, 22406, 63, 77, 65, 273, 389, 12838, 22406, 63, 77, 15533, 203, 5411, 2142, 273, 2142, 380, 261, 67, 12838, 22406, 63, 77, 65, 300, 404, 1769, 203, 203, 5411, 22893, 288, 203, 7734, 965, 77, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 2583, 12, 1364, 422, 511, 22, 67, 916, 2226, 900, 67, 8362, 15566, 67, 16435, 16, 315, 914, 538, 307, 379, 30, 2057, 5155, 10917, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.2; import "../registry/AbstractRNS.sol"; import "../util/AbstractWhitelist.sol"; import "../resolver/AbstractAddrResolver.sol"; /** * @title SubdomainRegistrar * Allows anyone who is whitelisted to create subnodes under a given RNS node */ contract SubdomainRegistrar { address public owner = msg.sender; AbstractRNS public rns; AbstractWhitelist public whitelist; bytes32 public rootNode; bytes4 constant ADDR_SIGN = 0x3b3b57de; modifier onlyOwner () { require(msg.sender == owner); _; } modifier onlyManager () { require(whitelist.isAManager(msg.sender)); _; } /** * @dev Constructor * @param _rns AbstractRNS RNS registry address. * @param _whitelist AbstractWhitelist Whitelist to manage who can register domains. * @param _rootNode bytes32 An owned node. The contract emits subnodes under this node. */ constructor (AbstractRNS _rns, AbstractWhitelist _whitelist, bytes32 _rootNode) public { rns = _rns; whitelist = _whitelist; rootNode = _rootNode; } /** * @dev Registrers a subnode under a given and delegated node. * @param label bytres32 The label of the new subnode. */ function register (bytes32 label, address addr) public onlyManager() { bytes32 subnode = keccak256(abi.encodePacked(rootNode, label)); require(rns.owner(subnode) == address(0)); AbstractAddrResolver resolver = AbstractAddrResolver(rns.resolver(rootNode)); require(resolver.supportsInterface(ADDR_SIGN)); rns.setSubnodeOwner(rootNode, label, address(this)); resolver.setAddr(subnode, addr); rns.setOwner(subnode, addr); } /** * @dev Transfers back the root node ownership to the contract's owner. */ function transferOwnershipBack () public onlyOwner() { rns.setOwner(rootNode, owner); } }
* @dev Constructor @param _rns AbstractRNS RNS registry address. @param _whitelist AbstractWhitelist Whitelist to manage who can register domains. @param _rootNode bytes32 An owned node. The contract emits subnodes under this node./
constructor (AbstractRNS _rns, AbstractWhitelist _whitelist, bytes32 _rootNode) public { rns = _rns; whitelist = _whitelist; rootNode = _rootNode; }
6,479,654
[ 1, 6293, 225, 389, 86, 2387, 4115, 54, 3156, 534, 3156, 4023, 1758, 18, 225, 389, 20409, 4115, 18927, 3497, 7523, 358, 10680, 10354, 848, 1744, 10128, 18, 225, 389, 3085, 907, 1731, 1578, 1922, 16199, 756, 18, 1021, 6835, 24169, 720, 4690, 3613, 333, 756, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 261, 7469, 54, 3156, 389, 86, 2387, 16, 4115, 18927, 389, 20409, 16, 1731, 1578, 389, 3085, 907, 13, 1071, 288, 203, 3639, 436, 2387, 273, 389, 86, 2387, 31, 203, 3639, 10734, 273, 389, 20409, 31, 203, 3639, 10181, 273, 389, 3085, 907, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.1; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; interface IMinterFactory { function mintTo(address to, address tokenAddress) external; } contract ComboStaking is Ownable { using SafeERC20 for IERC20; uint256 public constant MIN_STAKING_VALUE = 25000 * 10 ** 18; enum StakingLevel { SIMPLE, UNCOMMON, RARE, EPIC, LEGENDARY } struct RewardRule { uint256 apr; uint256 period; address nftHero; } struct Staking { uint256 timestamp; uint256 amount; uint256 rewarded; StakingLevel targetLevel; StakingLevel rewardedLevel; bool isCompleted; bool isInitialized; } struct UserStaking { mapping(uint256 => Staking) stakings; mapping(uint256 => bool) activeStakings; uint256 stakingNumber; } mapping(address => UserStaking) private stakers; mapping(StakingLevel => RewardRule) public rewardRules; uint256 public totalStaked; IERC20 public taleToken; IMinterFactory public minterFactory; event Stake(address indexed staker, uint256 amount, StakingLevel targetLevel); event TaleReward(address indexed staker, uint256 amount, uint256 reward); event NftReward(address indexed staker, address taleHero); constructor(address _taleToken, address _minterFactory) { taleToken = IERC20(_taleToken); minterFactory = IMinterFactory(_minterFactory); rewardRules[StakingLevel.SIMPLE] = RewardRule(15, 15 days, address(0)); rewardRules[StakingLevel.UNCOMMON] = RewardRule(30, 30 days, address(0)); rewardRules[StakingLevel.RARE] = RewardRule(50, 50 days, address(0)); rewardRules[StakingLevel.EPIC] = RewardRule(75, 75 days, address(0)); rewardRules[StakingLevel.LEGENDARY] = RewardRule(100, 100 days, address(0)); } /** * @notice Starts a new staking. * * @param amount Amount of tokens to stake. * @param targetLevel Type of staking, see StakingLevel enum and rewardRules. */ function stake(uint256 amount, StakingLevel targetLevel) external { require(amount >= MIN_STAKING_VALUE, "TaleStaking: Minimum staking amount 25000TALE"); address staker = _msgSender(); //check erc20 balance and allowance require(taleToken.balanceOf(staker) >= amount, "TaleStaking: Insufficient tokens"); require(taleToken.allowance(staker, address(this)) >= amount, "TaleStaking: Not enough tokens allowed"); uint stakingId = stakers[staker].stakingNumber; stakers[staker].stakingNumber = stakingId + 1; stakers[staker].stakings[stakingId] = Staking(block.timestamp, amount, 0, targetLevel, StakingLevel.SIMPLE, false, true); stakers[staker].activeStakings[stakingId] = true; totalStaked += amount; taleToken.safeTransferFrom(staker, address(this), amount); emit Stake(staker, amount, targetLevel); } /** * @notice Pays rewards and withdraws the specified amount of tokens from staking. * * @param stakingId Id of staking; */ function claim(uint256 stakingId) external { address staker = _msgSender(); Staking storage staking = stakers[staker].stakings[stakingId]; require(staking.isInitialized, "TaleStaking: Staking is not exists"); require(!staking.isCompleted, "TaleStaking: Staking is completed"); claimNft(staking, staker); claimTale(staking, stakingId, staker); } function claimTale(Staking storage staking, uint256 stakingId, address staker) private { RewardRule memory rewardRule = rewardRules[staking.targetLevel]; if (block.timestamp >= staking.timestamp + rewardRule.period) { staking.isCompleted = true; staking.rewarded = staking.amount * rewardRule.apr * rewardRule.period / 365 days / 100; delete stakers[staker].activeStakings[stakingId]; totalStaked -= staking.amount; uint256 totalAmount = staking.amount + staking.rewarded; taleToken.safeTransfer(staker, totalAmount); emit TaleReward(staker, staking.amount, staking.rewarded); } } function claimNft(Staking storage staking, address staker) private { uint256 stakingDuration = block.timestamp - staking.timestamp; for (uint256 i = uint256(staking.rewardedLevel) + 1; i <= uint256(staking.targetLevel); ++i) { StakingLevel level = StakingLevel(i); RewardRule memory rule = rewardRules[level]; if (stakingDuration >= rule.period) { staking.rewardedLevel = level; require(rule.nftHero != address(0), "TaleStaking: Hero unset"); minterFactory.mintTo(staker, rule.nftHero); emit NftReward(staker, rule.nftHero); } else { break; } } } /** * @notice Returns the maximum available level for the user and staking * * @param user User address * @param stakingId Id of staking; */ function getAvailableLevel(address user, uint256 stakingId) public view returns (StakingLevel) { Staking storage staking = stakers[user].stakings[stakingId]; StakingLevel availableLevel; uint256 stakingDuration = block.timestamp - staking.timestamp; for (uint256 i = uint256(staking.rewardedLevel) + 1; i < 5; ++i) { StakingLevel level = StakingLevel(i); RewardRule memory rule = rewardRules[level]; if (rule.period >= stakingDuration) { availableLevel = level; } else { break; } } return availableLevel; } /** * @notice Sets MinterFactory, only available to the owner * * @param factory Address of minter factory */ function setMinterFactory(address factory) external onlyOwner { minterFactory = IMinterFactory(factory); } /** * @notice Sets hero address for different levels * * @param stakingLevel User address * @param nftAddress Hero NFT address */ function setNft(StakingLevel stakingLevel, address nftAddress) external onlyOwner { rewardRules[stakingLevel].nftHero = nftAddress; } /** * @notice Withdraws tokens from the pool. * Available only to the owner of the contract. * * @param to Address where tokens will be withdrawn * @param amount Amount of tokens to withdraw. */ function withdraw(address to, uint256 amount) external onlyOwner { require(getPoolSize() >= amount, "TaleStaking: Owner can't withdraw more than pool size"); taleToken.safeTransfer(to, amount); } /** * @notice Returns the current number of tokens in the pool */ function getPoolSize() public view returns(uint256) { uint256 balance = taleToken.balanceOf(address(this)); return balance - totalStaked; } /** * @notice Returns active staking indexes for the specified user * * @param user Address for which indexes will be returned */ function getActiveStakingIndexes(address user) external view returns(uint256[] memory) { uint256 activeStakingsCount = getActiveStakingCount(user); uint256[] memory result = new uint256[](activeStakingsCount); uint256 j = 0; for (uint256 i = 0; i < stakers[user].stakingNumber; ++i) { if (stakers[user].activeStakings[i]) { result[j] = i; ++j; } } return result; } /** * @notice Returns staking for the specified user and index * * @param user Address for which indexes will be returned * @param stakingIndex Index of the staking */ function getStaking(address user, uint256 stakingIndex) external view returns(Staking memory) { Staking memory staking = stakers[user].stakings[stakingIndex]; require(staking.isInitialized, "TaleStaking: Staking is not exists"); return staking; } /** * @notice Returns the number of all stakings for the user * * @param user The user whose number of stakings will be returned */ function getAllStakingCount(address user) public view returns(uint256) { return stakers[user].stakingNumber; } /** * @notice Returns the number of active stakings for the user * * @param user The user whose number of stakings will be returned */ function getActiveStakingCount(address user) public view returns(uint256) { uint256 count = 0; for (uint256 i = 0; i < stakers[user].stakingNumber; ++i) { if (stakers[user].activeStakings[i]) { ++count; } } return count; } }
* @notice Returns active staking indexes for the specified user @param user Address for which indexes will be returned/
function getActiveStakingIndexes(address user) external view returns(uint256[] memory) { uint256 activeStakingsCount = getActiveStakingCount(user); uint256[] memory result = new uint256[](activeStakingsCount); uint256 j = 0; for (uint256 i = 0; i < stakers[user].stakingNumber; ++i) { if (stakers[user].activeStakings[i]) { result[j] = i; ++j; } } return result; }
12,899,603
[ 1, 1356, 2695, 384, 6159, 5596, 364, 326, 1269, 729, 225, 729, 5267, 364, 1492, 5596, 903, 506, 2106, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11960, 510, 6159, 8639, 12, 2867, 729, 13, 3903, 1476, 1135, 12, 11890, 5034, 8526, 3778, 13, 288, 203, 3639, 2254, 5034, 2695, 510, 581, 899, 1380, 273, 11960, 510, 6159, 1380, 12, 1355, 1769, 203, 3639, 2254, 5034, 8526, 3778, 563, 273, 394, 2254, 5034, 8526, 12, 3535, 510, 581, 899, 1380, 1769, 203, 3639, 2254, 5034, 525, 273, 374, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 384, 581, 414, 63, 1355, 8009, 334, 6159, 1854, 31, 965, 77, 13, 288, 203, 5411, 309, 261, 334, 581, 414, 63, 1355, 8009, 3535, 510, 581, 899, 63, 77, 5717, 288, 203, 7734, 563, 63, 78, 65, 273, 277, 31, 203, 7734, 965, 78, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 563, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x0000D22bab9d6AF0104FDd6b05bF3e179b06A282/sources/project_/contracts/NewDawnPaymentForwarder.sol
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. These functions can be used to verify that a message was signed by the holder of the private keys of a given address./
library ECDSA { pragma solidity 0.8.7; enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { revert("ECDSA: invalid signature"); revert("ECDSA: invalid signature length"); revert("ECDSA: invalid signature 's' value"); } } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { revert("ECDSA: invalid signature"); revert("ECDSA: invalid signature length"); revert("ECDSA: invalid signature 's' value"); } } } else if (error == RecoverError.InvalidSignature) { } else if (error == RecoverError.InvalidSignatureLength) { } else if (error == RecoverError.InvalidSignatureS) { function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); return (address(0), RecoverError.InvalidSignatureLength); } } function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); return (address(0), RecoverError.InvalidSignatureLength); } } function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); return (address(0), RecoverError.InvalidSignatureLength); } } } else { function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) { if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) { if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } address signer = ecrecover(hash, v, r, s); function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) { if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } }
1,912,622
[ 1, 4958, 549, 21507, 22901, 11678, 7053, 9249, 15067, 261, 7228, 19748, 13, 5295, 18, 8646, 4186, 848, 506, 1399, 358, 3929, 716, 279, 883, 1703, 6726, 635, 326, 10438, 434, 326, 3238, 1311, 434, 279, 864, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 7773, 19748, 288, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 27, 31, 203, 565, 2792, 868, 3165, 668, 288, 203, 3639, 2631, 668, 16, 203, 3639, 1962, 5374, 16, 203, 3639, 1962, 5374, 1782, 16, 203, 3639, 1962, 5374, 55, 16, 203, 565, 289, 203, 203, 565, 445, 389, 12849, 668, 12, 27622, 668, 555, 13, 3238, 16618, 288, 203, 3639, 309, 261, 1636, 422, 868, 3165, 668, 18, 2279, 668, 13, 288, 203, 5411, 15226, 2932, 7228, 19748, 30, 2057, 3372, 8863, 203, 5411, 15226, 2932, 7228, 19748, 30, 2057, 3372, 769, 8863, 203, 5411, 15226, 2932, 7228, 19748, 30, 2057, 3372, 296, 87, 11, 460, 8863, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 389, 12849, 668, 12, 27622, 668, 555, 13, 3238, 16618, 288, 203, 3639, 309, 261, 1636, 422, 868, 3165, 668, 18, 2279, 668, 13, 288, 203, 5411, 15226, 2932, 7228, 19748, 30, 2057, 3372, 8863, 203, 5411, 15226, 2932, 7228, 19748, 30, 2057, 3372, 769, 8863, 203, 5411, 15226, 2932, 7228, 19748, 30, 2057, 3372, 296, 87, 11, 460, 8863, 203, 3639, 289, 203, 565, 289, 203, 203, 3639, 289, 469, 309, 261, 1636, 422, 868, 3165, 668, 18, 1941, 5374, 13, 288, 203, 3639, 289, 469, 309, 261, 1636, 422, 868, 3165, 668, 18, 1941, 5374, 1782, 13, 288, 203, 3639, 289, 469, 309, 261, 1636, 422, 868, 3165, 668, 18, 1941, 5374, 55, 13, 288, 203, 565, 445, 775, 27622, 12, 3890, 1578, 1651, 16, 1731, 3778, 3372, 13, 2713, 16618, 2 ]
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "../BaseLogic.sol"; import "../vendor/ISwapRouter.sol"; /// @notice Trading assets on Uniswap V3 and 1Inch V4 DEXs contract Swap is BaseLogic { address immutable public uniswapRouter; address immutable public oneInch; /// @notice Params for Uniswap V3 exact input trade on a single pool /// @param subAccountIdIn subaccount id to trade from /// @param subAccountIdOut subaccount id to trade to /// @param underlyingIn sold token address /// @param underlyingOut bought token address /// @param amountIn amount of token to sell /// @param amountOutMinimum minimum amount of bought token /// @param deadline trade must complete before this timestamp /// @param fee uniswap pool fee to use /// @param sqrtPriceLimitX96 maximum acceptable price struct SwapUniExactInputSingleParams { uint subAccountIdIn; uint subAccountIdOut; address underlyingIn; address underlyingOut; uint amountIn; uint amountOutMinimum; uint deadline; uint24 fee; uint160 sqrtPriceLimitX96; } /// @notice Params for Uniswap V3 exact input trade routed through multiple pools /// @param subAccountIdIn subaccount id to trade from /// @param subAccountIdOut subaccount id to trade to /// @param underlyingIn sold token address /// @param underlyingOut bought token address /// @param amountIn amount of token to sell /// @param amountOutMinimum minimum amount of bought token /// @param deadline trade must complete before this timestamp /// @param path list of pools to use for the trade struct SwapUniExactInputParams { uint subAccountIdIn; uint subAccountIdOut; uint amountIn; uint amountOutMinimum; uint deadline; bytes path; // list of pools to hop - constructed with uni SDK } /// @notice Params for Uniswap V3 exact output trade on a single pool /// @param subAccountIdIn subaccount id to trade from /// @param subAccountIdOut subaccount id to trade to /// @param underlyingIn sold token address /// @param underlyingOut bought token address /// @param amountOut amount of token to buy /// @param amountInMaximum maximum amount of sold token /// @param deadline trade must complete before this timestamp /// @param fee uniswap pool fee to use /// @param sqrtPriceLimitX96 maximum acceptable price struct SwapUniExactOutputSingleParams { uint subAccountIdIn; uint subAccountIdOut; address underlyingIn; address underlyingOut; uint amountOut; uint amountInMaximum; uint deadline; uint24 fee; uint160 sqrtPriceLimitX96; } /// @notice Params for Uniswap V3 exact output trade routed through multiple pools /// @param subAccountIdIn subaccount id to trade from /// @param subAccountIdOut subaccount id to trade to /// @param underlyingIn sold token address /// @param underlyingOut bought token address /// @param amountOut amount of token to buy /// @param amountInMaximum maximum amount of sold token /// @param deadline trade must complete before this timestamp /// @param path list of pools to use for the trade struct SwapUniExactOutputParams { uint subAccountIdIn; uint subAccountIdOut; uint amountOut; uint amountInMaximum; uint deadline; bytes path; } /// @notice Params for 1Inch trade /// @param subAccountIdIn subaccount id to trade from /// @param subAccountIdOut subaccount id to trade to /// @param underlyingIn sold token address /// @param underlyingOut bought token address /// @param amount amount of token to sell /// @param amountOutMinimum minimum amount of bought token /// @param payload call data passed to 1Inch contract struct Swap1InchParams { uint subAccountIdIn; uint subAccountIdOut; address underlyingIn; address underlyingOut; uint amount; uint amountOutMinimum; bytes payload; } struct SwapCache { address accountIn; address accountOut; address eTokenIn; address eTokenOut; AssetCache assetCacheIn; AssetCache assetCacheOut; uint balanceIn; uint balanceOut; uint amountIn; uint amountOut; uint amountInternalIn; } constructor(bytes32 moduleGitCommit_, address uniswapRouter_, address oneInch_) BaseLogic(MODULEID__SWAP, moduleGitCommit_) { uniswapRouter = uniswapRouter_; oneInch = oneInch_; } /// @notice Execute Uniswap V3 exact input trade on a single pool /// @param params struct defining trade parameters function swapUniExactInputSingle(SwapUniExactInputSingleParams memory params) external nonReentrant { SwapCache memory swap = initSwap( params.underlyingIn, params.underlyingOut, params.amountIn, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__UNI_EXACT_INPUT_SINGLE ); setWithdrawAmounts(swap, params.amountIn); Utils.safeApprove(params.underlyingIn, uniswapRouter, swap.amountIn); swap.amountOut = ISwapRouter(uniswapRouter).exactInputSingle( ISwapRouter.ExactInputSingleParams({ tokenIn: params.underlyingIn, tokenOut: params.underlyingOut, fee: params.fee, recipient: address(this), deadline: params.deadline > 0 ? params.deadline : block.timestamp, amountIn: swap.amountIn, amountOutMinimum: params.amountOutMinimum, sqrtPriceLimitX96: params.sqrtPriceLimitX96 }) ); finalizeSwap(swap); } /// @notice Execute Uniswap V3 exact input trade routed through multiple pools /// @param params struct defining trade parameters function swapUniExactInput(SwapUniExactInputParams memory params) external nonReentrant { (address underlyingIn, address underlyingOut) = decodeUniPath(params.path, false); SwapCache memory swap = initSwap( underlyingIn, underlyingOut, params.amountIn, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__UNI_EXACT_INPUT ); setWithdrawAmounts(swap, params.amountIn); Utils.safeApprove(underlyingIn, uniswapRouter, swap.amountIn); swap.amountOut = ISwapRouter(uniswapRouter).exactInput( ISwapRouter.ExactInputParams({ path: params.path, recipient: address(this), deadline: params.deadline > 0 ? params.deadline : block.timestamp, amountIn: swap.amountIn, amountOutMinimum: params.amountOutMinimum }) ); finalizeSwap(swap); } /// @notice Execute Uniswap V3 exact output trade on a single pool /// @param params struct defining trade parameters function swapUniExactOutputSingle(SwapUniExactOutputSingleParams memory params) external nonReentrant { SwapCache memory swap = initSwap( params.underlyingIn, params.underlyingOut, params.amountOut, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__UNI_EXACT_OUTPUT_SINGLE ); swap.amountOut = params.amountOut; doSwapUniExactOutputSingle(swap, params); finalizeSwap(swap); } /// @notice Execute Uniswap V3 exact output trade routed through multiple pools /// @param params struct defining trade parameters function swapUniExactOutput(SwapUniExactOutputParams memory params) external nonReentrant { (address underlyingIn, address underlyingOut) = decodeUniPath(params.path, true); SwapCache memory swap = initSwap( underlyingIn, underlyingOut, params.amountOut, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__UNI_EXACT_OUTPUT ); swap.amountOut = params.amountOut; doSwapUniExactOutput(swap, params, underlyingIn); finalizeSwap(swap); } /// @notice Trade on Uniswap V3 single pool and repay debt with bought asset /// @param params struct defining trade parameters (amountOut is ignored) /// @param targetDebt amount of debt that is expected to remain after trade and repay (0 to repay full debt) function swapAndRepayUniSingle(SwapUniExactOutputSingleParams memory params, uint targetDebt) external nonReentrant { SwapCache memory swap = initSwap( params.underlyingIn, params.underlyingOut, targetDebt, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__UNI_EXACT_OUTPUT_SINGLE_REPAY ); swap.amountOut = getRepayAmount(swap, targetDebt); doSwapUniExactOutputSingle(swap, params); finalizeSwapAndRepay(swap); } /// @notice Trade on Uniswap V3 through multiple pools pool and repay debt with bought asset /// @param params struct defining trade parameters (amountOut is ignored) /// @param targetDebt amount of debt that is expected to remain after trade and repay (0 to repay full debt) function swapAndRepayUni(SwapUniExactOutputParams memory params, uint targetDebt) external nonReentrant { (address underlyingIn, address underlyingOut) = decodeUniPath(params.path, true); SwapCache memory swap = initSwap( underlyingIn, underlyingOut, targetDebt, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__UNI_EXACT_OUTPUT_REPAY ); swap.amountOut = getRepayAmount(swap, targetDebt); doSwapUniExactOutput(swap, params, underlyingIn); finalizeSwapAndRepay(swap); } /// @notice Execute 1Inch V4 trade /// @param params struct defining trade parameters function swap1Inch(Swap1InchParams memory params) external nonReentrant { SwapCache memory swap = initSwap( params.underlyingIn, params.underlyingOut, params.amount, params.subAccountIdIn, params.subAccountIdOut, SWAP_TYPE__1INCH ); setWithdrawAmounts(swap, params.amount); Utils.safeApprove(params.underlyingIn, oneInch, swap.amountIn); (bool success, bytes memory result) = oneInch.call(params.payload); if (!success) revertBytes(result); swap.amountOut = abi.decode(result, (uint)); require(swap.amountOut >= params.amountOutMinimum, "e/swap/min-amount-out"); finalizeSwap(swap); } function initSwap( address underlyingIn, address underlyingOut, uint amount, uint subAccountIdIn, uint subAccountIdOut, uint swapType ) private returns (SwapCache memory swap) { require(underlyingIn != underlyingOut, "e/swap/same"); address msgSender = unpackTrailingParamMsgSender(); swap.accountIn = getSubAccount(msgSender, subAccountIdIn); swap.accountOut = getSubAccount(msgSender, subAccountIdOut); updateAverageLiquidity(swap.accountIn); if (swap.accountIn != swap.accountOut) updateAverageLiquidity(swap.accountOut); emit RequestSwap( swap.accountIn, swap.accountOut, underlyingIn, underlyingOut, amount, swapType ); swap.eTokenIn = underlyingLookup[underlyingIn].eTokenAddress; swap.eTokenOut = underlyingLookup[underlyingOut].eTokenAddress; AssetStorage storage assetStorageIn = eTokenLookup[swap.eTokenIn]; AssetStorage storage assetStorageOut = eTokenLookup[swap.eTokenOut]; require(swap.eTokenIn != address(0), "e/swap/in-market-not-activated"); require(swap.eTokenOut != address(0), "e/swap/out-market-not-activated"); swap.assetCacheIn = loadAssetCache(underlyingIn, assetStorageIn); swap.assetCacheOut = loadAssetCache(underlyingOut, assetStorageOut); swap.balanceIn = callBalanceOf(swap.assetCacheIn, address(this)) ; swap.balanceOut = callBalanceOf(swap.assetCacheOut, address(this)); } function doSwapUniExactOutputSingle(SwapCache memory swap, SwapUniExactOutputSingleParams memory params) private { Utils.safeApprove(params.underlyingIn, uniswapRouter, params.amountInMaximum); uint pulledAmountIn = ISwapRouter(uniswapRouter).exactOutputSingle( ISwapRouter.ExactOutputSingleParams({ tokenIn: params.underlyingIn, tokenOut: params.underlyingOut, fee: params.fee, recipient: address(this), deadline: params.deadline > 0 ? params.deadline : block.timestamp, amountOut: swap.amountOut, amountInMaximum: params.amountInMaximum, sqrtPriceLimitX96: params.sqrtPriceLimitX96 }) ); require(pulledAmountIn != type(uint).max, "e/swap/exact-out-amount-in"); setWithdrawAmounts(swap, pulledAmountIn); if (swap.amountIn < params.amountInMaximum) { Utils.safeApprove(params.underlyingIn, uniswapRouter, 0); } } function doSwapUniExactOutput(SwapCache memory swap, SwapUniExactOutputParams memory params, address underlyingIn) private { Utils.safeApprove(underlyingIn, uniswapRouter, params.amountInMaximum); uint pulledAmountIn = ISwapRouter(uniswapRouter).exactOutput( ISwapRouter.ExactOutputParams({ path: params.path, recipient: address(this), deadline: params.deadline > 0 ? params.deadline : block.timestamp, amountOut: swap.amountOut, amountInMaximum: params.amountInMaximum }) ); require(pulledAmountIn != type(uint).max, "e/swap/exact-out-amount-in"); setWithdrawAmounts(swap, pulledAmountIn); if (swap.amountIn < params.amountInMaximum) { Utils.safeApprove(underlyingIn, uniswapRouter, 0); } } function setWithdrawAmounts(SwapCache memory swap, uint amount) private view { (amount, swap.amountInternalIn) = withdrawAmounts(eTokenLookup[swap.eTokenIn], swap.assetCacheIn, swap.accountIn, amount); require(swap.assetCacheIn.poolSize >= amount, "e/swap/insufficient-pool-size"); swap.amountIn = amount / swap.assetCacheIn.underlyingDecimalsScaler; } function finalizeSwap(SwapCache memory swap) private { uint balanceIn = checkBalances(swap); processWithdraw(eTokenLookup[swap.eTokenIn], swap.assetCacheIn, swap.eTokenIn, swap.accountIn, swap.amountInternalIn, balanceIn); processDeposit(eTokenLookup[swap.eTokenOut], swap.assetCacheOut, swap.eTokenOut, swap.accountOut, swap.amountOut); // only checking outgoing account, deposit can't lower health score checkLiquidity(swap.accountIn); } function finalizeSwapAndRepay(SwapCache memory swap) private { uint balanceIn = checkBalances(swap); processWithdraw(eTokenLookup[swap.eTokenIn], swap.assetCacheIn, swap.eTokenIn, swap.accountIn, swap.amountInternalIn, balanceIn); processRepay(eTokenLookup[swap.eTokenOut], swap.assetCacheOut, swap.accountOut, swap.amountOut); // only checking outgoing account, repay can't lower health score checkLiquidity(swap.accountIn); } function processWithdraw(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address account, uint amountInternal, uint balanceIn) private { assetCache.poolSize = decodeExternalAmount(assetCache, balanceIn); decreaseBalance(assetStorage, assetCache, eTokenAddress, account, amountInternal); logAssetStatus(assetCache); } function processDeposit(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address account, uint amount) private { uint amountDecoded = decodeExternalAmount(assetCache, amount); uint amountInternal = underlyingAmountToBalance(assetCache, amountDecoded); assetCache.poolSize += amountDecoded; increaseBalance(assetStorage, assetCache, eTokenAddress, account, amountInternal); logAssetStatus(assetCache); } function processRepay(AssetStorage storage assetStorage, AssetCache memory assetCache, address account, uint amount) private { decreaseBorrow(assetStorage, assetCache, assetStorage.dTokenAddress, account, decodeExternalAmount(assetCache, amount)); logAssetStatus(assetCache); } function checkBalances(SwapCache memory swap) private view returns (uint) { uint balanceIn = callBalanceOf(swap.assetCacheIn, address(this)); require(balanceIn == swap.balanceIn - swap.amountIn, "e/swap/balance-in"); require(callBalanceOf(swap.assetCacheOut, address(this)) == swap.balanceOut + swap.amountOut, "e/swap/balance-out"); return balanceIn; } function decodeUniPath(bytes memory path, bool isExactOutput) private pure returns (address, address) { require(path.length >= 20 + 3 + 20, "e/swap/uni-path-length"); require((path.length - 20) % 23 == 0, "e/swap/uni-path-format"); address token0 = toAddress(path, 0); address token1 = toAddress(path, path.length - 20); return isExactOutput ? (token1, token0) : (token0, token1); } function getRepayAmount(SwapCache memory swap, uint targetDebt) private view returns (uint) { uint owed = getCurrentOwed(eTokenLookup[swap.eTokenOut], swap.assetCacheOut, swap.accountOut) / swap.assetCacheOut.underlyingDecimalsScaler; require (owed > targetDebt, "e/swap/target-debt"); return owed - targetDebt; } function toAddress(bytes memory data, uint start) private pure returns (address result) { // assuming data length is already validated assembly { // borrowed from BytesLib https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol result := div(mload(add(add(data, 0x20), start)), 0x1000000000000000000000000) } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./BaseModule.sol"; import "./BaseIRM.sol"; import "./Interfaces.sol"; import "./Utils.sol"; import "./vendor/RPow.sol"; import "./IRiskManager.sol"; abstract contract BaseLogic is BaseModule { constructor(uint moduleId_, bytes32 moduleGitCommit_) BaseModule(moduleId_, moduleGitCommit_) {} // Account auth function getSubAccount(address primary, uint subAccountId) internal pure returns (address) { require(subAccountId < 256, "e/sub-account-id-too-big"); return address(uint160(primary) ^ uint160(subAccountId)); } function isSubAccountOf(address primary, address subAccount) internal pure returns (bool) { return (uint160(primary) | 0xFF) == (uint160(subAccount) | 0xFF); } // Entered markets array function getEnteredMarketsArray(address account) internal view returns (address[] memory) { uint32 numMarketsEntered = accountLookup[account].numMarketsEntered; address firstMarketEntered = accountLookup[account].firstMarketEntered; address[] memory output = new address[](numMarketsEntered); if (numMarketsEntered == 0) return output; address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account]; output[0] = firstMarketEntered; for (uint i = 1; i < numMarketsEntered; ++i) { output[i] = markets[i]; } return output; } function isEnteredInMarket(address account, address underlying) internal view returns (bool) { uint32 numMarketsEntered = accountLookup[account].numMarketsEntered; address firstMarketEntered = accountLookup[account].firstMarketEntered; if (numMarketsEntered == 0) return false; if (firstMarketEntered == underlying) return true; address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account]; for (uint i = 1; i < numMarketsEntered; ++i) { if (markets[i] == underlying) return true; } return false; } function doEnterMarket(address account, address underlying) internal { AccountStorage storage accountStorage = accountLookup[account]; uint32 numMarketsEntered = accountStorage.numMarketsEntered; address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account]; if (numMarketsEntered != 0) { if (accountStorage.firstMarketEntered == underlying) return; // already entered for (uint i = 1; i < numMarketsEntered; i++) { if (markets[i] == underlying) return; // already entered } } require(numMarketsEntered < MAX_ENTERED_MARKETS, "e/too-many-entered-markets"); if (numMarketsEntered == 0) accountStorage.firstMarketEntered = underlying; else markets[numMarketsEntered] = underlying; accountStorage.numMarketsEntered = numMarketsEntered + 1; emit EnterMarket(underlying, account); } // Liquidity check must be done by caller after calling this function doExitMarket(address account, address underlying) internal { AccountStorage storage accountStorage = accountLookup[account]; uint32 numMarketsEntered = accountStorage.numMarketsEntered; address[MAX_POSSIBLE_ENTERED_MARKETS] storage markets = marketsEntered[account]; uint searchIndex = type(uint).max; if (numMarketsEntered == 0) return; // already exited if (accountStorage.firstMarketEntered == underlying) { searchIndex = 0; } else { for (uint i = 1; i < numMarketsEntered; i++) { if (markets[i] == underlying) { searchIndex = i; break; } } if (searchIndex == type(uint).max) return; // already exited } uint lastMarketIndex = numMarketsEntered - 1; if (searchIndex != lastMarketIndex) { if (searchIndex == 0) accountStorage.firstMarketEntered = markets[lastMarketIndex]; else markets[searchIndex] = markets[lastMarketIndex]; } accountStorage.numMarketsEntered = uint32(lastMarketIndex); if (lastMarketIndex != 0) markets[lastMarketIndex] = address(0); // zero out for storage refund emit ExitMarket(underlying, account); } // AssetConfig function resolveAssetConfig(address underlying) internal view returns (AssetConfig memory) { AssetConfig memory config = underlyingLookup[underlying]; require(config.eTokenAddress != address(0), "e/market-not-activated"); if (config.borrowFactor == type(uint32).max) config.borrowFactor = DEFAULT_BORROW_FACTOR; if (config.twapWindow == type(uint24).max) config.twapWindow = DEFAULT_TWAP_WINDOW_SECONDS; return config; } // AssetCache struct AssetCache { address underlying; uint112 totalBalances; uint144 totalBorrows; uint96 reserveBalance; uint interestAccumulator; uint40 lastInterestAccumulatorUpdate; uint8 underlyingDecimals; uint32 interestRateModel; int96 interestRate; uint32 reserveFee; uint16 pricingType; uint32 pricingParameters; uint poolSize; // result of calling balanceOf on underlying (in external units) uint underlyingDecimalsScaler; uint maxExternalAmount; } function initAssetCache(address underlying, AssetStorage storage assetStorage, AssetCache memory assetCache) internal view returns (bool dirty) { dirty = false; assetCache.underlying = underlying; // Storage loads assetCache.lastInterestAccumulatorUpdate = assetStorage.lastInterestAccumulatorUpdate; uint8 underlyingDecimals = assetCache.underlyingDecimals = assetStorage.underlyingDecimals; assetCache.interestRateModel = assetStorage.interestRateModel; assetCache.interestRate = assetStorage.interestRate; assetCache.reserveFee = assetStorage.reserveFee; assetCache.pricingType = assetStorage.pricingType; assetCache.pricingParameters = assetStorage.pricingParameters; assetCache.reserveBalance = assetStorage.reserveBalance; assetCache.totalBalances = assetStorage.totalBalances; assetCache.totalBorrows = assetStorage.totalBorrows; assetCache.interestAccumulator = assetStorage.interestAccumulator; // Derived state unchecked { assetCache.underlyingDecimalsScaler = 10**(18 - underlyingDecimals); assetCache.maxExternalAmount = MAX_SANE_AMOUNT / assetCache.underlyingDecimalsScaler; } uint poolSize = callBalanceOf(assetCache, address(this)); if (poolSize <= assetCache.maxExternalAmount) { unchecked { assetCache.poolSize = poolSize * assetCache.underlyingDecimalsScaler; } } else { assetCache.poolSize = 0; } // Update interest accumulator and reserves if (block.timestamp != assetCache.lastInterestAccumulatorUpdate) { dirty = true; uint deltaT = block.timestamp - assetCache.lastInterestAccumulatorUpdate; // Compute new values uint newInterestAccumulator = (RPow.rpow(uint(int(assetCache.interestRate) + 1e27), deltaT, 1e27) * assetCache.interestAccumulator) / 1e27; uint newTotalBorrows = assetCache.totalBorrows * newInterestAccumulator / assetCache.interestAccumulator; uint newReserveBalance = assetCache.reserveBalance; uint newTotalBalances = assetCache.totalBalances; uint feeAmount = (newTotalBorrows - assetCache.totalBorrows) * (assetCache.reserveFee == type(uint32).max ? DEFAULT_RESERVE_FEE : assetCache.reserveFee) / (RESERVE_FEE_SCALE * INTERNAL_DEBT_PRECISION); if (feeAmount != 0) { uint poolAssets = assetCache.poolSize + (newTotalBorrows / INTERNAL_DEBT_PRECISION); newTotalBalances = poolAssets * newTotalBalances / (poolAssets - feeAmount); newReserveBalance += newTotalBalances - assetCache.totalBalances; } // Store new values in assetCache, only if no overflows will occur if (newTotalBalances <= MAX_SANE_AMOUNT && newTotalBorrows <= MAX_SANE_DEBT_AMOUNT) { assetCache.totalBorrows = encodeDebtAmount(newTotalBorrows); assetCache.interestAccumulator = newInterestAccumulator; assetCache.lastInterestAccumulatorUpdate = uint40(block.timestamp); if (newTotalBalances != assetCache.totalBalances) { assetCache.reserveBalance = encodeSmallAmount(newReserveBalance); assetCache.totalBalances = encodeAmount(newTotalBalances); } } } } function loadAssetCache(address underlying, AssetStorage storage assetStorage) internal returns (AssetCache memory assetCache) { if (initAssetCache(underlying, assetStorage, assetCache)) { assetStorage.lastInterestAccumulatorUpdate = assetCache.lastInterestAccumulatorUpdate; assetStorage.underlying = assetCache.underlying; // avoid an SLOAD of this slot assetStorage.reserveBalance = assetCache.reserveBalance; assetStorage.totalBalances = assetCache.totalBalances; assetStorage.totalBorrows = assetCache.totalBorrows; assetStorage.interestAccumulator = assetCache.interestAccumulator; } } function loadAssetCacheRO(address underlying, AssetStorage storage assetStorage) internal view returns (AssetCache memory assetCache) { initAssetCache(underlying, assetStorage, assetCache); } // Utils function decodeExternalAmount(AssetCache memory assetCache, uint externalAmount) internal pure returns (uint scaledAmount) { require(externalAmount <= assetCache.maxExternalAmount, "e/amount-too-large"); unchecked { scaledAmount = externalAmount * assetCache.underlyingDecimalsScaler; } } function encodeAmount(uint amount) internal pure returns (uint112) { require(amount <= MAX_SANE_AMOUNT, "e/amount-too-large-to-encode"); return uint112(amount); } function encodeSmallAmount(uint amount) internal pure returns (uint96) { require(amount <= MAX_SANE_SMALL_AMOUNT, "e/small-amount-too-large-to-encode"); return uint96(amount); } function encodeDebtAmount(uint amount) internal pure returns (uint144) { require(amount <= MAX_SANE_DEBT_AMOUNT, "e/debt-amount-too-large-to-encode"); return uint144(amount); } function computeExchangeRate(AssetCache memory assetCache) private pure returns (uint) { if (assetCache.totalBalances == 0) return 1e18; return (assetCache.poolSize + (assetCache.totalBorrows / INTERNAL_DEBT_PRECISION)) * 1e18 / assetCache.totalBalances; } function underlyingAmountToBalance(AssetCache memory assetCache, uint amount) internal pure returns (uint) { uint exchangeRate = computeExchangeRate(assetCache); return amount * 1e18 / exchangeRate; } function underlyingAmountToBalanceRoundUp(AssetCache memory assetCache, uint amount) internal pure returns (uint) { uint exchangeRate = computeExchangeRate(assetCache); return (amount * 1e18 + (exchangeRate - 1)) / exchangeRate; } function balanceToUnderlyingAmount(AssetCache memory assetCache, uint amount) internal pure returns (uint) { uint exchangeRate = computeExchangeRate(assetCache); return amount * exchangeRate / 1e18; } function callBalanceOf(AssetCache memory assetCache, address account) internal view FREEMEM returns (uint) { // We set a gas limit so that a malicious token can't eat up all gas and cause a liquidity check to fail. (bool success, bytes memory data) = assetCache.underlying.staticcall{gas: 20000}(abi.encodeWithSelector(IERC20.balanceOf.selector, account)); // If token's balanceOf() call fails for any reason, return 0. This prevents malicious tokens from causing liquidity checks to fail. // If the contract doesn't exist (maybe because selfdestructed), then data.length will be 0 and we will return 0. // Data length > 32 is allowed because some legitimate tokens append extra data that can be safely ignored. if (!success || data.length < 32) return 0; return abi.decode(data, (uint256)); } function updateInterestRate(AssetStorage storage assetStorage, AssetCache memory assetCache) internal { uint32 utilisation; { uint totalBorrows = assetCache.totalBorrows / INTERNAL_DEBT_PRECISION; uint poolAssets = assetCache.poolSize + totalBorrows; if (poolAssets == 0) utilisation = 0; // empty pool arbitrarily given utilisation of 0 else utilisation = uint32(totalBorrows * (uint(type(uint32).max) * 1e18) / poolAssets / 1e18); } bytes memory result = callInternalModule(assetCache.interestRateModel, abi.encodeWithSelector(BaseIRM.computeInterestRate.selector, assetCache.underlying, utilisation)); (int96 newInterestRate) = abi.decode(result, (int96)); assetStorage.interestRate = assetCache.interestRate = newInterestRate; } function logAssetStatus(AssetCache memory a) internal { emit AssetStatus(a.underlying, a.totalBalances, a.totalBorrows / INTERNAL_DEBT_PRECISION, a.reserveBalance, a.poolSize, a.interestAccumulator, a.interestRate, block.timestamp); } // Balances function increaseBalance(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address account, uint amount) internal { assetStorage.users[account].balance = encodeAmount(assetStorage.users[account].balance + amount); assetStorage.totalBalances = assetCache.totalBalances = encodeAmount(uint(assetCache.totalBalances) + amount); updateInterestRate(assetStorage, assetCache); emit Deposit(assetCache.underlying, account, amount); emitViaProxy_Transfer(eTokenAddress, address(0), account, amount); } function decreaseBalance(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address account, uint amount) internal { uint origBalance = assetStorage.users[account].balance; require(origBalance >= amount, "e/insufficient-balance"); assetStorage.users[account].balance = encodeAmount(origBalance - amount); assetStorage.totalBalances = assetCache.totalBalances = encodeAmount(assetCache.totalBalances - amount); updateInterestRate(assetStorage, assetCache); emit Withdraw(assetCache.underlying, account, amount); emitViaProxy_Transfer(eTokenAddress, account, address(0), amount); } function transferBalance(AssetStorage storage assetStorage, AssetCache memory assetCache, address eTokenAddress, address from, address to, uint amount) internal { uint origFromBalance = assetStorage.users[from].balance; require(origFromBalance >= amount, "e/insufficient-balance"); uint newFromBalance; unchecked { newFromBalance = origFromBalance - amount; } assetStorage.users[from].balance = encodeAmount(newFromBalance); assetStorage.users[to].balance = encodeAmount(assetStorage.users[to].balance + amount); emit Withdraw(assetCache.underlying, from, amount); emit Deposit(assetCache.underlying, to, amount); emitViaProxy_Transfer(eTokenAddress, from, to, amount); } function withdrawAmounts(AssetStorage storage assetStorage, AssetCache memory assetCache, address account, uint amount) internal view returns (uint, uint) { uint amountInternal; if (amount == type(uint).max) { amountInternal = assetStorage.users[account].balance; amount = balanceToUnderlyingAmount(assetCache, amountInternal); } else { amount = decodeExternalAmount(assetCache, amount); amountInternal = underlyingAmountToBalanceRoundUp(assetCache, amount); } return (amount, amountInternal); } // Borrows // Returns internal precision function getCurrentOwedExact(AssetStorage storage assetStorage, AssetCache memory assetCache, address account, uint owed) internal view returns (uint) { // Don't bother loading the user's accumulator if (owed == 0) return 0; // Can't divide by 0 here: If owed is non-zero, we must've initialised the user's interestAccumulator return owed * assetCache.interestAccumulator / assetStorage.users[account].interestAccumulator; } // When non-zero, we round *up* to the smallest external unit so that outstanding dust in a loan can be repaid. // unchecked is OK here since owed is always loaded from storage, so we know it fits into a uint144 (pre-interest accural) // Takes and returns 27 decimals precision. function roundUpOwed(AssetCache memory assetCache, uint owed) private pure returns (uint) { if (owed == 0) return 0; unchecked { uint scale = INTERNAL_DEBT_PRECISION * assetCache.underlyingDecimalsScaler; return (owed + scale - 1) / scale * scale; } } // Returns 18-decimals precision (debt amount is rounded up) function getCurrentOwed(AssetStorage storage assetStorage, AssetCache memory assetCache, address account) internal view returns (uint) { return roundUpOwed(assetCache, getCurrentOwedExact(assetStorage, assetCache, account, assetStorage.users[account].owed)) / INTERNAL_DEBT_PRECISION; } function updateUserBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address account) private returns (uint newOwedExact, uint prevOwedExact) { prevOwedExact = assetStorage.users[account].owed; newOwedExact = getCurrentOwedExact(assetStorage, assetCache, account, prevOwedExact); assetStorage.users[account].owed = encodeDebtAmount(newOwedExact); assetStorage.users[account].interestAccumulator = assetCache.interestAccumulator; } function logBorrowChange(AssetCache memory assetCache, address dTokenAddress, address account, uint prevOwed, uint owed) private { prevOwed = roundUpOwed(assetCache, prevOwed) / INTERNAL_DEBT_PRECISION; owed = roundUpOwed(assetCache, owed) / INTERNAL_DEBT_PRECISION; if (owed > prevOwed) { uint change = owed - prevOwed; emit Borrow(assetCache.underlying, account, change); emitViaProxy_Transfer(dTokenAddress, address(0), account, change); } else if (prevOwed > owed) { uint change = prevOwed - owed; emit Repay(assetCache.underlying, account, change); emitViaProxy_Transfer(dTokenAddress, account, address(0), change); } } function increaseBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address dTokenAddress, address account, uint amount) internal { amount *= INTERNAL_DEBT_PRECISION; require(assetCache.pricingType != PRICINGTYPE__FORWARDED || pTokenLookup[assetCache.underlying] == address(0), "e/borrow-not-supported"); (uint owed, uint prevOwed) = updateUserBorrow(assetStorage, assetCache, account); if (owed == 0) doEnterMarket(account, assetCache.underlying); owed += amount; assetStorage.users[account].owed = encodeDebtAmount(owed); assetStorage.totalBorrows = assetCache.totalBorrows = encodeDebtAmount(assetCache.totalBorrows + amount); updateInterestRate(assetStorage, assetCache); logBorrowChange(assetCache, dTokenAddress, account, prevOwed, owed); } function decreaseBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address dTokenAddress, address account, uint origAmount) internal { uint amount = origAmount * INTERNAL_DEBT_PRECISION; (uint owed, uint prevOwed) = updateUserBorrow(assetStorage, assetCache, account); uint owedRoundedUp = roundUpOwed(assetCache, owed); require(amount <= owedRoundedUp, "e/repay-too-much"); uint owedRemaining; unchecked { owedRemaining = owedRoundedUp - amount; } if (owed > assetCache.totalBorrows) owed = assetCache.totalBorrows; assetStorage.users[account].owed = encodeDebtAmount(owedRemaining); assetStorage.totalBorrows = assetCache.totalBorrows = encodeDebtAmount(assetCache.totalBorrows - owed + owedRemaining); updateInterestRate(assetStorage, assetCache); logBorrowChange(assetCache, dTokenAddress, account, prevOwed, owedRemaining); } function transferBorrow(AssetStorage storage assetStorage, AssetCache memory assetCache, address dTokenAddress, address from, address to, uint origAmount) internal { uint amount = origAmount * INTERNAL_DEBT_PRECISION; (uint fromOwed, uint fromOwedPrev) = updateUserBorrow(assetStorage, assetCache, from); (uint toOwed, uint toOwedPrev) = updateUserBorrow(assetStorage, assetCache, to); if (toOwed == 0) doEnterMarket(to, assetCache.underlying); // If amount was rounded up, transfer exact amount owed if (amount > fromOwed && amount - fromOwed < INTERNAL_DEBT_PRECISION * assetCache.underlyingDecimalsScaler) amount = fromOwed; require(fromOwed >= amount, "e/insufficient-balance"); unchecked { fromOwed -= amount; } // Transfer any residual dust if (fromOwed < INTERNAL_DEBT_PRECISION) { amount += fromOwed; fromOwed = 0; } toOwed += amount; assetStorage.users[from].owed = encodeDebtAmount(fromOwed); assetStorage.users[to].owed = encodeDebtAmount(toOwed); logBorrowChange(assetCache, dTokenAddress, from, fromOwedPrev, fromOwed); logBorrowChange(assetCache, dTokenAddress, to, toOwedPrev, toOwed); } // Reserves function increaseReserves(AssetStorage storage assetStorage, AssetCache memory assetCache, uint amount) internal { assetStorage.reserveBalance = assetCache.reserveBalance = encodeSmallAmount(assetCache.reserveBalance + amount); assetStorage.totalBalances = assetCache.totalBalances = encodeAmount(assetCache.totalBalances + amount); } // Token asset transfers // amounts are in underlying units function pullTokens(AssetCache memory assetCache, address from, uint amount) internal returns (uint amountTransferred) { uint poolSizeBefore = assetCache.poolSize; Utils.safeTransferFrom(assetCache.underlying, from, address(this), amount / assetCache.underlyingDecimalsScaler); uint poolSizeAfter = assetCache.poolSize = decodeExternalAmount(assetCache, callBalanceOf(assetCache, address(this))); require(poolSizeAfter >= poolSizeBefore, "e/negative-transfer-amount"); unchecked { amountTransferred = poolSizeAfter - poolSizeBefore; } } function pushTokens(AssetCache memory assetCache, address to, uint amount) internal returns (uint amountTransferred) { uint poolSizeBefore = assetCache.poolSize; Utils.safeTransfer(assetCache.underlying, to, amount / assetCache.underlyingDecimalsScaler); uint poolSizeAfter = assetCache.poolSize = decodeExternalAmount(assetCache, callBalanceOf(assetCache, address(this))); require(poolSizeBefore >= poolSizeAfter, "e/negative-transfer-amount"); unchecked { amountTransferred = poolSizeBefore - poolSizeAfter; } } // Liquidity function getAssetPrice(address asset) internal returns (uint) { bytes memory result = callInternalModule(MODULEID__RISK_MANAGER, abi.encodeWithSelector(IRiskManager.getPrice.selector, asset)); return abi.decode(result, (uint)); } function getAccountLiquidity(address account) internal returns (uint collateralValue, uint liabilityValue) { bytes memory result = callInternalModule(MODULEID__RISK_MANAGER, abi.encodeWithSelector(IRiskManager.computeLiquidity.selector, account)); (IRiskManager.LiquidityStatus memory status) = abi.decode(result, (IRiskManager.LiquidityStatus)); collateralValue = status.collateralValue; liabilityValue = status.liabilityValue; } function checkLiquidity(address account) internal { uint8 status = accountLookup[account].deferLiquidityStatus; if (status == DEFERLIQUIDITY__NONE) { callInternalModule(MODULEID__RISK_MANAGER, abi.encodeWithSelector(IRiskManager.requireLiquidity.selector, account)); } else if (status == DEFERLIQUIDITY__CLEAN) { accountLookup[account].deferLiquidityStatus = DEFERLIQUIDITY__DIRTY; } } // Optional average liquidity tracking function computeNewAverageLiquidity(address account, uint deltaT) private returns (uint) { uint currDuration = deltaT >= AVERAGE_LIQUIDITY_PERIOD ? AVERAGE_LIQUIDITY_PERIOD : deltaT; uint prevDuration = AVERAGE_LIQUIDITY_PERIOD - currDuration; uint currAverageLiquidity; { (uint collateralValue, uint liabilityValue) = getAccountLiquidity(account); currAverageLiquidity = collateralValue > liabilityValue ? collateralValue - liabilityValue : 0; } return (accountLookup[account].averageLiquidity * prevDuration / AVERAGE_LIQUIDITY_PERIOD) + (currAverageLiquidity * currDuration / AVERAGE_LIQUIDITY_PERIOD); } function getUpdatedAverageLiquidity(address account) internal returns (uint) { uint lastAverageLiquidityUpdate = accountLookup[account].lastAverageLiquidityUpdate; if (lastAverageLiquidityUpdate == 0) return 0; uint deltaT = block.timestamp - lastAverageLiquidityUpdate; if (deltaT == 0) return accountLookup[account].averageLiquidity; return computeNewAverageLiquidity(account, deltaT); } function getUpdatedAverageLiquidityWithDelegate(address account) internal returns (uint) { address delegate = accountLookup[account].averageLiquidityDelegate; return delegate != address(0) && accountLookup[delegate].averageLiquidityDelegate == account ? getUpdatedAverageLiquidity(delegate) : getUpdatedAverageLiquidity(account); } function updateAverageLiquidity(address account) internal { uint lastAverageLiquidityUpdate = accountLookup[account].lastAverageLiquidityUpdate; if (lastAverageLiquidityUpdate == 0) return; uint deltaT = block.timestamp - lastAverageLiquidityUpdate; if (deltaT == 0) return; accountLookup[account].lastAverageLiquidityUpdate = uint40(block.timestamp); accountLookup[account].averageLiquidity = computeNewAverageLiquidity(account, deltaT); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.7.5; pragma abicoder v2; import './IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Base.sol"; abstract contract BaseModule is Base { // Construction // public accessors common to all modules uint immutable public moduleId; bytes32 immutable public moduleGitCommit; constructor(uint moduleId_, bytes32 moduleGitCommit_) { moduleId = moduleId_; moduleGitCommit = moduleGitCommit_; } // Accessing parameters function unpackTrailingParamMsgSender() internal pure returns (address msgSender) { assembly { msgSender := shr(96, calldataload(sub(calldatasize(), 40))) } } function unpackTrailingParams() internal pure returns (address msgSender, address proxyAddr) { assembly { msgSender := shr(96, calldataload(sub(calldatasize(), 40))) proxyAddr := shr(96, calldataload(sub(calldatasize(), 20))) } } // Emit logs via proxies function emitViaProxy_Transfer(address proxyAddr, address from, address to, uint value) internal FREEMEM { (bool success,) = proxyAddr.call(abi.encodePacked( uint8(3), keccak256(bytes('Transfer(address,address,uint256)')), bytes32(uint(uint160(from))), bytes32(uint(uint160(to))), value )); require(success, "e/log-proxy-fail"); } function emitViaProxy_Approval(address proxyAddr, address owner, address spender, uint value) internal FREEMEM { (bool success,) = proxyAddr.call(abi.encodePacked( uint8(3), keccak256(bytes('Approval(address,address,uint256)')), bytes32(uint(uint160(owner))), bytes32(uint(uint160(spender))), value )); require(success, "e/log-proxy-fail"); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./BaseModule.sol"; abstract contract BaseIRM is BaseModule { constructor(uint moduleId_, bytes32 moduleGitCommit_) BaseModule(moduleId_, moduleGitCommit_) {} int96 internal constant MAX_ALLOWED_INTEREST_RATE = int96(int(uint(5 * 1e27) / SECONDS_PER_YEAR)); // 500% APR int96 internal constant MIN_ALLOWED_INTEREST_RATE = 0; function computeInterestRateImpl(address, uint32) internal virtual returns (int96); function computeInterestRate(address underlying, uint32 utilisation) external returns (int96) { int96 rate = computeInterestRateImpl(underlying, utilisation); if (rate > MAX_ALLOWED_INTEREST_RATE) rate = MAX_ALLOWED_INTEREST_RATE; else if (rate < MIN_ALLOWED_INTEREST_RATE) rate = MIN_ALLOWED_INTEREST_RATE; return rate; } function reset(address underlying, bytes calldata resetParams) external virtual {} } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; interface IERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); } interface IERC20Permit { function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; function permit(address owner, address spender, uint value, uint deadline, bytes calldata signature) external; } interface IERC3156FlashBorrower { function onFlashLoan(address initiator, address token, uint256 amount, uint256 fee, bytes calldata data) external returns (bytes32); } interface IERC3156FlashLender { function maxFlashLoan(address token) external view returns (uint256); function flashFee(address token, uint256 amount) external view returns (uint256); function flashLoan(IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data) external returns (bool); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Interfaces.sol"; library Utils { function safeTransferFrom(address token, address from, address to, uint value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), string(data)); } function safeTransfer(address token, address to, uint value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), string(data)); } function safeApprove(address token, address to, uint value) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), string(data)); } } // SPDX-License-Identifier: AGPL-3.0-or-later // From MakerDAO DSS // 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; library RPow { 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) } } } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Storage.sol"; // This interface is used to avoid a circular dependency between BaseLogic and RiskManager interface IRiskManager { struct NewMarketParameters { uint16 pricingType; uint32 pricingParameters; Storage.AssetConfig config; } struct LiquidityStatus { uint collateralValue; uint liabilityValue; uint numBorrows; bool borrowIsolated; } struct AssetLiquidity { address underlying; LiquidityStatus status; } function getNewMarketParameters(address underlying) external returns (NewMarketParameters memory); function requireLiquidity(address account) external view; function computeLiquidity(address account) external view returns (LiquidityStatus memory status); function computeAssetLiquidities(address account) external view returns (AssetLiquidity[] memory assets); function getPrice(address underlying) external view returns (uint twap, uint twapPeriod); function getPriceFull(address underlying) external view returns (uint twap, uint twapPeriod, uint currPrice); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; //import "hardhat/console.sol"; // DEV_MODE import "./Storage.sol"; import "./Events.sol"; import "./Proxy.sol"; abstract contract Base is Storage, Events { // Modules function _createProxy(uint proxyModuleId) internal returns (address) { require(proxyModuleId != 0, "e/create-proxy/invalid-module"); require(proxyModuleId <= MAX_EXTERNAL_MODULEID, "e/create-proxy/internal-module"); // If we've already created a proxy for a single-proxy module, just return it: if (proxyLookup[proxyModuleId] != address(0)) return proxyLookup[proxyModuleId]; // Otherwise create a proxy: address proxyAddr = address(new Proxy()); if (proxyModuleId <= MAX_EXTERNAL_SINGLE_PROXY_MODULEID) proxyLookup[proxyModuleId] = proxyAddr; trustedSenders[proxyAddr] = TrustedSenderInfo({ moduleId: uint32(proxyModuleId), moduleImpl: address(0) }); emit ProxyCreated(proxyAddr, proxyModuleId); return proxyAddr; } function callInternalModule(uint moduleId, bytes memory input) internal returns (bytes memory) { (bool success, bytes memory result) = moduleLookup[moduleId].delegatecall(input); if (!success) revertBytes(result); return result; } // Modifiers modifier nonReentrant() { require(reentrancyLock == REENTRANCYLOCK__UNLOCKED, "e/reentrancy"); reentrancyLock = REENTRANCYLOCK__LOCKED; _; reentrancyLock = REENTRANCYLOCK__UNLOCKED; } modifier reentrantOK() { // documentation only _; } // Used to flag functions which do not modify storage, but do perform a delegate call // to a view function, which prohibits a standard view modifier. The flag is used to // patch state mutability in compiled ABIs and interfaces. modifier staticDelegate() { _; } // WARNING: Must be very careful with this modifier. It resets the free memory pointer // to the value it was when the function started. This saves gas if more memory will // be allocated in the future. However, if the memory will be later referenced // (for example because the function has returned a pointer to it) then you cannot // use this modifier. modifier FREEMEM() { uint origFreeMemPtr; assembly { origFreeMemPtr := mload(0x40) } _; /* assembly { // DEV_MODE: overwrite the freed memory with garbage to detect bugs let garbage := 0xDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEFDEADBEEF for { let i := origFreeMemPtr } lt(i, mload(0x40)) { i := add(i, 32) } { mstore(i, garbage) } } */ assembly { mstore(0x40, origFreeMemPtr) } } // Error handling function revertBytes(bytes memory errMsg) internal pure { if (errMsg.length > 0) { assembly { revert(add(32, errMsg), mload(errMsg)) } } revert("e/empty-error"); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Constants.sol"; abstract contract Storage is Constants { // Dispatcher and upgrades uint reentrancyLock; address upgradeAdmin; address governorAdmin; mapping(uint => address) moduleLookup; // moduleId => module implementation mapping(uint => address) proxyLookup; // moduleId => proxy address (only for single-proxy modules) struct TrustedSenderInfo { uint32 moduleId; // 0 = un-trusted address moduleImpl; // only non-zero for external single-proxy modules } mapping(address => TrustedSenderInfo) trustedSenders; // sender address => moduleId (0 = un-trusted) // Account-level state // Sub-accounts are considered distinct accounts struct AccountStorage { // Packed slot: 1 + 5 + 4 + 20 = 30 uint8 deferLiquidityStatus; uint40 lastAverageLiquidityUpdate; uint32 numMarketsEntered; address firstMarketEntered; uint averageLiquidity; address averageLiquidityDelegate; } mapping(address => AccountStorage) accountLookup; mapping(address => address[MAX_POSSIBLE_ENTERED_MARKETS]) marketsEntered; // Markets and assets struct AssetConfig { // Packed slot: 20 + 1 + 4 + 4 + 3 = 32 address eTokenAddress; bool borrowIsolated; uint32 collateralFactor; uint32 borrowFactor; uint24 twapWindow; } struct UserAsset { uint112 balance; uint144 owed; uint interestAccumulator; } struct AssetStorage { // Packed slot: 5 + 1 + 4 + 12 + 4 + 2 + 4 = 32 uint40 lastInterestAccumulatorUpdate; uint8 underlyingDecimals; // Not dynamic, but put here to live in same storage slot uint32 interestRateModel; int96 interestRate; uint32 reserveFee; uint16 pricingType; uint32 pricingParameters; address underlying; uint96 reserveBalance; address dTokenAddress; uint112 totalBalances; uint144 totalBorrows; uint interestAccumulator; mapping(address => UserAsset) users; mapping(address => mapping(address => uint)) eTokenAllowance; mapping(address => mapping(address => uint)) dTokenAllowance; } mapping(address => AssetConfig) internal underlyingLookup; // underlying => AssetConfig mapping(address => AssetStorage) internal eTokenLookup; // EToken => AssetStorage mapping(address => address) internal dTokenLookup; // DToken => EToken mapping(address => address) internal pTokenLookup; // PToken => underlying mapping(address => address) internal reversePTokenLookup; // underlying => PToken } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; import "./Storage.sol"; abstract contract Events { event Genesis(); event ProxyCreated(address indexed proxy, uint moduleId); event MarketActivated(address indexed underlying, address indexed eToken, address indexed dToken); event PTokenActivated(address indexed underlying, address indexed pToken); event EnterMarket(address indexed underlying, address indexed account); event ExitMarket(address indexed underlying, address indexed account); event Deposit(address indexed underlying, address indexed account, uint amount); event Withdraw(address indexed underlying, address indexed account, uint amount); event Borrow(address indexed underlying, address indexed account, uint amount); event Repay(address indexed underlying, address indexed account, uint amount); event Liquidation(address indexed liquidator, address indexed violator, address indexed underlying, address collateral, uint repay, uint yield, uint healthScore, uint baseDiscount, uint discount); event TrackAverageLiquidity(address indexed account); event UnTrackAverageLiquidity(address indexed account); event DelegateAverageLiquidity(address indexed account, address indexed delegate); event PTokenWrap(address indexed underlying, address indexed account, uint amount); event PTokenUnWrap(address indexed underlying, address indexed account, uint amount); event AssetStatus(address indexed underlying, uint totalBalances, uint totalBorrows, uint96 reserveBalance, uint poolSize, uint interestAccumulator, int96 interestRate, uint timestamp); event RequestDeposit(address indexed account, uint amount); event RequestWithdraw(address indexed account, uint amount); event RequestMint(address indexed account, uint amount); event RequestBurn(address indexed account, uint amount); event RequestTransferEToken(address indexed from, address indexed to, uint amount); event RequestBorrow(address indexed account, uint amount); event RequestRepay(address indexed account, uint amount); event RequestTransferDToken(address indexed from, address indexed to, uint amount); event RequestLiquidate(address indexed liquidator, address indexed violator, address indexed underlying, address collateral, uint repay, uint minYield); event InstallerSetUpgradeAdmin(address indexed newUpgradeAdmin); event InstallerSetGovernorAdmin(address indexed newGovernorAdmin); event InstallerInstallModule(uint indexed moduleId, address indexed moduleImpl, bytes32 moduleGitCommit); event GovSetAssetConfig(address indexed underlying, Storage.AssetConfig newConfig); event GovSetIRM(address indexed underlying, uint interestRateModel, bytes resetParams); event GovSetPricingConfig(address indexed underlying, uint16 newPricingType, uint32 newPricingParameter); event GovSetReserveFee(address indexed underlying, uint32 newReserveFee); event GovConvertReserves(address indexed underlying, address indexed recipient, uint amount); event RequestSwap(address indexed accountIn, address indexed accountOut, address indexed underlyingIn, address underlyingOut, uint amount, uint swapType); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; contract Proxy { address immutable creator; constructor() { creator = msg.sender; } // External interface fallback() external { address creator_ = creator; if (msg.sender == creator_) { assembly { mstore(0, 0) calldatacopy(31, 0, calldatasize()) switch mload(0) // numTopics case 0 { log0(32, sub(calldatasize(), 1)) } case 1 { log1(64, sub(calldatasize(), 33), mload(32)) } case 2 { log2(96, sub(calldatasize(), 65), mload(32), mload(64)) } case 3 { log3(128, sub(calldatasize(), 97), mload(32), mload(64), mload(96)) } case 4 { log4(160, sub(calldatasize(), 129), mload(32), mload(64), mload(96), mload(128)) } default { revert(0, 0) } return(0, 0) } } else { assembly { mstore(0, 0xe9c4a3ac00000000000000000000000000000000000000000000000000000000) // dispatch() selector calldatacopy(4, 0, calldatasize()) mstore(add(4, calldatasize()), shl(96, caller())) let result := call(gas(), creator_, 0, 0, add(24, calldatasize()), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity ^0.8.0; abstract contract Constants { // Universal uint internal constant SECONDS_PER_YEAR = 365.2425 * 86400; // Gregorian calendar // Protocol parameters uint internal constant MAX_SANE_AMOUNT = type(uint112).max; uint internal constant MAX_SANE_SMALL_AMOUNT = type(uint96).max; uint internal constant MAX_SANE_DEBT_AMOUNT = type(uint144).max; uint internal constant INTERNAL_DEBT_PRECISION = 1e9; uint internal constant MAX_ENTERED_MARKETS = 10; // per sub-account uint internal constant MAX_POSSIBLE_ENTERED_MARKETS = 2**32; // limited by size of AccountStorage.numMarketsEntered uint internal constant CONFIG_FACTOR_SCALE = 4_000_000_000; // must fit into a uint32 uint internal constant RESERVE_FEE_SCALE = 4_000_000_000; // must fit into a uint32 uint32 internal constant DEFAULT_RESERVE_FEE = uint32(0.23 * 4_000_000_000); uint internal constant INITIAL_INTEREST_ACCUMULATOR = 1e27; uint internal constant AVERAGE_LIQUIDITY_PERIOD = 24 * 60 * 60; uint16 internal constant MIN_UNISWAP3_OBSERVATION_CARDINALITY = 144; uint24 internal constant DEFAULT_TWAP_WINDOW_SECONDS = 30 * 60; uint32 internal constant DEFAULT_BORROW_FACTOR = uint32(0.28 * 4_000_000_000); uint32 internal constant SELF_COLLATERAL_FACTOR = uint32(0.95 * 4_000_000_000); // Implementation internals uint internal constant REENTRANCYLOCK__UNLOCKED = 1; uint internal constant REENTRANCYLOCK__LOCKED = 2; uint8 internal constant DEFERLIQUIDITY__NONE = 0; uint8 internal constant DEFERLIQUIDITY__CLEAN = 1; uint8 internal constant DEFERLIQUIDITY__DIRTY = 2; // Pricing types uint16 internal constant PRICINGTYPE__PEGGED = 1; uint16 internal constant PRICINGTYPE__UNISWAP3_TWAP = 2; uint16 internal constant PRICINGTYPE__FORWARDED = 3; // Modules // Public single-proxy modules uint internal constant MODULEID__INSTALLER = 1; uint internal constant MODULEID__MARKETS = 2; uint internal constant MODULEID__LIQUIDATION = 3; uint internal constant MODULEID__GOVERNANCE = 4; uint internal constant MODULEID__EXEC = 5; uint internal constant MODULEID__SWAP = 6; uint internal constant MAX_EXTERNAL_SINGLE_PROXY_MODULEID = 499_999; // Public multi-proxy modules uint internal constant MODULEID__ETOKEN = 500_000; uint internal constant MODULEID__DTOKEN = 500_001; uint internal constant MAX_EXTERNAL_MODULEID = 999_999; // Internal modules uint internal constant MODULEID__RISK_MANAGER = 1_000_000; // Interest rate models // Default for new markets uint internal constant MODULEID__IRM_DEFAULT = 2_000_000; // Testing-only uint internal constant MODULEID__IRM_ZERO = 2_000_001; uint internal constant MODULEID__IRM_FIXED = 2_000_002; uint internal constant MODULEID__IRM_LINEAR = 2_000_100; // Classes uint internal constant MODULEID__IRM_CLASS__STABLE = 2_000_500; uint internal constant MODULEID__IRM_CLASS__MAJOR = 2_000_501; uint internal constant MODULEID__IRM_CLASS__MIDCAP = 2_000_502; uint internal constant MODULEID__IRM_CLASS__MEGA = 2_000_503; // Swap types uint internal constant SWAP_TYPE__UNI_EXACT_INPUT_SINGLE = 1; uint internal constant SWAP_TYPE__UNI_EXACT_INPUT = 2; uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT_SINGLE = 3; uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT = 4; uint internal constant SWAP_TYPE__1INCH = 5; uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT_SINGLE_REPAY = 6; uint internal constant SWAP_TYPE__UNI_EXACT_OUTPUT_REPAY = 7; } // 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; }
Storage loads Derived state Compute new values
function initAssetCache(address underlying, AssetStorage storage assetStorage, AssetCache memory assetCache) internal view returns (bool dirty) { dirty = false; assetCache.underlying = underlying; assetCache.lastInterestAccumulatorUpdate = assetStorage.lastInterestAccumulatorUpdate; uint8 underlyingDecimals = assetCache.underlyingDecimals = assetStorage.underlyingDecimals; assetCache.interestRateModel = assetStorage.interestRateModel; assetCache.interestRate = assetStorage.interestRate; assetCache.reserveFee = assetStorage.reserveFee; assetCache.pricingType = assetStorage.pricingType; assetCache.pricingParameters = assetStorage.pricingParameters; assetCache.reserveBalance = assetStorage.reserveBalance; assetCache.totalBalances = assetStorage.totalBalances; assetCache.totalBorrows = assetStorage.totalBorrows; assetCache.interestAccumulator = assetStorage.interestAccumulator; unchecked { assetCache.underlyingDecimalsScaler = 10**(18 - underlyingDecimals); assetCache.maxExternalAmount = MAX_SANE_AMOUNT / assetCache.underlyingDecimalsScaler; } uint poolSize = callBalanceOf(assetCache, address(this)); if (poolSize <= assetCache.maxExternalAmount) { assetCache.poolSize = 0; } if (block.timestamp != assetCache.lastInterestAccumulatorUpdate) { dirty = true; uint deltaT = block.timestamp - assetCache.lastInterestAccumulatorUpdate; uint newInterestAccumulator = (RPow.rpow(uint(int(assetCache.interestRate) + 1e27), deltaT, 1e27) * assetCache.interestAccumulator) / 1e27; uint newTotalBorrows = assetCache.totalBorrows * newInterestAccumulator / assetCache.interestAccumulator; uint newReserveBalance = assetCache.reserveBalance; uint newTotalBalances = assetCache.totalBalances; uint feeAmount = (newTotalBorrows - assetCache.totalBorrows) * (assetCache.reserveFee == type(uint32).max ? DEFAULT_RESERVE_FEE : assetCache.reserveFee) / (RESERVE_FEE_SCALE * INTERNAL_DEBT_PRECISION); if (feeAmount != 0) { uint poolAssets = assetCache.poolSize + (newTotalBorrows / INTERNAL_DEBT_PRECISION); newTotalBalances = poolAssets * newTotalBalances / (poolAssets - feeAmount); newReserveBalance += newTotalBalances - assetCache.totalBalances; } if (newTotalBalances <= MAX_SANE_AMOUNT && newTotalBorrows <= MAX_SANE_DEBT_AMOUNT) { assetCache.totalBorrows = encodeDebtAmount(newTotalBorrows); assetCache.interestAccumulator = newInterestAccumulator; assetCache.lastInterestAccumulatorUpdate = uint40(block.timestamp); if (newTotalBalances != assetCache.totalBalances) { assetCache.reserveBalance = encodeSmallAmount(newReserveBalance); assetCache.totalBalances = encodeAmount(newTotalBalances); } } } }
25,757
[ 1, 3245, 6277, 14969, 2950, 919, 8155, 394, 924, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1208, 6672, 1649, 12, 2867, 6808, 16, 10494, 3245, 2502, 3310, 3245, 16, 10494, 1649, 3778, 3310, 1649, 13, 2713, 1476, 1135, 261, 6430, 9603, 13, 288, 203, 3639, 9603, 273, 629, 31, 203, 203, 3639, 3310, 1649, 18, 9341, 6291, 273, 6808, 31, 203, 203, 203, 3639, 3310, 1649, 18, 2722, 29281, 27361, 1891, 273, 3310, 3245, 18, 2722, 29281, 27361, 1891, 31, 203, 3639, 2254, 28, 6808, 31809, 273, 3310, 1649, 18, 9341, 6291, 31809, 273, 3310, 3245, 18, 9341, 6291, 31809, 31, 203, 3639, 3310, 1649, 18, 2761, 395, 4727, 1488, 273, 3310, 3245, 18, 2761, 395, 4727, 1488, 31, 203, 3639, 3310, 1649, 18, 2761, 395, 4727, 273, 3310, 3245, 18, 2761, 395, 4727, 31, 203, 3639, 3310, 1649, 18, 455, 6527, 14667, 273, 3310, 3245, 18, 455, 6527, 14667, 31, 203, 3639, 3310, 1649, 18, 683, 14774, 559, 273, 3310, 3245, 18, 683, 14774, 559, 31, 203, 3639, 3310, 1649, 18, 683, 14774, 2402, 273, 3310, 3245, 18, 683, 14774, 2402, 31, 203, 203, 3639, 3310, 1649, 18, 455, 6527, 13937, 273, 3310, 3245, 18, 455, 6527, 13937, 31, 203, 203, 3639, 3310, 1649, 18, 4963, 38, 26488, 273, 3310, 3245, 18, 4963, 38, 26488, 31, 203, 3639, 3310, 1649, 18, 4963, 38, 280, 3870, 273, 3310, 3245, 18, 4963, 38, 280, 3870, 31, 203, 203, 3639, 3310, 1649, 18, 2761, 395, 27361, 273, 3310, 3245, 18, 2761, 395, 27361, 31, 203, 203, 203, 3639, 22893, 288, 203, 5411, 3310, 1649, 18, 9341, 6291, 31809, 55, 13501, 2 ]
pragma solidity 0.5.8; contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(isOwner()); _; } function isOwner() public view returns (bool) { return msg.sender == _owner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title RelayRegistry * @dev Singleton contract that registers a whitelist of relays accessed by the factory and smart wallets. Contract is owned by an external account for now but ownership should be transferred to a governance contract in the future. */ contract RelayRegistry is Ownable { event AddedRelay(address relay); event RemovedRelay(address relay); mapping (address => bool) public relays; constructor(address initialRelay) public { relays[initialRelay] = true; } /** * @dev Allows relay registry owner to add or remove a relay from the whitelist * @param relay Address of the selected relay * @param value True to add them to the whitelist, false to remove them */ function triggerRelay(address relay, bool value) onlyOwner public returns (bool) { relays[relay] = value; if(value) { emit AddedRelay(relay); } else { emit RemovedRelay(relay); } return true; } } interface IERC20 { function transfer(address to, uint256 value) external returns (bool); } /** * @title Smart Wallet Contract * @dev All functions of this contract should be called using delegatecall from the Proxy contract. This allows us to significantly reduce the deployment costs of smart wallets. All functions of this contract are executed in the context of Proxy contract. */ contract SmartWallet { event Upgrade(address indexed newImplementation); /** * @dev Shared key value store. Data should be encoded and decoded using abi.encode()/abi.decode() by different functions. No data is actually stored in SmartWallet, instead everything is stored in the Proxy contract's context. */ mapping (bytes32 => bytes) public store; modifier onlyRelay { RelayRegistry registry = RelayRegistry(0x4360b517f5b3b2D4ddfAEDb4fBFc7eF0F48A4Faa); require(registry.relays(msg.sender)); _; } modifier onlyOwner { require(msg.sender == abi.decode(store["factory"], (address)) || msg.sender == abi.decode(store["owner"], (address))); _; } /** * @dev Function called once by Factory contract to initiate owner and nonce. This is necessary because we cannot pass arguments to a CREATE2-created contract without changing its address. * @param owner Wallet Owner */ function initiate(address owner) public returns (bool) { // this function can only be called by the factory if(msg.sender != abi.decode(store["factory"], (address))) return false; // store current owner in key store store["owner"] = abi.encode(owner); store["nonce"] = abi.encode(0); return true; } /** * @dev Same as above, but also applies a feee to a relayer address provided by the factory * @param owner Wallet Owner * @param relay Address of the relayer * @param fee Fee paid to relayer in a token * @param token Address of ERC20 contract in which fee will be denominated. */ function initiate(address owner, address relay, uint fee, address token) public returns (bool) { require(initiate(owner), "internal initiate failed"); // Access ERC20 token IERC20 tokenContract = IERC20(token); // Send fee to relay tokenContract.transfer(relay, fee); return true; } /** * @dev Relayed token transfer. Submitted by a relayer on behalf of the wallet owner. * @param to Recipient address * @param value Transfer amount * @param fee Fee paid to the relayer * @param tokenContract Address of the token contract used for both the transfer and the fees * @param deadline Block number deadline for this signed message */ function pay(address to, uint value, uint fee, address tokenContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) { uint currentNonce = abi.decode(store["nonce"], (uint)); require(block.number <= deadline); require(abi.decode(store["owner"], (address)) == recover(keccak256(abi.encodePacked("pay", msg.sender, to, tokenContract, value, fee, tx.gasprice, currentNonce, deadline)), v, r, s)); IERC20 token = IERC20(tokenContract); store["nonce"] = abi.encode(currentNonce+1); token.transfer(to, value); token.transfer(msg.sender, fee); return true; } /** * @dev Direct token transfer. Submitted by the wallet owner * @param to Recipient address * @param value Transfer amount * @param tokenContract Address of the token contract used for the transfer */ function pay(address to, uint value, address tokenContract) onlyOwner public returns (bool) { IERC20 token = IERC20(tokenContract); token.transfer(to, value); return true; } /** * @dev Same as above but allows batched transfers in multiple tokens */ function pay(address[] memory to, uint[] memory value, address[] memory tokenContract) onlyOwner public returns (bool) { for (uint i; i < to.length; i++) { IERC20 token = IERC20(tokenContract[i]); token.transfer(to[i], value[i]); } return true; } /** * @dev Internal function that executes a call to any contract * @param contractAddress Address of the contract to call * @param data calldata to send to contractAddress * @param msgValue Amount in wei to be sent with the call to the contract from the wallet's balance */ function _execCall(address contractAddress, bytes memory data, uint256 msgValue) internal returns (bool result) { // Warning: This executes an external contract call, may pose re-entrancy risk. assembly { result := call(gas, contractAddress, msgValue, add(data, 0x20), mload(data), 0, 0) } } /** * @dev Internal function that creates any contract * @param data bytecode of the new contract */ function _execCreate(bytes memory data) internal returns (bool result) { address deployedContract; assembly { deployedContract := create(0, add(data, 0x20), mload(data)) } result = (deployedContract != address(0)); } /** * @dev Internal function that creates any contract using create2 * @param data bytecode of the new contract * @param salt Create2 salt parameter */ function _execCreate2(bytes memory data, uint256 salt) internal returns (bool result) { address deployedContract; assembly { deployedContract := create2(0, add(data, 0x20), mload(data), salt) } result = (deployedContract != address(0)); } /** * @dev Public function that allows the owner to execute a call to any contract * @param contractAddress Address of the contract to call * @param data calldata to send to contractAddress * @param msgValue Amount in wei to be sent with the call to the contract from the wallet's balance */ function execCall(address contractAddress, bytes memory data, uint256 msgValue) onlyOwner public returns (bool) { require(_execCall(contractAddress, data, msgValue)); return true; } /** * @dev Public function that allows a relayer to execute a call to any contract on behalf of the owner * @param contractAddress Address of the contract to call * @param data calldata to send to contractAddress * @param msgValue Amount in wei to be sent with the call to the contract from the wallet's balance * @param fee Fee paid to the relayer * @param tokenContract Address of the token contract used for the fee * @param deadline Block number deadline for this signed message */ function execCall(address contractAddress, bytes memory data, uint256 msgValue, uint fee, address tokenContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) { uint currentNonce = abi.decode(store["nonce"], (uint)); require(block.number <= deadline); require(abi.decode(store["owner"], (address)) == recover(keccak256(abi.encodePacked("execCall", msg.sender, contractAddress, tokenContract, data, msgValue, fee, tx.gasprice, currentNonce, deadline)), v, r, s)); IERC20 token = IERC20(tokenContract); store["nonce"] = abi.encode(currentNonce+1); token.transfer(msg.sender, fee); require(_execCall(contractAddress, data, msgValue)); return true; } /** * @dev Public function that allows the owner to create any contract * @param data bytecode of the new contract */ function execCreate(bytes memory data) onlyOwner public returns (bool) { require(_execCreate(data)); return true; } /** * @dev Public function that allows a relayer to create any contract on behalf of the owner * @param data new contract bytecode * @param fee Fee paid to the relayer * @param tokenContract Address of the token contract used for the fee * @param deadline Block number deadline for this signed message */ function execCreate(bytes memory data, uint fee, address tokenContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) { uint currentNonce = abi.decode(store["nonce"], (uint)); require(block.number <= deadline); require(abi.decode(store["owner"], (address)) == recover(keccak256(abi.encodePacked("execCreate", msg.sender, tokenContract, data, fee, tx.gasprice, currentNonce, deadline)), v, r, s)); require(_execCreate(data)); IERC20 token = IERC20(tokenContract); store["nonce"] = abi.encode(currentNonce+1); token.transfer(msg.sender, fee); return true; } /** * @dev Public function that allows the owner to create any contract using create2 * @param data bytecode of the new contract * @param salt Create2 salt parameter */ function execCreate2(bytes memory data, uint salt) onlyOwner public returns (bool) { require(_execCreate2(data, salt)); return true; } /** * @dev Public function that allows a relayer to create any contract on behalf of the owner using create2 * @param data new contract bytecode * @param salt Create2 salt parameter * @param fee Fee paid to the relayer * @param tokenContract Address of the token contract used for the fee * @param deadline Block number deadline for this signed message */ function execCreate2(bytes memory data, uint salt, uint fee, address tokenContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) { uint currentNonce = abi.decode(store["nonce"], (uint)); require(block.number <= deadline); require(abi.decode(store["owner"], (address)) == recover(keccak256(abi.encodePacked("execCreate2", msg.sender, tokenContract, data, salt, fee, tx.gasprice, currentNonce, deadline)), v, r, s)); require(_execCreate2(data, salt)); IERC20 token = IERC20(tokenContract); store["nonce"] = abi.encode(currentNonce+1); token.transfer(msg.sender, fee); return true; } /** * @dev Since all eth transfers to this contract are redirected to the owner. This is the only way for anyone, including the owner, to keep ETH on this contract. */ function depositEth() public payable {} /** * @dev Allows the owner to withdraw all ETH from the contract. */ function withdrawEth() public onlyOwner() { address payable owner = abi.decode(store["owner"], (address)); owner.transfer(address(this).balance); } /** * @dev Allows a relayer to change the address of the smart wallet implementation contract on behalf of the owner. New contract should have its own upgradability logic or Proxy will be stuck on it. * @param implementation Address of the new implementation contract to replace this one. * @param fee Fee paid to the relayer * @param feeContract Address of the fee token contract * @param deadline Block number deadline for this signed message */ function upgrade(address implementation, uint fee, address feeContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) { uint currentNonce = abi.decode(store["nonce"], (uint)); require(block.number <= deadline); address owner = abi.decode(store["owner"], (address)); require(owner == recover(keccak256(abi.encodePacked("upgrade", msg.sender, implementation, feeContract, fee, tx.gasprice, currentNonce, deadline)), v, r, s)); store["nonce"] = abi.encode(currentNonce+1); store["fallback"] = abi.encode(implementation); IERC20 feeToken = IERC20(feeContract); feeToken.transfer(msg.sender, fee); emit Upgrade(implementation); return true; } /** * @dev Same as above, but activated directly by the owner. * @param implementation Address of the new implementation contract to replace this one. */ function upgrade(address implementation) onlyOwner public returns (bool) { store["fallback"] = abi.encode(implementation); emit Upgrade(implementation); return true; } /** * @dev Internal function used to prefix hashes to allow for compatibility with signers such as Metamask * @param messageHash Original hash */ function recover(bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { bytes memory prefix = "\x19Metacash Signed Message:\n32"; bytes32 prefixedMessageHash = keccak256(abi.encodePacked(prefix, messageHash)); return ecrecover(prefixedMessageHash, v, r, s); } } /** * @title Proxy * @dev This contract is usually deployed as part of every user's first gasless transaction. It refers to a hardcoded address of the smart wallet contract and uses its functions via delegatecall. */ contract Proxy { /** * @dev Shared key value store. All data across different SmartWallet implementations is stored here. It also keeps storage across different upgrades. */ mapping (bytes32 => bytes) public store; /** * @dev The Proxy constructor adds the hardcoded address of SmartWallet and the address of the factory (from msg.sender) to the store for later transactions */ constructor() public { // set implementation address in storage store["fallback"] = abi.encode(0xEfc66C37a06507bCcABc0ce8d8bb5Ac4c1A2a8AA); // SmartWallet address // set factory address in storage store["factory"] = abi.encode(msg.sender); } /** * @dev The fallback functions forwards everything as a delegatecall to the implementation SmartWallet contract */ function() external payable { address impl = abi.decode(store["fallback"], (address)); assembly { let ptr := mload(0x40) // (1) copy incoming call data calldatacopy(ptr, 0, calldatasize) // (2) forward call to logic contract let result := delegatecall(gas, impl, ptr, calldatasize, 0, 0) let size := returndatasize // (3) retrieve return data returndatacopy(ptr, 0, size) // (4) forward return data back to caller switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } /** * @title Smart wallet factory * @dev Singleton contract responsible for deploying new smart wallet instances */ contract Factory { event Deployed(address indexed addr, address indexed owner); modifier onlyRelay { RelayRegistry registry = RelayRegistry(0x4360b517f5b3b2D4ddfAEDb4fBFc7eF0F48A4Faa); // Relay Registry address require(registry.relays(msg.sender)); _; } /** * @dev Internal function used for deploying smart wallets using create2 * @param owner Address of the wallet signer address (external account) associated with the smart wallet */ function deployCreate2(address owner) internal returns (address) { bytes memory code = type(Proxy).creationCode; address addr; assembly { // create2 addr := create2(0, add(code, 0x20), mload(code), owner) // revert if contract was not created if iszero(extcodesize(addr)) {revert(0, 0)} } return addr; } /** * @dev Allows a relayer to deploy a smart wallet on behalf of a user * @param fee Fee paid from the user's newly deployed smart wallet to the relay * @param token Address of token contract for the fee * @param deadline Block number deadline for this signed message */ function deployWallet(uint fee, address token, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (address) { require(block.number <= deadline); address signer = recover(keccak256(abi.encodePacked("deployWallet", msg.sender, token, tx.gasprice, fee, deadline)), v, r, s); address addr = deployCreate2(signer); SmartWallet wallet = SmartWallet(uint160(addr)); require(wallet.initiate(signer, msg.sender, fee, token)); emit Deployed(addr, signer); return addr; } /** * @dev Allows a relayer to deploy a smart wallet and send a token transfer on behalf of a user * @param fee Fee paid from the user's newly deployed smart wallet to the relay * @param token Address of token contract for the fee * @param to Transfer recipient address * @param value Transfer amount * @param deadline Block number deadline for this signed message */ function deployWalletPay(uint fee, address token, address to, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (address addr) { require(block.number <= deadline); address signer = recover(keccak256(abi.encodePacked("deployWalletPay", msg.sender, token, to, tx.gasprice, fee, value, deadline)), v, r, s); addr = deployCreate2(signer); SmartWallet wallet = SmartWallet(uint160(addr)); require(wallet.initiate(signer, msg.sender, fee, token)); require(wallet.pay(to, value, token)); emit Deployed(addr, signer); } /** * @dev Allows a user to directly deploy their own smart wallet */ function deployWallet() public returns (address) { address addr = deployCreate2(msg.sender); SmartWallet wallet = SmartWallet(uint160(addr)); require(wallet.initiate(msg.sender)); emit Deployed(addr, msg.sender); return addr; } /** * @dev Same as above, but also sends a transfer from the newly-deployed smart wallet * @param token Address of the token contract for the transfer * @param to Transfer recipient address * @param value Transfer amount */ function deployWalletPay(address token, address to, uint value) public returns (address) { address addr = deployCreate2(msg.sender); SmartWallet wallet = SmartWallet(uint160(addr)); require(wallet.pay(to, value, token)); require(wallet.initiate(msg.sender)); emit Deployed(addr, msg.sender); return addr; } /** * @dev Allows user to deploy their wallet and execute a call operation to a foreign contract. * @notice The order of wallet.execCall & wallet.initiate is important. It allows the fee to be paid after the execution is finished. This allows collect-call use cases. * @param contractAddress Address of the contract to call * @param data calldata to send to contractAddress */ function deployWalletExecCall(address contractAddress, bytes memory data) public payable returns (address) { address addr = deployCreate2(msg.sender); SmartWallet wallet = SmartWallet(uint160(addr)); if(msg.value > 0) { wallet.depositEth.value(msg.value)(); } require(wallet.execCall(contractAddress, data, msg.value)); require(wallet.initiate(msg.sender)); emit Deployed(addr, msg.sender); return addr; } /** * @dev Allows a relayer to deploy a wallet and execute a call operation to a foreign contract on behalf of a user. * @param contractAddress Address of the contract to call * @param data calldata to send to contractAddress * @param msgValue Amount in wei to be sent with the call to the contract from the wallet's balance * @param fee Fee paid to the relayer * @param token Address of the token contract for the fee * @param deadline Block number deadline for this signed message */ function deployWalletExecCall(address contractAddress, bytes memory data, uint msgValue, uint fee, address token, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (address addr) { require(block.number <= deadline); address signer = recover(keccak256(abi.encodePacked("deployWalletExecCall", msg.sender, token, contractAddress, data, msgValue, tx.gasprice, fee, deadline)), v, r, s); addr = deployCreate2(signer); SmartWallet wallet = SmartWallet(uint160(addr)); require(wallet.execCall(contractAddress, data, msgValue)); require(wallet.initiate(signer, msg.sender, fee, token)); emit Deployed(addr, signer); } /** * @dev Allows user to deploy their wallet and deploy a new contract through their wallet * @param data bytecode of the new contract */ function deployWalletExecCreate(bytes memory data) public returns (address) { address addr = deployCreate2(msg.sender); SmartWallet wallet = SmartWallet(uint160(addr)); require(wallet.execCreate(data)); require(wallet.initiate(msg.sender)); emit Deployed(addr, msg.sender); return addr; } /** * @dev Allows a relayer to deploy a wallet and deploy a new contract through the wallet on behalf of a user. * @param data bytecode of the new contract * @param fee Fee paid to the relayer * @param token Address of the token contract for the fee * @param deadline Block number deadline for this signed message */ function deployWalletExecCreate(bytes memory data, uint fee, address token, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (address addr) { require(block.number <= deadline); address signer = recover(keccak256(abi.encodePacked("deployWalletExecCreate", msg.sender, token, data, tx.gasprice, fee, deadline)), v, r, s); addr = deployCreate2(signer); SmartWallet wallet = SmartWallet(uint160(addr)); require(wallet.execCreate(data)); require(wallet.initiate(signer, msg.sender, fee, token)); emit Deployed(addr, signer); } /** * @dev Allows user to deploy their wallet and deploy a new contract through their wallet using create2 * @param data bytecode of the new contract * @param salt create2 salt parameter */ function deployWalletExecCreate2(bytes memory data, uint salt) public returns (address) { address addr = deployCreate2(msg.sender); SmartWallet wallet = SmartWallet(uint160(addr)); require(wallet.execCreate2(data, salt)); require(wallet.initiate(msg.sender)); emit Deployed(addr, msg.sender); return addr; } /** * @dev Allows a relayer to deploy a wallet and deploy a new contract through the wallet using create2 on behalf of a user. * @param data bytecode of the new contract * @param salt create2 salt parameter * @param fee Fee paid to the relayer * @param token Address of the token contract for the fee * @param deadline Block number deadline for this signed message */ function deployWalletExecCreate2(bytes memory data, uint salt, uint fee, address token, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (address addr) { require(block.number <= deadline); address signer = recover(keccak256(abi.encodePacked("deployWalletExecCreate2", msg.sender, token, data, tx.gasprice, salt, fee, deadline)), v, r, s); addr = deployCreate2(signer); SmartWallet wallet = SmartWallet(uint160(addr)); require(wallet.execCreate2(data, salt)); require(wallet.initiate(signer, msg.sender, fee, token)); emit Deployed(addr, signer); } /** * @dev Utility view function that allows clients to fetch a smart wallet address of any signer address * @param owner Signer address */ function getCreate2Address(address owner) public view returns (address) { bytes32 temp = keccak256(abi.encodePacked(bytes1(0xff), address(this), uint(owner), bytes32(keccak256(type(Proxy).creationCode)))); address ret; uint mask = 2 ** 160 - 1; assembly { ret := and(temp, mask) } return ret; } /** * @dev Utility view function that allows clients to fetch own smart wallet address */ function getCreate2Address() public view returns (address) { return getCreate2Address(msg.sender); } /** * @dev Utility view function that allows clients to query whether a signer's smart wallet can be deployed or has already been * @param owner Signer address */ function canDeploy(address owner) public view returns (bool inexistent) { address wallet = getCreate2Address(owner); assembly { inexistent := eq(extcodesize(wallet), 0) } } /** * @dev Utility view function that allows clients to query whether their signer's smart wallet can be deployed or has already been */ function canDeploy() public view returns (bool) { return canDeploy(msg.sender); } /** * @dev Internal function used to prefix hashes to allow for compatibility with signers such as Metamask * @param messageHash Original hash */ function recover(bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { bytes memory prefix = "\x19Metacash Signed Message:\n32"; bytes32 prefixedMessageHash = keccak256(abi.encodePacked(prefix, messageHash)); return ecrecover(prefixedMessageHash, v, r, s); } }
* @dev Utility view function that allows clients to query whether a signer's smart wallet can be deployed or has already been @param owner Signer address/
function canDeploy(address owner) public view returns (bool inexistent) { address wallet = getCreate2Address(owner); assembly { inexistent := eq(extcodesize(wallet), 0) } }
6,353,907
[ 1, 6497, 1476, 445, 716, 5360, 7712, 358, 843, 2856, 279, 10363, 1807, 13706, 9230, 848, 506, 19357, 578, 711, 1818, 2118, 225, 3410, 16763, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 848, 10015, 12, 2867, 3410, 13, 1071, 1476, 1135, 261, 6430, 316, 19041, 13, 288, 203, 3639, 1758, 9230, 273, 25667, 22, 1887, 12, 8443, 1769, 203, 3639, 19931, 288, 203, 5411, 316, 19041, 519, 7555, 12, 408, 7000, 554, 12, 19177, 3631, 374, 13, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x2d255b756dD75a11D75cf701aBaD7c6D64b0AeDD/sources/Roles.sol
* @dev Makes function callable only if sender is an operator./
modifier onlyOperator() { require(isOperator(_msgSender()), "OperatorRole: caller does not have the Operator role"); _; }
15,682,714
[ 1, 14534, 445, 4140, 1338, 309, 5793, 353, 392, 3726, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 5592, 1435, 288, 203, 3639, 2583, 12, 291, 5592, 24899, 3576, 12021, 1435, 3631, 315, 5592, 2996, 30, 4894, 1552, 486, 1240, 326, 11097, 2478, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/97/0x6e812dD5B642334bbd17636d3865CE82C3D4d7eB/sources/Sparta.sol
======================================EMISSION======================================== Internal - Update emission function
function _checkEmission() private { }
11,386,960
[ 1, 4428, 894, 631, 3375, 45, 4475, 4428, 1432, 3186, 300, 2315, 801, 19710, 445, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 1893, 1514, 19710, 1435, 3238, 288, 203, 3639, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.10; /// ------------ IMPORTS ------------ import {ReentrancyGuard} from "@rari-capital/solmate/src/utils/ReentrancyGuard.sol"; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {ERC721TransferHelper} from "../../../transferHelpers/ERC721TransferHelper.sol"; import {UniversalExchangeEventV1} from "../../../common/UniversalExchangeEvent/V1/UniversalExchangeEventV1.sol"; import {IncomingTransferSupportV1} from "../../../common/IncomingTransferSupport/V1/IncomingTransferSupportV1.sol"; import {FeePayoutSupportV1} from "../../../common/FeePayoutSupport/FeePayoutSupportV1.sol"; import {ModuleNamingSupportV1} from "../../../common/ModuleNamingSupport/ModuleNamingSupportV1.sol"; /// @title Offers V1 /// @author kulkarohan <[email protected]> /// @notice This module allows users to make ETH/ERC-20 offers for any ERC-721 token contract OffersV1 is ReentrancyGuard, UniversalExchangeEventV1, IncomingTransferSupportV1, FeePayoutSupportV1, ModuleNamingSupportV1 { /// @dev The indicator to pass all remaining gas when paying out royalties uint256 private constant USE_ALL_GAS_FLAG = 0; /// @notice The total number of offers made uint256 public offerCount; /// @notice The ZORA ERC-721 Transfer Helper ERC721TransferHelper public immutable erc721TransferHelper; /// @notice The metadata of an offer /// @param maker The address of the user who made the offer /// @param currency The address of the ERC-20 offered, or address(0) for ETH /// @param findersFeeBps The fee to the referrer of the offer /// @param amount The amount of ETH/ERC-20 tokens offered struct Offer { address maker; address currency; uint16 findersFeeBps; uint256 amount; } /// ------------ STORAGE ------------ /// @notice The metadata for a given offer /// @dev ERC-721 token address => ERC-721 token ID => Offer ID => Offer mapping(address => mapping(uint256 => mapping(uint256 => Offer))) public offers; /// @notice The offers for a given NFT /// @dev ERC-721 token address => ERC-721 token ID => Offer IDs mapping(address => mapping(uint256 => uint256[])) public offersForNFT; /// ------------ EVENTS ------------ /// @notice Emitted when an offer is created /// @param tokenContract The ERC-721 token address of the created offer /// @param tokenId The ERC-721 token ID of the created offer /// @param id The ID of the created offer /// @param offer The metadata of the created offer event OfferCreated(address indexed tokenContract, uint256 indexed tokenId, uint256 indexed id, Offer offer); /// @notice Emitted when an offer is updated /// @param tokenContract The ERC-721 token address of the updated offer /// @param tokenId The ERC-721 token ID of the updated offer /// @param id The ID of the updated offer /// @param offer The metadata of the updated offer event OfferUpdated(address indexed tokenContract, uint256 indexed tokenId, uint256 indexed id, Offer offer); /// @notice Emitted when an offer is canceled /// @param tokenContract The ERC-721 token address of the canceled offer /// @param tokenId The ERC-721 token ID of the canceled offer /// @param id The ID of the canceled offer /// @param offer The metadata of the canceled offer event OfferCanceled(address indexed tokenContract, uint256 indexed tokenId, uint256 indexed id, Offer offer); /// @notice Emitted when an offer is filled /// @param tokenContract The ERC-721 token address of the filled offer /// @param tokenId The ERC-721 token ID of the filled offer /// @param id The ID of the filled offer /// @param taker The address of the taker who filled the offer /// @param finder The address of the finder who referred the offer /// @param offer The metadata of the filled offer event OfferFilled(address indexed tokenContract, uint256 indexed tokenId, uint256 indexed id, address taker, address finder, Offer offer); /// ------------ CONSTRUCTOR ------------ /// @param _erc20TransferHelper The ZORA ERC-20 Transfer Helper address /// @param _erc721TransferHelper The ZORA ERC-721 Transfer Helper address /// @param _royaltyEngine The Manifold Royalty Engine address /// @param _protocolFeeSettings The ZoraProtocolFeeSettingsV1 address /// @param _wethAddress The WETH token address constructor( address _erc20TransferHelper, address _erc721TransferHelper, address _royaltyEngine, address _protocolFeeSettings, address _wethAddress ) IncomingTransferSupportV1(_erc20TransferHelper) FeePayoutSupportV1(_royaltyEngine, _protocolFeeSettings, _wethAddress, ERC721TransferHelper(_erc721TransferHelper).ZMM().registrar()) ModuleNamingSupportV1("Offers: v1.0") { erc721TransferHelper = ERC721TransferHelper(_erc721TransferHelper); } /// ------------ MAKER FUNCTIONS ------------ // ,-. // `-' // /|\ // | ,--------. ,-------------------. // / \ |OffersV1| |ERC20TransferHelper| // Caller `---+----' `---------+---------' // | createOffer() | | // | -----------------> | // | | | // | | transferFrom() | // | | -----------------------------> // | | | // | | |----. // | | | | transfer tokens into escrow // | | |<---' // | | | // | |----. | // | | | ++offerCount | // | |<---' | // | | | // | |----. | // | | | create offer | // | |<---' | // | | | // | |----. // | | | offersFor[NFT].append(id) // | |<---' // | | | // | |----. | // | | | emit OfferCreated() | // | |<---' | // | | | // | id | | // | <----------------- | // Caller ,---+----. ,---------+---------. // ,-. |OffersV1| |ERC20TransferHelper| // `-' `--------' `-------------------' // /|\ // | // / \ /// @notice Creates an offer for an NFT /// @param _tokenContract The address of the desired ERC-721 token /// @param _tokenId The ID of the desired ERC-721 token /// @param _currency The address of the ERC-20 token offering, or address(0) for ETH /// @param _amount The amount offering /// @param _findersFeeBps The bps of the amount (post-royalties) to send to a referrer of the sale /// @return The ID of the created offer function createOffer( address _tokenContract, uint256 _tokenId, address _currency, uint256 _amount, uint16 _findersFeeBps ) external payable nonReentrant returns (uint256) { require(_findersFeeBps <= 10000, "createOffer finders fee bps must be less than or equal to 10000"); // Validate offer and take custody _handleIncomingTransfer(_amount, _currency); // "the sun will devour the earth before it could ever overflow" - @transmissions11 // offerCount++ --> unchecked { offerCount++ } // "Although the increment part is cheaper with unchecked, the opcodes after become more expensive for some reason" - @joshieDo // unchecked { offerCount++ } --> offerCount++ // "Earlier today while reviewing c4rena findings I learned that doing ++offerCount would save 5 gas per increment here" - @devtooligan // offerCount++ --> ++offerCount // TLDR; unchecked checked // non-optimized 130,037 gas < 130,149 gas // optimized 127,932 gas > *127,298 gas* ++offerCount; offers[_tokenContract][_tokenId][offerCount] = Offer({ maker: msg.sender, currency: _currency, findersFeeBps: _findersFeeBps, amount: _amount }); offersForNFT[_tokenContract][_tokenId].push(offerCount); emit OfferCreated(_tokenContract, _tokenId, offerCount, offers[_tokenContract][_tokenId][offerCount]); return offerCount; } // ,-. // `-' // /|\ // | ,--------. ,-------------------. // / \ |OffersV1| |ERC20TransferHelper| // Caller `---+----' `---------+---------' // | setOfferAmount() | | // | -----------------> | // | | | // | | | // | _______________________________________________________________________ // | ! ALT / same token? | ! // | !_____/ | | ! // | ! | retrieve increase / refund decrease| ! // | ! | -----------------------------------> ! // | !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! // | ! [different token] | ! // | ! | refund previous offer | ! // | ! | -----------------------------------> ! // | ! | | ! // | ! | retrieve new offer | ! // | ! | -----------------------------------> ! // | !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! // | | | // | |----. | // | | | emit OfferUpdated() | // | |<---' | // Caller ,---+----. ,---------+---------. // ,-. |OffersV1| |ERC20TransferHelper| // `-' `--------' `-------------------' // /|\ // | // / \ /// @notice Updates the given offer for an NFT /// @param _tokenContract The address of the offer ERC-721 token /// @param _tokenId The ID of the offer ERC-721 token /// @param _offerId The ID of the offer /// @param _currency The address of the ERC-20 token offering, or address(0) for ETH /// @param _amount The new amount offering function setOfferAmount( address _tokenContract, uint256 _tokenId, uint256 _offerId, address _currency, uint256 _amount ) external payable nonReentrant { Offer storage offer = offers[_tokenContract][_tokenId][_offerId]; require(offer.maker == msg.sender, "setOfferAmount must be maker"); // If same currency -- if (_currency == offer.currency) { // Get initial amount uint256 prevAmount = offer.amount; // Ensure valid update require(_amount > 0 && _amount != prevAmount, "setOfferAmount invalid _amount"); // If offer increase -- if (_amount > prevAmount) { unchecked { // Get delta uint256 increaseAmount = _amount - prevAmount; // Custody increase _handleIncomingTransfer(increaseAmount, offer.currency); // Update storage offer.amount += increaseAmount; } // Else offer decrease -- } else { unchecked { // Get delta uint256 decreaseAmount = prevAmount - _amount; // Refund difference _handleOutgoingTransfer(offer.maker, decreaseAmount, offer.currency, USE_ALL_GAS_FLAG); // Update storage offer.amount -= decreaseAmount; } } // Else other currency -- } else { // Refund previous offer _handleOutgoingTransfer(offer.maker, offer.amount, offer.currency, USE_ALL_GAS_FLAG); // Custody new offer _handleIncomingTransfer(_amount, _currency); // Update storage offer.currency = _currency; offer.amount = _amount; } emit OfferUpdated(_tokenContract, _tokenId, _offerId, offer); } // ,-. // `-' // /|\ // | ,--------. ,-------------------. // / \ |OffersV1| |ERC20TransferHelper| // Caller `---+----' `---------+---------' // | cancelOffer() | | // | -----------------> | // | | | // | | transferFrom() | // | | ------------------------> // | | | // | | |----. // | | | | refund tokens from escrow // | | |<---' // | | | // | |----. // | | | emit OfferCanceled() // | |<---' // | | | // | |----. | // | | | delete offer | // | |<---' | // Caller ,---+----. ,---------+---------. // ,-. |OffersV1| |ERC20TransferHelper| // `-' `--------' `-------------------' // /|\ // | // / \ /// @notice Cancels and refunds the given offer for an NFT /// @param _tokenContract The ERC-721 token address of the offer /// @param _tokenId The ERC-721 token ID of the offer /// @param _offerId The ID of the offer function cancelOffer( address _tokenContract, uint256 _tokenId, uint256 _offerId ) external nonReentrant { Offer memory offer = offers[_tokenContract][_tokenId][_offerId]; require(offer.maker == msg.sender, "cancelOffer must be maker"); // Refund offer _handleOutgoingTransfer(offer.maker, offer.amount, offer.currency, USE_ALL_GAS_FLAG); emit OfferCanceled(_tokenContract, _tokenId, _offerId, offer); delete offers[_tokenContract][_tokenId][_offerId]; } /// ------------ TAKER FUNCTIONS ------------ // ,-. // `-' // /|\ // | ,--------. ,--------------------. // / \ |OffersV1| |ERC721TransferHelper| // Caller `---+----' `---------+----------' // | fillOffer() | | // | -----------------> | // | | | // | |----. | // | | | validate token owner | // | |<---' | // | | | // | |----. | // | | | handle royalty payouts | // | |<---' | // | | | // | | | // | __________________________________________________ // | ! ALT / finders fee configured for this offer? ! // | !_____/ | | ! // | ! |----. | ! // | ! | | handle finders fee payout| ! // | ! |<---' | ! // | !~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! // | !~[noop]~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~! // | | | // | | transferFrom() | // | | ------------------------------> // | | | // | | |----. // | | | | transfer NFT from taker to maker // | | |<---' // | | | // | |----. | // | | | emit ExchangeExecuted() | // | |<---' | // | | | // | |----. | // | | | emit OfferFilled() | // | |<---' | // | | | // | |----. // | | | delete offer from contract // | |<---' // Caller ,---+----. ,---------+----------. // ,-. |OffersV1| |ERC721TransferHelper| // `-' `--------' `--------------------' // /|\ // | // / \ /// @notice Fills a given offer for an owned NFT, in exchange for ETH/ERC-20 tokens /// @param _tokenContract The address of the ERC-721 token to transfer /// @param _tokenId The ID of the ERC-721 token to transfer /// @param _offerId The ID of the offer to fill /// @param _currency The address of the ERC-20 to take, or address(0) for ETH /// @param _amount The amount to take /// @param _finder The address of the offer referrer function fillOffer( address _tokenContract, uint256 _tokenId, uint256 _offerId, address _currency, uint256 _amount, address _finder ) external nonReentrant { Offer memory offer = offers[_tokenContract][_tokenId][_offerId]; require(offer.maker != address(0), "fillOffer must be active offer"); require(IERC721(_tokenContract).ownerOf(_tokenId) == msg.sender, "fillOffer must be token owner"); require(offer.currency == _currency && offer.amount == _amount, "fillOffer _currency & _amount must match offer"); // Payout respective parties, ensuring royalties are honored (uint256 remainingProfit, ) = _handleRoyaltyPayout(_tokenContract, _tokenId, offer.amount, offer.currency, USE_ALL_GAS_FLAG); // Payout optional protocol fee remainingProfit = _handleProtocolFeePayout(remainingProfit, offer.currency); // Payout optional finders fee if (_finder != address(0)) { uint256 findersFee = (remainingProfit * offer.findersFeeBps) / 10000; _handleOutgoingTransfer(_finder, findersFee, offer.currency, USE_ALL_GAS_FLAG); remainingProfit -= findersFee; } // Transfer remaining ETH/ERC-20 tokens to offer taker _handleOutgoingTransfer(msg.sender, remainingProfit, offer.currency, USE_ALL_GAS_FLAG); // Transfer NFT to offer maker erc721TransferHelper.transferFrom(_tokenContract, msg.sender, offer.maker, _tokenId); ExchangeDetails memory userAExchangeDetails = ExchangeDetails({tokenContract: offer.currency, tokenId: 0, amount: offer.amount}); ExchangeDetails memory userBExchangeDetails = ExchangeDetails({tokenContract: _tokenContract, tokenId: _tokenId, amount: 1}); emit ExchangeExecuted(offer.maker, msg.sender, userAExchangeDetails, userBExchangeDetails); emit OfferFilled(_tokenContract, _tokenId, _offerId, msg.sender, _finder, offer); delete offers[_tokenContract][_tokenId][_offerId]; } }
Transfer remaining ETH/ERC-20 tokens to offer taker
_handleOutgoingTransfer(msg.sender, remainingProfit, offer.currency, USE_ALL_GAS_FLAG);
1,777,191
[ 1, 5912, 4463, 512, 2455, 19, 654, 39, 17, 3462, 2430, 358, 10067, 268, 6388, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 4110, 24866, 5912, 12, 3576, 18, 15330, 16, 4463, 626, 7216, 16, 10067, 18, 7095, 16, 14988, 67, 4685, 67, 43, 3033, 67, 9651, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42220/0x8eBbCa451eF4D55b660c32bac93CCF5651D06ED6/sources/contracts/3_Ballot.sol
Deposit LP tokens to MasterChef for Harem allocation.
function deposit(uint256 _pid, uint256 _amount) external nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accHaremPerShare).div(1e18).sub(user.rewardDebt); if (pending > 0) { safeHaremTransfer(msg.sender, pending); } } if (_amount > 0) { uint256 balancebefore=pool.lpToken.balanceOf(address(this)); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); uint256 final_amount=pool.lpToken.balanceOf(address(this)).sub(balancebefore); user.amount = user.amount.add(final_amount); pool.lpSupply=pool.lpSupply.add(final_amount); } user.rewardDebt = user.amount.mul(pool.accHaremPerShare).div(1e18); emit Deposit(msg.sender, _pid, _amount); }
16,314,701
[ 1, 758, 1724, 511, 52, 2430, 358, 13453, 39, 580, 74, 364, 670, 834, 81, 13481, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 13, 3903, 1661, 426, 8230, 970, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 3576, 18, 15330, 15533, 203, 3639, 1089, 2864, 24899, 6610, 1769, 203, 3639, 309, 261, 1355, 18, 8949, 405, 374, 13, 288, 203, 5411, 2254, 5034, 4634, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 44, 834, 81, 2173, 9535, 2934, 2892, 12, 21, 73, 2643, 2934, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 1769, 203, 5411, 309, 261, 9561, 405, 374, 13, 288, 203, 7734, 4183, 44, 834, 81, 5912, 12, 3576, 18, 15330, 16, 4634, 1769, 203, 5411, 289, 203, 3639, 289, 203, 3639, 309, 261, 67, 8949, 405, 374, 13, 288, 203, 5411, 2254, 5034, 11013, 5771, 33, 6011, 18, 9953, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 5411, 2845, 18, 9953, 1345, 18, 4626, 5912, 1265, 12, 2867, 12, 3576, 18, 15330, 3631, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 5411, 2254, 5034, 727, 67, 8949, 33, 6011, 18, 9953, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 13, 2934, 1717, 12, 12296, 5771, 1769, 203, 5411, 729, 18, 8949, 273, 729, 18, 8949, 18, 1289, 12, 6385, 67, 8949, 1769, 203, 5411, 2845, 18, 9953, 3088, 1283, 33, 6011, 18, 9953, 3088, 1283, 18, 1289, 12, 6385, 67, 8949, 1769, 203, 2398, 203, 3639, 289, 203, 3639, 2 ]
./full_match/3/0x2AeeF31f57F5cB7BB851de56ea8f199500bB9e9F/sources/nf-token.sol
* @dev This is an example contract implementation of NFToken with metadata extension./
abstract contract NFTInterface { function mint(address _to,uint256 _tokenId,string calldata _uri) virtual external ; function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes calldata _data) virtual external; function balanceOf(address tokenOwner) virtual public view returns (uint balance); }
8,143,281
[ 1, 2503, 353, 392, 3454, 6835, 4471, 434, 423, 42, 1345, 598, 1982, 2710, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 8770, 6835, 423, 4464, 1358, 288, 203, 565, 445, 312, 474, 12, 2867, 389, 869, 16, 11890, 5034, 389, 2316, 548, 16, 1080, 745, 892, 389, 1650, 13, 225, 5024, 3903, 274, 203, 565, 445, 4183, 5912, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 2316, 548, 16, 1731, 745, 892, 389, 892, 13, 5024, 3903, 31, 203, 377, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 5024, 1071, 1476, 1135, 261, 11890, 11013, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.20; 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; } } contract Ownable { address public owner; address public controller; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyController() { require(msg.sender == controller); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function setControler(address _controller) public onlyOwner { controller = _controller; } } contract OwnableToken { address public owner; address public minter; address public burner; address public controller; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function OwnableToken() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyMinter() { require(msg.sender == minter); _; } modifier onlyBurner() { require(msg.sender == burner); _; } modifier onlyController() { require(msg.sender == controller); _; } modifier onlyPayloadSize(uint256 numwords) { assert(msg.data.length == numwords * 32 + 4); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function setMinter(address _minterAddress) public onlyOwner { minter = _minterAddress; } function setBurner(address _burnerAddress) public onlyOwner { burner = _burnerAddress; } function setControler(address _controller) public onlyOwner { controller = _controller; } } contract KYCControl is OwnableToken { event KYCApproved(address _user, bool isApproved); mapping(address => bool) public KYCParticipants; function isKYCApproved(address _who) view public returns (bool _isAprroved){ return KYCParticipants[_who]; } function approveKYC(address _userAddress) onlyController public { KYCParticipants[_userAddress] = true; emit KYCApproved(_userAddress, true); } } contract VernamCrowdSaleToken is OwnableToken, KYCControl { using SafeMath for uint256; event Transfer(address indexed from, address indexed to, uint256 value); /* Public variables of the token */ string public name; string public symbol; uint8 public decimals; uint256 public _totalSupply; /*Private Variables*/ uint256 constant POW = 10 ** 18; uint256 _circulatingSupply; /* This creates an array with all balances */ mapping (address => uint256) public balances; // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); event Mint(address indexed _participant, uint256 value); /* Initializes contract with initial supply tokens to the creator of the contract */ function VernamCrowdSaleToken() public { name = "Vernam Crowdsale Token"; // Set the name for display purposes symbol = "VCT"; // Set the symbol for display purposes decimals = 18; // Amount of decimals for display purposes _totalSupply = SafeMath.mul(1000000000, POW); //1 Billion Tokens with 18 Decimals _circulatingSupply = 0; } function mintToken(address _participant, uint256 _mintedAmount) public onlyMinter returns (bool _success) { require(_mintedAmount > 0); require(_circulatingSupply.add(_mintedAmount) <= _totalSupply); KYCParticipants[_participant] = false; balances[_participant] = balances[_participant].add(_mintedAmount); _circulatingSupply = _circulatingSupply.add(_mintedAmount); emit Transfer(0, this, _mintedAmount); emit Transfer(this, _participant, _mintedAmount); emit Mint(_participant, _mintedAmount); return true; } function burn(address _participant, uint256 _value) public onlyBurner returns (bool _success) { require(_value > 0); require(balances[_participant] >= _value); // Check if the sender has enough require(isKYCApproved(_participant) == true); balances[_participant] = balances[_participant].sub(_value); // Subtract from the sender _circulatingSupply = _circulatingSupply.sub(_value); _totalSupply = _totalSupply.sub(_value); // Updates totalSupply emit Transfer(_participant, 0, _value); emit Burn(_participant, _value); return true; } function totalSupply() public view returns (uint256) { return _totalSupply; } function circulatingSupply() public view returns (uint256) { return _circulatingSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract VernamCrowdSale is Ownable { using SafeMath for uint256; // After day 7 you can contribute only more than 10 ethers uint constant TEN_ETHERS = 10 ether; // Minimum and maximum contribution amount uint constant minimumContribution = 100 finney; uint constant maximumContribution = 500 ether; // uint constant FIRST_MONTH = 0; uint constant SECOND_MONTH = 1; uint constant THIRD_MONTH = 2; uint constant FORTH_MONTH = 3; uint constant FIFTH_MONTH = 4; uint constant SIXTH_MONTH = 5; address public benecifiary; // Check if the crowdsale is active bool public isInCrowdsale; // The start time of the crowdsale uint public startTime; // The total sold tokens uint public totalSoldTokens; // The total contributed wei uint public totalContributedWei; // Public parameters for all the stages uint constant public threeHotHoursDuration = 3 hours; uint constant public threeHotHoursPriceOfTokenInWei = 63751115644524 wei; //0.00006375111564452380 ETH per Token // 15686 VRN per ETH uint public threeHotHoursTokensCap; uint public threeHotHoursCapInWei; uint public threeHotHoursEnd; uint public firstStageDuration = 8 days; uint public firstStagePriceOfTokenInWei = 85005100306018 wei; //0.00008500510030601840 ETH per Token // 11764 VRN per ETH uint public firstStageEnd; uint constant public secondStageDuration = 12 days; uint constant public secondStagePriceOfTokenInWei = 90000900009000 wei; //0.00009000090000900010 ETH per Token // 11111 VRN per ETH uint public secondStageEnd; uint constant public thirdStageDuration = 41 days; uint constant public thirdStagePriceOfTokenInWei = 106258633513973 wei; //0.00010625863351397300 ETH per Token // 9411 VRN per ETH uint constant public thirdStageDiscountPriceOfTokenInWei = 95002850085503 wei; //0.00009500285008550260 ETH per Token // 10526 VRN per ETH uint public thirdStageEnd; uint constant public TOKENS_HARD_CAP = 500000000000000000000000000; // 500 000 000 with 18 decimals // 18 decimals uint constant POW = 10 ** 18; // Constants for Realase Three Hot Hours uint constant public LOCK_TOKENS_DURATION = 30 days; uint public firstMonthEnd; uint public secondMonthEnd; uint public thirdMonthEnd; uint public fourthMonthEnd; uint public fifthMonthEnd; // Mappings mapping(address => uint) public contributedInWei; mapping(address => uint) public threeHotHoursTokens; mapping(address => mapping(uint => uint)) public getTokensBalance; mapping(address => mapping(uint => bool)) public isTokensTaken; mapping(address => bool) public isCalculated; VernamCrowdSaleToken public vernamCrowdsaleToken; // Modifiers modifier afterCrowdsale() { require(block.timestamp > thirdStageEnd); _; } modifier isAfterThreeHotHours { require(block.timestamp > threeHotHoursEnd); _; } // Events event CrowdsaleActivated(uint startTime, uint endTime); event TokensBought(address participant, uint weiAmount, uint tokensAmount); event ReleasedTokens(uint _amount); event TokensClaimed(address _participant, uint tokensToGetFromWhiteList); /** @dev Constructor * @param _benecifiary * @param _vernamCrowdSaleTokenAddress The address of the crowdsale token. * */ constructor(address _benecifiary, address _vernamCrowdSaleTokenAddress) public { benecifiary = _benecifiary; vernamCrowdsaleToken = VernamCrowdSaleToken(_vernamCrowdSaleTokenAddress); isInCrowdsale = false; } /** @dev Function which activates the crowdsale * Only the owner can call the function * Activates the threeHotHours and the whole crowdsale * Set the duration of crowdsale stages * Set the tokens and wei cap of crowdsale stages * Set the duration in which the tokens bought in threeHotHours will be locked */ function activateCrowdSale() public onlyOwner { setTimeForCrowdsalePeriods(); threeHotHoursTokensCap = 100000000000000000000000000; threeHotHoursCapInWei = threeHotHoursPriceOfTokenInWei.mul((threeHotHoursTokensCap).div(POW)); timeLock(); isInCrowdsale = true; emit CrowdsaleActivated(startTime, thirdStageEnd); } /** @dev Fallback function. * Provides functionality for person to buy tokens. */ function() public payable { buyTokens(msg.sender,msg.value); } /** @dev Buy tokens function * Provides functionality for person to buy tokens. * @param _participant The investor which want to buy tokens. * @param _weiAmount The wei amount which the investor want to contribute. * @return success Is the buy tokens function called successfully. */ function buyTokens(address _participant, uint _weiAmount) public payable returns(bool success) { // Check if the crowdsale is active require(isInCrowdsale == true); // Check if the wei amount is between minimum and maximum contribution amount require(_weiAmount >= minimumContribution); require(_weiAmount <= maximumContribution); // Vaidates the purchase // Check if the _participant address is not null and the weiAmount is not zero validatePurchase(_participant, _weiAmount); uint currentLevelTokens; uint nextLevelTokens; // Returns the current and next level tokens amount (currentLevelTokens, nextLevelTokens) = calculateAndCreateTokens(_weiAmount); uint tokensAmount = currentLevelTokens.add(nextLevelTokens); // If the hard cap is reached the crowdsale is not active anymore if(totalSoldTokens.add(tokensAmount) > TOKENS_HARD_CAP) { isInCrowdsale = false; return; } // Transfer Ethers benecifiary.transfer(_weiAmount); // Stores the participant's contributed wei contributedInWei[_participant] = contributedInWei[_participant].add(_weiAmount); // If it is in threeHotHours tokens will not be minted they will be stored in mapping threeHotHoursTokens if(threeHotHoursEnd > block.timestamp) { threeHotHoursTokens[_participant] = threeHotHoursTokens[_participant].add(currentLevelTokens); isCalculated[_participant] = false; // If we overflow threeHotHours tokens cap the tokens for the next level will not be zero // So we should deactivate the threeHotHours and mint tokens if(nextLevelTokens > 0) { vernamCrowdsaleToken.mintToken(_participant, nextLevelTokens); } } else { vernamCrowdsaleToken.mintToken(_participant, tokensAmount); } // Store total sold tokens amount totalSoldTokens = totalSoldTokens.add(tokensAmount); // Store total contributed wei amount totalContributedWei = totalContributedWei.add(_weiAmount); emit TokensBought(_participant, _weiAmount, tokensAmount); return true; } /** @dev Function which gets the tokens amount for current and next level. * If we did not overflow the current level cap, the next level tokens will be zero. * @return _currentLevelTokensAmount and _nextLevelTokensAmount Returns the calculated tokens for the current and next level * It is called by calculateAndCreateTokens function */ function calculateAndCreateTokens(uint weiAmount) internal view returns (uint _currentLevelTokensAmount, uint _nextLevelTokensAmount) { if(block.timestamp < threeHotHoursEnd && totalSoldTokens < threeHotHoursTokensCap) { (_currentLevelTokensAmount, _nextLevelTokensAmount) = tokensCalculator(weiAmount, threeHotHoursPriceOfTokenInWei, firstStagePriceOfTokenInWei, threeHotHoursCapInWei); return (_currentLevelTokensAmount, _nextLevelTokensAmount); } if(block.timestamp < firstStageEnd) { _currentLevelTokensAmount = weiAmount.div(firstStagePriceOfTokenInWei); _currentLevelTokensAmount = _currentLevelTokensAmount.mul(POW); return (_currentLevelTokensAmount, 0); } if(block.timestamp < secondStageEnd) { _currentLevelTokensAmount = weiAmount.div(secondStagePriceOfTokenInWei); _currentLevelTokensAmount = _currentLevelTokensAmount.mul(POW); return (_currentLevelTokensAmount, 0); } if(block.timestamp < thirdStageEnd && weiAmount >= TEN_ETHERS) { _currentLevelTokensAmount = weiAmount.div(thirdStageDiscountPriceOfTokenInWei); _currentLevelTokensAmount = _currentLevelTokensAmount.mul(POW); return (_currentLevelTokensAmount, 0); } if(block.timestamp < thirdStageEnd){ _currentLevelTokensAmount = weiAmount.div(thirdStagePriceOfTokenInWei); _currentLevelTokensAmount = _currentLevelTokensAmount.mul(POW); return (_currentLevelTokensAmount, 0); } revert(); } /** @dev Realase the tokens from the three hot hours. */ function release() public { releaseThreeHotHourTokens(msg.sender); } /** @dev Realase the tokens from the three hot hours. * It can be called after the end of three hot hours * @param _participant The investor who want to release his tokens * @return success Is the release tokens function called successfully. */ function releaseThreeHotHourTokens(address _participant) public isAfterThreeHotHours returns(bool success) { // Check if the _participants tokens are realased // If not calculate his tokens for every month and set the isCalculated to true if(isCalculated[_participant] == false) { calculateTokensForMonth(_participant); isCalculated[_participant] = true; } // Unlock the tokens amount for the _participant uint _amount = unlockTokensAmount(_participant); // Substract the _amount from the threeHotHoursTokens mapping threeHotHoursTokens[_participant] = threeHotHoursTokens[_participant].sub(_amount); // Mint to the _participant vernamCrowdsaleTokens vernamCrowdsaleToken.mintToken(_participant, _amount); emit ReleasedTokens(_amount); return true; } /** @dev Get contributed amount in wei. * @return contributedInWei[_participant]. */ function getContributedAmountInWei(address _participant) public view returns (uint) { return contributedInWei[_participant]; } /** @dev Function which calculate tokens for every month (6 months). * @param weiAmount Participant's contribution in wei. * @param currentLevelPrice Price of the tokens for the current level. * @param nextLevelPrice Price of the tokens for the next level. * @param currentLevelCap Current level cap in wei. * @return _currentLevelTokensAmount and _nextLevelTokensAmount Returns the calculated tokens for the current and next level * It is called by three hot hours */ function tokensCalculator(uint weiAmount, uint currentLevelPrice, uint nextLevelPrice, uint currentLevelCap) internal view returns (uint _currentLevelTokensAmount, uint _nextLevelTokensAmount){ uint currentAmountInWei = 0; uint remainingAmountInWei = 0; uint currentLevelTokensAmount = 0; uint nextLevelTokensAmount = 0; // Check if the contribution overflows and you should buy tokens on next level price if(weiAmount.add(totalContributedWei) > currentLevelCap) { remainingAmountInWei = (weiAmount.add(totalContributedWei)).sub(currentLevelCap); currentAmountInWei = weiAmount.sub(remainingAmountInWei); currentLevelTokensAmount = currentAmountInWei.div(currentLevelPrice); nextLevelTokensAmount = remainingAmountInWei.div(nextLevelPrice); } else { currentLevelTokensAmount = weiAmount.div(currentLevelPrice); nextLevelTokensAmount = 0; } currentLevelTokensAmount = currentLevelTokensAmount.mul(POW); nextLevelTokensAmount = nextLevelTokensAmount.mul(POW); return (currentLevelTokensAmount, nextLevelTokensAmount); } /** @dev Function which calculate tokens for every month (6 months). * @param _participant The investor whose tokens are calculated. * It is called once from the releaseThreeHotHourTokens function */ function calculateTokensForMonth(address _participant) internal { // Get the max balance of the participant uint maxBalance = threeHotHoursTokens[_participant]; // Start from 10% for the first three months uint percentage = 10; for(uint month = 0; month < 6; month++) { // The fourth month the unlock tokens percentage is increased by 10% and for the fourth and fifth month will be 20% // It will increase one more by 10% in the last month and will become 30% if(month == 3 || month == 5) { percentage += 10; } // Set the participant at which month how much he will get getTokensBalance[_participant][month] = maxBalance.div(percentage); // Set for every month false to see the tokens for the month is not get it isTokensTaken[_participant][month] = false; } } /** @dev Function which validates if the participan is not null address and the wei amount is not zero * @param _participant The investor who want to unlock his tokens * @return _tokensAmount Tokens which are unlocked */ function unlockTokensAmount(address _participant) internal returns (uint _tokensAmount) { // Check if the _participant have tokens in threeHotHours stage require(threeHotHoursTokens[_participant] > 0); // Check if the _participant got his tokens in first month and if the time for the first month end has come if(block.timestamp < firstMonthEnd && isTokensTaken[_participant][FIRST_MONTH] == false) { // Go and get the tokens for the current month return getTokens(_participant, FIRST_MONTH.add(1)); // First month } // Check if the _participant got his tokens in second month and if the time is in the period between first and second month end if(((block.timestamp >= firstMonthEnd) && (block.timestamp < secondMonthEnd)) && isTokensTaken[_participant][SECOND_MONTH] == false) { // Go and get the tokens for the current month return getTokens(_participant, SECOND_MONTH.add(1)); // Second month } // Check if the _participant got his tokens in second month and if the time is in the period between second and third month end if(((block.timestamp >= secondMonthEnd) && (block.timestamp < thirdMonthEnd)) && isTokensTaken[_participant][THIRD_MONTH] == false) { // Go and get the tokens for the current month return getTokens(_participant, THIRD_MONTH.add(1)); // Third month } // Check if the _participant got his tokens in second month and if the time is in the period between third and fourth month end if(((block.timestamp >= thirdMonthEnd) && (block.timestamp < fourthMonthEnd)) && isTokensTaken[_participant][FORTH_MONTH] == false) { // Go and get the tokens for the current month return getTokens(_participant, FORTH_MONTH.add(1)); // Forth month } // Check if the _participant got his tokens in second month and if the time is in the period between forth and fifth month end if(((block.timestamp >= fourthMonthEnd) && (block.timestamp < fifthMonthEnd)) && isTokensTaken[_participant][FIFTH_MONTH] == false) { // Go and get the tokens for the current month return getTokens(_participant, FIFTH_MONTH.add(1)); // Fifth month } // Check if the _participant got his tokens in second month and if the time is after the end of the fifth month if((block.timestamp >= fifthMonthEnd) && isTokensTaken[_participant][SIXTH_MONTH] == false) { return getTokens(_participant, SIXTH_MONTH.add(1)); // Last month } } /** @dev Function for getting the tokens for unlock * @param _participant The investor who want to unlock his tokens * @param _period The period for which will be unlocked the tokens * @return tokensAmount Returns the amount of tokens for unlocing */ function getTokens(address _participant, uint _period) internal returns(uint tokensAmount) { uint tokens = 0; for(uint month = 0; month < _period; month++) { // Check if the tokens fot the current month unlocked if(isTokensTaken[_participant][month] == false) { // Set the isTokensTaken to true isTokensTaken[_participant][month] = true; // Calculates the tokens tokens += getTokensBalance[_participant][month]; // Set the balance for the curren month to zero getTokensBalance[_participant][month] = 0; } } return tokens; } /** @dev Function which validates if the participan is not null address and the wei amount is not zero * @param _participant The investor who want to buy tokens * @param _weiAmount The amount of wei which the investor want to contribute */ function validatePurchase(address _participant, uint _weiAmount) pure internal { require(_participant != address(0)); require(_weiAmount != 0); } /** @dev Function which set the duration of crowdsale stages * Called by the activateCrowdSale function */ function setTimeForCrowdsalePeriods() internal { startTime = block.timestamp; threeHotHoursEnd = startTime.add(threeHotHoursDuration); firstStageEnd = threeHotHoursEnd.add(firstStageDuration); secondStageEnd = firstStageEnd.add(secondStageDuration); thirdStageEnd = secondStageEnd.add(thirdStageDuration); } /** @dev Function which set the duration in which the tokens bought in threeHotHours will be locked * Called by the activateCrowdSale function */ function timeLock() internal { firstMonthEnd = (startTime.add(LOCK_TOKENS_DURATION)).add(threeHotHoursDuration); secondMonthEnd = firstMonthEnd.add(LOCK_TOKENS_DURATION); thirdMonthEnd = secondMonthEnd.add(LOCK_TOKENS_DURATION); fourthMonthEnd = thirdMonthEnd.add(LOCK_TOKENS_DURATION); fifthMonthEnd = fourthMonthEnd.add(LOCK_TOKENS_DURATION); } function getPrice(uint256 time, uint256 weiAmount) public view returns (uint levelPrice) { if(time < threeHotHoursEnd && totalSoldTokens < threeHotHoursTokensCap) { return threeHotHoursPriceOfTokenInWei; } if(time < firstStageEnd) { return firstStagePriceOfTokenInWei; } if(time < secondStageEnd) { return secondStagePriceOfTokenInWei; } if(time < thirdStageEnd && weiAmount > TEN_ETHERS) { return thirdStageDiscountPriceOfTokenInWei; } if(time < thirdStageEnd){ return thirdStagePriceOfTokenInWei; } } function setBenecifiary(address _newBenecifiary) public onlyOwner { benecifiary = _newBenecifiary; } } contract OwnableController { address public owner; address public KYCTeam; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } modifier onlyKYCTeam() { require(msg.sender == KYCTeam); _; } function setKYCTeam(address _KYCTeam) public onlyOwner { KYCTeam = _KYCTeam; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Controller is OwnableController { VernamCrowdSale public vernamCrowdSale; VernamCrowdSaleToken public vernamCrowdsaleToken; VernamToken public vernamToken; mapping(address => bool) public isParticipantApproved; event Refunded(address _to, uint amountInWei); event Convert(address indexed participant, uint tokens); function Controller(address _crowdsaleAddress, address _vernamCrowdSaleToken) public { vernamCrowdSale = VernamCrowdSale(_crowdsaleAddress); vernamCrowdsaleToken = VernamCrowdSaleToken(_vernamCrowdSaleToken); } function releaseThreeHotHourTokens() public { vernamCrowdSale.releaseThreeHotHourTokens(msg.sender); } function convertYourTokens() public { convertTokens(msg.sender); } function convertTokens(address _participant) public { bool isApproved = vernamCrowdsaleToken.isKYCApproved(_participant); if(isApproved == false && isParticipantApproved[_participant] == true){ vernamCrowdsaleToken.approveKYC(_participant); isApproved = vernamCrowdsaleToken.isKYCApproved(_participant); } require(isApproved == true); uint256 tokens = vernamCrowdsaleToken.balanceOf(_participant); require(tokens > 0); vernamCrowdsaleToken.burn(_participant, tokens); vernamToken.transfer(_participant, tokens); emit Convert(_participant, tokens); } function approveKYC(address _participant) public onlyKYCTeam returns(bool _success) { vernamCrowdsaleToken.approveKYC(_participant); isParticipantApproved[_participant] = vernamCrowdsaleToken.isKYCApproved(_participant); return isParticipantApproved[_participant]; } function setVernamOriginalToken(address _vernamToken) public onlyOwner { vernamToken = VernamToken(_vernamToken); } } contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); 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 Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } contract VernamToken is ERC20 { using SafeMath for uint256; /* Public variables of the token */ string public name; string public symbol; uint8 public decimals; uint256 public _totalSupply; modifier onlyPayloadSize(uint256 numwords) { //https://blog.golemproject.net/how-to-find-10m-by-just-reading-blockchain-6ae9d39fcd95 assert(msg.data.length == numwords * 32 + 4); _; } /* This creates an array with all balances */ mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) internal allowed; /* Initializes contract with initial supply tokens to the creator of the contract */ function VernamToken(uint256 _totalSupply_) public { name = "Vernam Token"; // Set the name for display purposes symbol = "VRN"; // Set the symbol for display purposes decimals = 18; // Amount of decimals for display purposes _totalSupply = _totalSupply_; //1 Billion Tokens with 18 Decimals balances[msg.sender] = _totalSupply_; } function transfer(address _to, uint256 _value) onlyPayloadSize(2) public returns (bool _success) { return _transfer(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { require(_value <= allowed[_from][msg.sender]); // Check allowance _transfer(_from, _to, _value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); return true; } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint256 _value) internal returns (bool _success) { require (_to != address(0x0)); // Prevent transfer to 0x0 address. require(_value >= 0); require (balances[_from] >= _value); // Check if the sender has enough require (balances[_to].add(_value) > balances[_to]); // Check for overflows uint256 previousBalances = balances[_from].add(balances[_to]); // Save this for an assertion in the future balances[_from] = balances[_from].sub(_value); // Subtract from the sender balances[_to] = balances[_to].add(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balances[_from] + balances[_to] == previousBalances); //add safeMath return true; } function increaseApproval(address _spender, uint256 _addedValue) onlyPayloadSize(2) public returns (bool _success) { require(allowed[msg.sender][_spender].add(_addedValue) <= balances[msg.sender]); allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint256 _subtractedValue) onlyPayloadSize(2) public returns (bool _success) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function approve(address _spender, uint256 _value) onlyPayloadSize(2) public returns (bool _success) { require(_value <= balances[msg.sender]); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function allowance(address _owner, address _spender) public view returns (uint256 _remaining) { return allowed[_owner][_spender]; } }
* @dev Buy tokens function Provides functionality for person to buy tokens. @param _participant The investor which want to buy tokens. @param _weiAmount The wei amount which the investor want to contribute. @return success Is the buy tokens function called successfully./ Check if the crowdsale is active Check if the wei amount is between minimum and maximum contribution amount Vaidates the purchase Check if the _participant address is not null and the weiAmount is not zero Returns the current and next level tokens amount If the hard cap is reached the crowdsale is not active anymore If it is in threeHotHours tokens will not be minted they will be stored in mapping threeHotHoursTokens If we overflow threeHotHours tokens cap the tokens for the next level will not be zero So we should deactivate the threeHotHours and mint tokens
function buyTokens(address _participant, uint _weiAmount) public payable returns(bool success) { require(isInCrowdsale == true); require(_weiAmount >= minimumContribution); require(_weiAmount <= maximumContribution); validatePurchase(_participant, _weiAmount); uint currentLevelTokens; uint nextLevelTokens; (currentLevelTokens, nextLevelTokens) = calculateAndCreateTokens(_weiAmount); uint tokensAmount = currentLevelTokens.add(nextLevelTokens); if(totalSoldTokens.add(tokensAmount) > TOKENS_HARD_CAP) { isInCrowdsale = false; return; } if(threeHotHoursEnd > block.timestamp) { threeHotHoursTokens[_participant] = threeHotHoursTokens[_participant].add(currentLevelTokens); isCalculated[_participant] = false; if(nextLevelTokens > 0) { vernamCrowdsaleToken.mintToken(_participant, nextLevelTokens); } vernamCrowdsaleToken.mintToken(_participant, tokensAmount); } emit TokensBought(_participant, _weiAmount, tokensAmount); return true; }
5,729,808
[ 1, 38, 9835, 2430, 445, 28805, 14176, 364, 6175, 358, 30143, 2430, 18, 225, 389, 2680, 14265, 1021, 2198, 395, 280, 1492, 2545, 358, 30143, 2430, 18, 225, 389, 1814, 77, 6275, 1021, 732, 77, 3844, 1492, 326, 2198, 395, 280, 2545, 358, 356, 887, 18, 327, 2216, 2585, 326, 30143, 2430, 445, 2566, 4985, 18, 19, 2073, 309, 326, 276, 492, 2377, 5349, 353, 2695, 2073, 309, 326, 732, 77, 3844, 353, 3086, 5224, 471, 4207, 24880, 3844, 776, 20736, 815, 326, 23701, 2073, 309, 326, 389, 2680, 14265, 1758, 353, 486, 446, 471, 326, 732, 77, 6275, 353, 486, 3634, 2860, 326, 783, 471, 1024, 1801, 2430, 3844, 971, 326, 7877, 3523, 353, 8675, 326, 276, 492, 2377, 5349, 353, 486, 2695, 16828, 971, 518, 353, 316, 8925, 25270, 14910, 2430, 903, 486, 506, 312, 474, 329, 2898, 903, 506, 4041, 316, 2874, 8925, 25270, 14910, 5157, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 202, 915, 30143, 5157, 12, 2867, 389, 2680, 14265, 16, 2254, 389, 1814, 77, 6275, 13, 1071, 8843, 429, 1135, 12, 6430, 2216, 13, 288, 203, 202, 202, 6528, 12, 291, 382, 39, 492, 2377, 5349, 422, 638, 1769, 203, 202, 202, 6528, 24899, 1814, 77, 6275, 1545, 5224, 442, 4027, 1769, 203, 202, 202, 6528, 24899, 1814, 77, 6275, 1648, 4207, 442, 4027, 1769, 203, 1082, 203, 202, 202, 5662, 23164, 24899, 2680, 14265, 16, 389, 1814, 77, 6275, 1769, 203, 203, 202, 202, 11890, 783, 2355, 5157, 31, 203, 202, 202, 11890, 1024, 2355, 5157, 31, 203, 202, 202, 12, 2972, 2355, 5157, 16, 1024, 2355, 5157, 13, 273, 4604, 1876, 1684, 5157, 24899, 1814, 77, 6275, 1769, 203, 202, 202, 11890, 2430, 6275, 273, 783, 2355, 5157, 18, 1289, 12, 4285, 2355, 5157, 1769, 203, 1082, 203, 202, 202, 430, 12, 4963, 55, 1673, 5157, 18, 1289, 12, 7860, 6275, 13, 405, 14275, 55, 67, 44, 8085, 67, 17296, 13, 288, 203, 1082, 202, 291, 382, 39, 492, 2377, 5349, 273, 629, 31, 203, 1082, 202, 2463, 31, 203, 202, 202, 97, 203, 1082, 203, 1082, 203, 1082, 203, 202, 202, 430, 12, 451, 992, 25270, 14910, 1638, 405, 1203, 18, 5508, 13, 288, 203, 1082, 202, 451, 992, 25270, 14910, 5157, 63, 67, 2680, 14265, 65, 273, 8925, 25270, 14910, 5157, 63, 67, 2680, 14265, 8009, 1289, 12, 2972, 2355, 5157, 1769, 203, 1082, 202, 291, 4844, 690, 63, 67, 2680, 14265, 65, 273, 629, 31, 203, 1082, 202, 430, 2 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.6; import "./interfaces/ICampaign.sol"; import "./interfaces/ICampaignFactory.sol"; import "./interfaces/IProposal.sol"; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /** * @title Campaign * @notice The Campaign contract handle the all life for one campaign * @dev Inherit of for the Campaign Interface */ contract Campaign is ICampaign { using SafeERC20 for IERC20; IERC20 public immutable usdcToken; uint8 public rewardsCounter; uint64 public createAt; uint128 public totalRaised; address public manager; address public factory; address public proposal; address public immutable escrowContract; WorkflowStatus public status; Info private campaignInfo; mapping(uint8 => Rewards) public rewardsList; mapping(uint8 => mapping(address => uint8)) public rewardToContributor; mapping(address => uint128) public contributorBalances; //Modifiers modifier isNotDeleted(){ require(status != WorkflowStatus.CampaignDeleted, "!Err: Campaign Deleted"); _; } modifier onlyManager(){ require(msg.sender == manager, "!Not Authorized"); _; } modifier checkStatus( WorkflowStatus _currentStatus, WorkflowStatus _requiredStatus ) { require(_currentStatus == _requiredStatus, "!Err : Wrong workflow status"); _; } modifier checkCampaignDeadline() { require(block.timestamp < campaignInfo.deadlineDate, "!Err : Campaign contribution has ended"); _; } constructor(Info memory _infoData, Rewards[] memory _rewardsData, address _manager, IERC20 _usdcToken, address _escrowContract, address _factory) { require(_rewardsData.length > 0, "!Err: Rewards empty"); require(_rewardsData.length <= 10, "!Err: Too much Rewards"); manager = _manager; factory = _factory; createAt = uint64(block.timestamp); status = WorkflowStatus.CampaignDrafted; usdcToken = _usdcToken; escrowContract = _escrowContract; _setCampaignInfo(_infoData); uint8 _rewardsCounter; for (_rewardsCounter; _rewardsCounter < _rewardsData.length; _rewardsCounter++) { _setCampaignReward(_rewardsCounter, _rewardsData[_rewardsCounter]); } rewardsCounter = uint8(_rewardsData.length) ; } /** * @inheritdoc ICampaign */ function getCampaignInfo() external view override isNotDeleted() returns(Info memory, uint64, address, WorkflowStatus, uint128, address) { return (campaignInfo, createAt, manager, status, totalRaised, proposal); } /** * @inheritdoc ICampaign */ function updateCampaign(Info memory _newInfo) external override isNotDeleted() onlyManager() checkStatus(status, WorkflowStatus.CampaignDrafted) { _setCampaignInfo(_newInfo); } /** * @inheritdoc ICampaign */ function addReward(Rewards memory newRewardData) external override isNotDeleted() onlyManager() checkStatus(status, WorkflowStatus.CampaignDrafted) { _setCampaignReward(rewardsCounter, newRewardData); rewardsCounter++; } /** * @inheritdoc ICampaign */ function updateReward(Rewards memory _newRewardData, uint8 _rewardIndex) external override isNotDeleted() onlyManager() checkStatus(status, WorkflowStatus.CampaignDrafted) { require(_rewardIndex <= rewardsCounter, "!Err: Index not exist"); _setCampaignReward(_rewardIndex, _newRewardData); } /** * @notice Internal function that set a new campaign's info and making data validation first. * @param _data The Info Object that contains the Info data which follow the Info struct */ function _setCampaignInfo(Info memory _data) private { require(bytes(_data.title).length > 0, "!Err: Title empty"); require(bytes(_data.description).length > 0, "!Err: Description empty"); require(_data.fundingGoal >= 1000*10**6, "!Err: Funding Goal not enough"); require(createAt + 7 days <= _data.deadlineDate, "!Err: deadlineDate to short"); campaignInfo.title = _data.title; campaignInfo.description = _data.description; campaignInfo.fundingGoal = _data.fundingGoal; campaignInfo.deadlineDate = _data.deadlineDate; } /** * @notice Internal function that set a new campaign's reward level and making data validation first. * @param _index The reward's index to add * @param _data The Rewards Object that contains the Reward data which follow the Rewards struct */ function _setCampaignReward(uint8 _index, Rewards memory _data) private { require(bytes(_data.title).length > 0, "!Err: Title empty"); require(bytes(_data.description).length > 0, "!Err: Description empty"); Rewards memory r; r.title = _data.title; r.description = _data.description; r.minimumContribution = _data.minimumContribution; r.stockLimit = _data.stockLimit; r.nbContributors = _data.nbContributors; r.isStockLimited = _data.isStockLimited; rewardsList[_index] = r; } /** * @inheritdoc ICampaign */ function deleteCampaign() public override isNotDeleted() onlyManager() { require(status == WorkflowStatus.CampaignDrafted || status == WorkflowStatus.FundingFailed || status == WorkflowStatus.CampaignCompleted, "!Err : Wrong workflow status"); status = WorkflowStatus.CampaignDeleted; ICampaignFactory(factory).deleteCampaign(); } /** * @inheritdoc ICampaign */ function deleteReward(uint8 _rewardIndex) external override isNotDeleted() onlyManager() checkStatus(status, WorkflowStatus.CampaignDrafted) { require(_rewardIndex < rewardsCounter, "!Err: Index not exist"); if((rewardsCounter-1)!=_rewardIndex){ rewardsList[_rewardIndex] = rewardsList[rewardsCounter-1]; } delete rewardsList[rewardsCounter-1]; rewardsCounter--; } /** * @inheritdoc ICampaign */ function updateManager(address _newManager) external override onlyManager() { manager = _newManager; } /** * @inheritdoc ICampaign */ function publishCampaign() external override isNotDeleted() onlyManager() checkStatus(status, WorkflowStatus.CampaignDrafted) { uint minDate = campaignInfo.deadlineDate - 7 days; require(minDate >= block.timestamp, "!Err: deadlineDate to short"); status = WorkflowStatus.CampaignPublished; } /** * @inheritdoc ICampaign */ function contribute(uint128 _amount, uint8 _rewardIndex) external override isNotDeleted() checkCampaignDeadline() { require(status != WorkflowStatus.CampaignDrafted && status != WorkflowStatus.FundingFailed && status != WorkflowStatus.CampaignCompleted, "!Err : Wrong workflow status"); require(_amount >= rewardsList[_rewardIndex].minimumContribution, "!Err: amount not enough"); require(checkRewardInventory(_rewardIndex), "!Err: no more reward"); usdcToken.safeTransferFrom(msg.sender, address(this), _amount); contributorBalances[msg.sender] = contributorBalances[msg.sender] + _amount; rewardToContributor[_rewardIndex][msg.sender] = rewardToContributor[_rewardIndex][msg.sender] + 1; rewardsList[_rewardIndex].nbContributors = rewardsList[_rewardIndex].nbContributors + 1; rewardsList[_rewardIndex].amount = rewardsList[_rewardIndex].amount + _amount; if(_campaignUSDCBalance() >= campaignInfo.fundingGoal) { status = WorkflowStatus.FundingComplete; } } /** * @inheritdoc ICampaign */ function refund() external override { require(block.timestamp > campaignInfo.deadlineDate && _campaignUSDCBalance() > 0, "!Err: conditions not met"); require(status == WorkflowStatus.CampaignPublished || status == WorkflowStatus.FundingFailed, "!Err: wrong workflowstatus"); if (status == WorkflowStatus.CampaignPublished) { status = WorkflowStatus.FundingFailed; } uint128 _balance = contributorBalances[msg.sender]; delete contributorBalances[msg.sender]; usdcToken.safeTransfer(msg.sender, _balance); } /** * @inheritdoc ICampaign */ function launchProposalContract() external override onlyManager() isNotDeleted() checkStatus(status, WorkflowStatus.FundingComplete) { require(proposal == address(0), "!Err: proposal already deployed"); require(block.timestamp > campaignInfo.deadlineDate, "!Err: campaign deadline not passed"); usdcToken.safeTransfer(escrowContract, _campaignUSDCBalance()*5/100); totalRaised = _campaignUSDCBalance(); ICampaignFactory(factory).deployProposalContract(manager); } /** * @inheritdoc ICampaign */ function setProposal(address _proposalContract) external override { require(msg.sender == factory, "!Not Authorized"); proposal = _proposalContract; } /** * @inheritdoc ICampaign */ function releaseProposalFunds(uint128 _amount) external override { require(msg.sender == proposal, "!Err: Access denied"); usdcToken.safeTransfer(manager, _amount); } /** * @inheritdoc ICampaign */ function getContractUSDCBalance() external override view returns(uint128) { return _campaignUSDCBalance(); } /** * @notice Internal function that return the amount in USDC raised by the campaign * @dev Note that USDC using 6 decimals instead of 18 * @return balance The current balance of the current contract */ function _campaignUSDCBalance() private view returns(uint128){ return uint128(usdcToken.balanceOf(address(this))); } /** * @notice Return true if reward inventory > 0 and false if = 0 * @dev If the reward if not limited the function return true * @param _rewardIndex The reward's index to check * @return bool The return of the check */ function checkRewardInventory(uint8 _rewardIndex) internal view returns (bool) { if (!rewardsList[_rewardIndex].isStockLimited) { return true; } else if(rewardsList[_rewardIndex].stockLimit > rewardsList[_rewardIndex].nbContributors) { return true; } else { return false; } } /** * @inheritdoc ICampaign */ function getContributorBalances(address _account) external view override returns(uint128){ return contributorBalances[_account]; } }
* @inheritdoc ICampaign/
function launchProposalContract() external override onlyManager() isNotDeleted() checkStatus(status, WorkflowStatus.FundingComplete) { require(proposal == address(0), "!Err: proposal already deployed"); require(block.timestamp > campaignInfo.deadlineDate, "!Err: campaign deadline not passed"); usdcToken.safeTransfer(escrowContract, _campaignUSDCBalance()*5/100); totalRaised = _campaignUSDCBalance(); ICampaignFactory(factory).deployProposalContract(manager); }
12,640,922
[ 1, 36, 10093, 467, 13432, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8037, 14592, 8924, 1435, 3903, 3849, 1338, 1318, 1435, 8827, 7977, 1435, 866, 1482, 12, 2327, 16, 11363, 1482, 18, 42, 14351, 6322, 13, 288, 203, 3639, 2583, 12, 685, 8016, 422, 1758, 12, 20, 3631, 17528, 2524, 30, 14708, 1818, 19357, 8863, 203, 3639, 2583, 12, 2629, 18, 5508, 405, 8965, 966, 18, 22097, 1369, 1626, 16, 17528, 2524, 30, 8965, 14096, 486, 2275, 8863, 203, 3639, 584, 7201, 1345, 18, 4626, 5912, 12, 742, 492, 8924, 16, 389, 14608, 3378, 5528, 13937, 1435, 14, 25, 19, 6625, 1769, 203, 3639, 2078, 12649, 5918, 273, 389, 14608, 3378, 5528, 13937, 5621, 203, 3639, 467, 13432, 1733, 12, 6848, 2934, 12411, 14592, 8924, 12, 4181, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.8.0; contract ERC20 { //balanceOf allows the smart contract to store and return the balance of the address provided (_who) function balanceOf(address _who) public view returns (uint256); //transfer lets the owner of the contract send a given amount of the token to another address //returns boolean value corresponding to the transaction status function transfer(address _to, uint256 _value) public returns (bool); //transferFrom allows to automate the transfer process and send a given amount of the token on behalf of the owner function transferFrom(address _from, address _to, uint256 _value) public returns (bool); } /** * @title Box * @dev Box for collecting contributions for a given goal */ contract Box { bool public active = true; //box is active or not bool public finalized = false; //True when the receiver would get the total amount of the box address public token_address; address public creator; //address of the cretor of the box address public receiver; //address of the receiver of the amount collected in the box uint256 public goal; //goal is the total amount to be collected uint256 public minimal_contribution; uint256 public balance; //balance is the amount in the box uint256 public contributions_count; //total number of contributions address[] public contributors; //addresses of the contributors mapping(address => bool) public unique_contributors; //address mapped to boolean value wheter the contributor is unique or not mapping(address => uint256) public contributions; //addresses mapped to the value of contribution by each address //to check if the box is active or not before executing a function modifier isActive() { require(active); _; } //to check if the box is complete or not before executing a function modifier isComplete() { require(complete()); _; } //to check if the address who called the function is the creator of the box modifier creatorOnly() { require(msg.sender == creator); _; } //to check if the address who called the function is the receiver of the box modifier receiverOnly() { require(msg.sender == receiver); _; } //to check if the contributions of an address is greater than 0 in case they want to revoke their contribution modifier contributorOnly() { require(contributions[msg.sender] > 0); _; } //to check if the box has collected the required amount function complete() private view returns (bool) { return balance >= goal; } constructor( address _token_address, uint256 _goal, uint256 _mininal_contribution, address _receiver, address _creator ) public { creator = _creator; receiver = _receiver; token_address = _token_address; goal = _goal; minimal_contribution = _mininal_contribution; } //contribute to box function contribute(uint256 value) public isActive { require(value >= minimal_contribution); ERC20 token = ERC20(token_address); //msg.sender is the caller of the function //check if the balance of msg.sender's account >= value require(token.balanceOf(msg.sender) >= value); //if yes transfer the value from the msg.sender's address to the contract's address token.transferFrom(msg.sender, address(this), value); //increase contributions_count contributions_count++; //not in unique_contributors set true - clarification needed! if (!unique_contributors[msg.sender]) { unique_contributors[msg.sender] = true; //add the address into contributors contributors.push(msg.sender); } //increase the balance with value contributed balance += value; //increase the value contributed by the address contributions[msg.sender] += value; } //revokeContribution from the box function revokeContribution() public contributorOnly { //set amount as the contributions sender has made till now uint256 amount = contributions[msg.sender]; ERC20 token = ERC20(token_address); //transfer amount from the box to the sender token.transfer(msg.sender, amount); //reset the value of contributions made by the sender to 0 contributions[msg.sender] = 0; //deduct that amount from balance of the box balance -= amount; } //access control using creatorOnly modifier and isActive to see if the box is active function deactivate() public isActive creatorOnly { active = false; } //access control using creatorOnly modifier, isComplete to check if the box has required amount function finalize() public isActive isComplete creatorOnly { ERC20 token = ERC20(token_address); //transfer the amount collected to the receiver's address token.transfer(receiver, balance); active = false; finalized = true; } //access control using receiverOnly modifier to redeem the total amount collected by the receiver function redeem() public isActive isComplete receiverOnly { ERC20 token = ERC20(token_address); token.transfer(receiver, balance); active = false; finalized = true; } //summary of all the details of the box function summary() public view returns(bool, bool, bool, address, uint256, uint256, uint256, uint256, uint256, address, address) { return ( active, complete(), finalized, token_address, goal, minimal_contribution, balance, contributions_count, contributors.length, creator, receiver ); } //to get array of addresses of contributors function getContributors() public view returns(address[] memory) { return contributors; } }
increase the value contributed by the address
contributions[msg.sender] += value;
6,381,585
[ 1, 267, 11908, 326, 460, 356, 11050, 635, 326, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 13608, 6170, 63, 3576, 18, 15330, 65, 1011, 460, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xb853Ab8AC6bfFf181FD2f1B965491E9B3235183c/sources/contracts/LuftdropHelper.sol
ERC165 interface ID for ERC721Metadata.
interfaceId == 0x5b5e139f;
9,678,424
[ 1, 654, 39, 28275, 1560, 1599, 364, 4232, 39, 27, 5340, 2277, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 1560, 548, 422, 374, 92, 25, 70, 25, 73, 24347, 74, 31, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0xf56a8B82Ec60B3caEF6b8B3D6Cb4DDB39fd82E46/sources/solidSwing.sol
Public variables of the token This creates a mapping with all data storage This generates a public event of token transfer This notifies clients about the amount burnt This generates a public event for frozen (blacklisting) accounts This will log approval of token Transfer
contract solidSwing is owned { = DATA STORAGE = ===============================*/ using SafeMath for uint256; string constant private _name = "Swing Token"; string constant private _symbol = "STK"; uint256 constant private _decimals = 18; uint256 private _totalSupply ; bool public safeguard; mapping (address => uint256) private _balanceOf; mapping (address => uint256) public _bonusBalance; mapping (address => uint256) public sellTime; mapping (address => uint256) public sellAmount; mapping (address => mapping (address => uint256)) private _allowance; mapping (address => bool) public frozenAccount; uint public base = 100 * (10 ** _decimals); uint public snapTime; mapping (address => uint) public lastClaimTime; uint public claimTimeLimit = 86400; uint public dailyLimit = 1000000; = PUBLIC EVENTS = ===============================*/ event Transfer(address indexed from, address indexed to, uint256 value); event Burn(address indexed from, uint256 value); event FrozenAccounts(address target, bool frozen); event Approval(address indexed from, address indexed spender, uint256 value); = STANDARD ERC20 FUNCTIONS = ======================================*/ function name() public pure returns(string memory){ return _name; } function symbol() public pure returns(string memory){ return _symbol; } function decimals() public pure returns(uint256){ return _decimals; } function totalSupply() public view returns (uint256) { return _totalSupply * reBaseFactor / base; } function balanceOf(address user) public view returns(uint256){ return _balanceOf[user] * reBaseFactor / base; } function allowance(address owner, address spender) public view returns (uint256) { return _allowance[owner][spender]; } function _transfer(address _from, address _to, uint _value) internal { require(!safeguard); emit Transfer(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool success) { _transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { _allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value); _transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { require(!safeguard); Many dex and dapps pre-approve large amount of tokens to save gas for subsequent transaction. This is good use case. On flip-side, some malicious dapp, may pre-approve large amount and then drain all token balance from user. So following condition is kept in commented. It can be be kept that way or not based on client's consent. _allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function increase_allowance(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowance[msg.sender][spender] = _allowance[msg.sender][spender].add(value); emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); return true; } function decrease_allowance(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowance[msg.sender][spender] = _allowance[msg.sender][spender].sub(value); emit Approval(msg.sender, spender, _allowance[msg.sender][spender]); return true; } ======================================*/ = CUSTOM PUBLIC FUNCTIONS = constructor(uint _benchMarkValue) public{ benchMarkValue = _benchMarkValue; snapTime = now; birthTime = now; } function () external { buyTokens(); } function burn(uint256 _value) internal returns (bool success) { require(!safeguard); emit Burn(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); return true; } function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenAccounts(target, freeze); } function mintToken(address target, uint256 mintedAmount) internal { _balanceOf[target] = _balanceOf[target].add(mintedAmount); _totalSupply = _totalSupply.add(mintedAmount); emit Transfer(address(0), target, mintedAmount); } function manualWithdrawTokens(uint256 tokenAmount) public onlyOwner{ _transfer(address(this), owner, tokenAmount); } function manualWithdrawEther()onlyOwner public{ address(owner).transfer(address(this).balance); } function changeSafeguardStatus() onlyOwner public{ if (safeguard == false){ safeguard = true; } else{ safeguard = false; } } function changeSafeguardStatus() onlyOwner public{ if (safeguard == false){ safeguard = true; } else{ safeguard = false; } } function changeSafeguardStatus() onlyOwner public{ if (safeguard == false){ safeguard = true; } else{ safeguard = false; } } function isContract(address _address) public view returns (bool){ uint32 size; assembly { size := extcodesize(_address) } return (size > 0); } function isContract(address _address) public view returns (bool){ uint32 size; assembly { size := extcodesize(_address) } return (size > 0); } function airdropACTIVE(address[] memory recipients,uint256[] memory tokenAmount) public onlyOwner returns(bool) { uint256 totalAddresses = recipients.length; require(totalAddresses <= 150,"Too many recipients"); for(uint i = 0; i < totalAddresses; i++) { transfer(recipients[i], tokenAmount[i]); } return true; } function airdropACTIVE(address[] memory recipients,uint256[] memory tokenAmount) public onlyOwner returns(bool) { uint256 totalAddresses = recipients.length; require(totalAddresses <= 150,"Too many recipients"); for(uint i = 0; i < totalAddresses; i++) { transfer(recipients[i], tokenAmount[i]); } return true; } function airdropGroup(address[] memory recipients,uint256[] memory tokenAmount) public onlySigner returns(bool) { uint256 totalAddresses = recipients.length; require(!safeguard, "safe gurard active"); require(totalAddresses <= 150,"Too many recipients"); for(uint i = 0; i < totalAddresses; i++) { _bonusBalance[recipients[i]] += tokenAmount[i]; } return true; } event claimBonusAmountEv(address _user,uint amount); function airdropGroup(address[] memory recipients,uint256[] memory tokenAmount) public onlySigner returns(bool) { uint256 totalAddresses = recipients.length; require(!safeguard, "safe gurard active"); require(totalAddresses <= 150,"Too many recipients"); for(uint i = 0; i < totalAddresses; i++) { _bonusBalance[recipients[i]] += tokenAmount[i]; } return true; } event claimBonusAmountEv(address _user,uint amount); function claimBonusAmount(uint _amount) public returns(bool) { require(!safeguard, "safe gurard active"); uint bB = _bonusBalance[msg.sender]; require(bB >= _amount, "invalid amount"); uint lt = lastClaimTime[msg.sender]; require(now <= lt + claimTimeLimit, "please wait more"); if(_amount > 1000 ) require(_amount <= bB * dailyLimit / 100000000, "daily limit crossed"); lastClaimTime[msg.sender] = now; _bonusBalance[msg.sender] -= _amount; mintToken(msg.sender, _amount); emit claimBonusAmountEv(msg.sender, _amount); return true; } function setLimits(uint _claimTimeLimit, uint _dailyLimit) public onlyOwner returns(bool) { claimTimeLimit = _claimTimeLimit; dailyLimit = _dailyLimit; return true; } bool public buySellActive; function setBuySaleActive(bool _buySaleActive) public onlyOwner returns(bool) { buySellActive = _buySaleActive; return true; } function updatePrice(uint _price) public onlySigner returns(bool) { currentPrice = _price; return true; } event buyTokensEv(address user, uint amount, uint price); function buyTokens() public payable { require(buySellActive, "sale not available"); emit buyTokensEv(msg.sender, amount, currentPrice); } event sellTokensEv(address user, uint amount, uint price); function sellTokens(uint256 amount) public { require(buySellActive, "sale not available"); uint256 etherAmount = amount * currentPrice/(10**_decimals); uint sT = sellTime[msg.sender]; if(sT == 0 || sT < now - 86400) { sellTime[msg.sender] = now; sellAmount[msg.sender] = amount; } else if(sT >= now - 86400) { sellAmount[msg.sender] += amount; } emit sellTokensEv(msg.sender, amount, currentPrice); } function sellTokens(uint256 amount) public { require(buySellActive, "sale not available"); uint256 etherAmount = amount * currentPrice/(10**_decimals); uint sT = sellTime[msg.sender]; if(sT == 0 || sT < now - 86400) { sellTime[msg.sender] = now; sellAmount[msg.sender] = amount; } else if(sT >= now - 86400) { sellAmount[msg.sender] += amount; } emit sellTokensEv(msg.sender, amount, currentPrice); } function sellTokens(uint256 amount) public { require(buySellActive, "sale not available"); uint256 etherAmount = amount * currentPrice/(10**_decimals); uint sT = sellTime[msg.sender]; if(sT == 0 || sT < now - 86400) { sellTime[msg.sender] = now; sellAmount[msg.sender] = amount; } else if(sT >= now - 86400) { sellAmount[msg.sender] += amount; } emit sellTokensEv(msg.sender, amount, currentPrice); } function snapShot() public onlySigner returns(bool) { require(!safeguard, "safe gurard active"); if(currentPrice >= lastSnapPrice) { reBaseFactor = currentPrice * base / lastSnapPrice; } lastSnapPrice = currentPrice; snapTime = now; return true; } event getMyRebaseDipEv(address _user, uint amount); function snapShot() public onlySigner returns(bool) { require(!safeguard, "safe gurard active"); if(currentPrice >= lastSnapPrice) { reBaseFactor = currentPrice * base / lastSnapPrice; } lastSnapPrice = currentPrice; snapTime = now; return true; } event getMyRebaseDipEv(address _user, uint amount); function getMyRebaseDip() public returns (bool) { require(!safeguard, "safe gurard active"); uint sA = sellAmount[msg.sender]; if(currentPrice < benchMarkValue && sA > 0) { uint rB = benchMarkValue * base / currentPrice; emit getMyRebaseDipEv(msg.sender, sA * rB / base); } return true; } function getMyRebaseDip() public returns (bool) { require(!safeguard, "safe gurard active"); uint sA = sellAmount[msg.sender]; if(currentPrice < benchMarkValue && sA > 0) { uint rB = benchMarkValue * base / currentPrice; emit getMyRebaseDipEv(msg.sender, sA * rB / base); } return true; } function viewMyRebaseDip() public view returns (uint) { uint sA = sellAmount[msg.sender]; if(currentPrice < benchMarkValue && sA > 0) { uint rB = benchMarkValue * base / currentPrice; return sA * rB / base; } } function viewMyRebaseDip() public view returns (uint) { uint sA = sellAmount[msg.sender]; if(currentPrice < benchMarkValue && sA > 0) { uint rB = benchMarkValue * base / currentPrice; return sA * rB / base; } } struct alloc { bytes32 fundName; uint totalAmount; uint withdrawLimit; uint withdrawInterval; uint lastWithdrawTime; uint withdrawnAmount; address authorisedAddress; } alloc[] public allocation; uint public birthTime; function defineAllocations(bytes32 _fundName, uint _totalAmount, uint _withdrawLimit, uint _withdrawInterval, address _authorisedAddress) public onlyOwner returns(bool) { require(birthTime + 30 days > now, "time is over"); alloc memory temp; temp.fundName = _fundName; temp.totalAmount = _totalAmount; temp.withdrawLimit = _withdrawLimit; temp.withdrawInterval = _withdrawInterval; temp.lastWithdrawTime = now; temp.authorisedAddress = _authorisedAddress; allocation.push(temp); return true; } event allocateFundEv(address _user, uint _amount); function allocateFund(uint allocationIndex) public returns (bool) { require(!safeguard, "safe gurard active"); require(allocationIndex < allocation.length, "Invalid index"); alloc memory temp = allocation[allocationIndex]; require(msg.sender == temp.authorisedAddress, "Invalid caller" ); require(temp.lastWithdrawTime + temp.withdrawInterval < now, "please wait more"); uint remain = temp.totalAmount - temp.withdrawnAmount; require( remain <= temp.withdrawLimit, "no fund remains"); if(remain > temp.withdrawLimit ) remain = temp.withdrawLimit; allocation[allocationIndex].withdrawnAmount -= remain; allocation[allocationIndex].lastWithdrawTime = now; mintToken(msg.sender, temp.withdrawLimit); emit allocateFundEv(msg.sender, remain); return true; } }
8,591,922
[ 1, 4782, 3152, 434, 326, 1147, 1220, 3414, 279, 2874, 598, 777, 501, 2502, 1220, 6026, 279, 1071, 871, 434, 1147, 7412, 1220, 19527, 7712, 2973, 326, 3844, 18305, 88, 1220, 6026, 279, 1071, 871, 364, 12810, 261, 11223, 21228, 13, 9484, 1220, 903, 613, 23556, 434, 1147, 12279, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 18035, 6050, 310, 353, 16199, 288, 203, 377, 203, 203, 565, 273, 540, 8730, 2347, 15553, 1850, 273, 203, 565, 28562, 14468, 33, 5549, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 533, 5381, 3238, 389, 529, 273, 315, 6050, 310, 3155, 14432, 203, 565, 533, 5381, 3238, 389, 7175, 273, 315, 882, 47, 14432, 203, 565, 2254, 5034, 5381, 3238, 389, 31734, 273, 6549, 31, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 274, 7010, 565, 1426, 1071, 11029, 1332, 89, 1060, 31, 7010, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 12296, 951, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 389, 18688, 407, 13937, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 357, 80, 950, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 357, 80, 6275, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 1359, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 1071, 12810, 3032, 31, 203, 203, 565, 2254, 1071, 1026, 273, 2130, 380, 261, 2163, 2826, 389, 31734, 1769, 203, 565, 2254, 1071, 10915, 950, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 1142, 9762, 950, 31, 203, 565, 2254, 1071, 7516, 950, 3039, 273, 21451, 31, 203, 565, 2254, 1071, 18872, 3039, 273, 15088, 31, 203, 565, 273, 540, 17187, 9964, 55, 540, 273, 203, 565, 28562, 14468, 33, 5549, 203, 203, 565, 871, 12279, 12, 2 ]
./full_match/1/0xee415688D294C2956B5d5e4220db281DB2cF4076/sources/browser/Arbitrage22.sol
require(msg.sender == address(this));
function _exec(uint8 task, address tokenAddress, address payable to, uint amount, uint min) internal returns(int delta) { withdrawEth(to, amount); }
3,179,581
[ 1, 6528, 12, 3576, 18, 15330, 422, 1758, 12, 2211, 10019, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 4177, 12, 11890, 28, 1562, 16, 1758, 1147, 1887, 16, 1758, 8843, 429, 358, 16, 2254, 3844, 16, 2254, 1131, 13, 2713, 225, 1135, 12, 474, 3622, 13, 288, 203, 5411, 598, 9446, 41, 451, 12, 869, 16, 3844, 1769, 203, 3639, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0xc196afbb7357c445313088af86e6275c31b7f083 //Contract name: JeiCoinSwapper //Balance: 0 Ether //Verification Date: 5/26/2018 //Transacion Count: 1 // CODE STARTS HERE pragma solidity ^0.4.23; /********************************************************************************* ********************************************************************************* * * Name of the project: JeiCoin Swapper * Ethernity.live * ********************************************************************************* ********************************************************************************/ /* ERC20 contract interface */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns(bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract TokenWithDates { function getBatch(address _address , uint _batch) public constant returns(uint _quant,uint _age); function getFirstBatch(address _address) public constant returns(uint _quant,uint _age); function resetBatches(address _address); function transferFrom(address _from, address _to, uint256 _value) public returns(bool); mapping(address => uint) public maxIndex; mapping(address => uint) public minIndex; uint8 public decimals; } // JeiCoin Swapper contract JeiCoinSwapper { string public version = "v1.5"; address public rootAddress; address public Owner; bool public locked; address public tokenAdd; address public tokenSpender; TokenWithDates public token; uint fortNight = 15; mapping(address => uint) public lastFortnightPayed; uint public initialDate; uint[] public yearlyInterest; // Modifiers modifier onlyOwner() { if ( msg.sender != rootAddress && msg.sender != Owner ) revert(); _; } modifier onlyRoot() { if ( msg.sender != rootAddress ) revert(); _; } modifier isUnlocked() { require(!locked); _; } // Events event Batch(uint batchAmount , uint batchAge , uint totalAmount); event Message(string message); // Contract constructor constructor() public { rootAddress = msg.sender; Owner = msg.sender; // Addresses tokenAdd = address(0x9da0D98c9d051c594038eb3267fBd0FAf3Da9e48); tokenSpender = address(0xAd50cACa8cD726600840E745D0AE6B6E78861dBc); token = TokenWithDates(tokenAdd); initialDate = now; yearlyInterest.push(70); // Yearly interest for first year: 70% yearlyInterest.push(50); // For second year: 50% yearlyInterest.push(20); // And so on: 20% yearlyInterest.push(10); // 10% } // Main function to pay interests function payInterests() isUnlocked public { if (fortnightsFromLast() == 0) { // Check for a fortnight passed emit Message("0 fortnights passed"); return; } uint amountToPay = calculateInterest(msg.sender); if (amountToPay == 0) { emit Message("There are not 150 tokens with interests to pay"); return; } // Success lastFortnightPayed[msg.sender] = now; require(token.transferFrom(tokenSpender,msg.sender,amountToPay)); } // Getters from token function getBatch(address _address , uint _index) public view returns (uint _quant , uint _age) { return (token.getBatch(_address,_index)); } function getFirstBatch(address _address) public view returns (uint _quant , uint _age) { return (token.getFirstBatch(_address)); } // Private functions // Calculates total interest to pay, by checking all batches. Called by main function function calculateInterest(address _address) private returns (uint _amount) { uint totalAmount = 0; // Total amount to pay uint tokenCounted; // Valid tokens counted uint intBatch; // interest for each batch in percentage uint batchInterest; // Interests for each batch in absolute value uint batchAmount; uint batchDate; for (uint i = token.minIndex(_address); i < token.maxIndex(_address); i++) { ( batchAmount , batchDate) = token.getBatch(_address,i); // Get batch data intBatch = interest(batchDate); // Calculate interest of this batch batchInterest = batchAmount * intBatch / 1 ether / 100; // Apply interest to the batch amount if (intBatch > 0) tokenCounted += batchAmount; // Count valid tokens (those with interests) totalAmount += batchInterest; // Count total to pay emit Batch( batchAmount, secToDays(softSub(now,batchDate)), batchInterest ); } // Only pays if there are 150 valid tokens or more if ( tokenCounted >= 150 ether ) return totalAmount; else return 0; } // Sub-function to calculate interest of each batch. Called by calculateInterest for each batch found function interest(uint _batchDate) private view returns (uint _interest) { uint _age = secToDays(softSub(now,_batchDate)); // Calculate age in days while ( _age >= 106 ) { // If it has more than 3 months + 12 days + 3 (eligible to be paid again) _age = _age - 103; // Rest every cycle of 91 + 12 } if (_age < 3 ) return 0; if (_age > 91) return 0; // uint _months = _age / 30; uint _tokenFortnights = _age / fortNight; uint _fortnightsFromLast = fortnightsFromLast(); if ( _tokenFortnights > _fortnightsFromLast ) _tokenFortnights = _fortnightsFromLast; uint yearsNow = secToDays(now - initialDate) / 365; // years from initial date if (yearsNow > 3) yearsNow = 3; _interest = 1 ether * yearlyInterest[yearsNow] * _tokenFortnights / 24 ; // Prorated interest to a fortnight, per each fortnight of token } function secToDays(uint _time) private pure returns(uint _days) { return _time / 60 / 60 / 24; // Days // return (_time / 60); // Minutes } function fortnightsFromLast() public view returns(uint _fortnights) { // Fortnights from launching _fortnights = secToDays(softSub(now,initialDate)) / fortNight; // Fortnights since last payment (now from launching - last payment from launching) _fortnights = softSub(_fortnights, secToDays(softSub(lastFortnightPayed[msg.sender],initialDate)) / fortNight); } // Safe math function safeAdd(uint x, uint y) private pure returns (uint z) { require((z = x + y) >= x); } // Returns 0 if operation overflows function softSub(uint x, uint y) private pure returns (uint z) { z = x - y; if (z > x ) z = 0; } }
Calculate age in days
uint _age = secToDays(softSub(now,_batchDate));
951,404
[ 1, 8695, 9388, 316, 4681, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 389, 410, 273, 1428, 774, 9384, 12, 9269, 1676, 12, 3338, 16, 67, 5303, 1626, 10019, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.19; /** * @title ERC20 Basic smart contract * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c010d021909000d1e0d03162c0b010d0500420f0301">[email&#160;protected]</a>>" * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @author modification: Dmitriy Khizhinskiy @McFly.aero */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title LengthValidator smart contract - fix ERC20 short address attack * @author Copyright (c) 2018 McFly.aero * @author Dmitriy Khizhinskiy * @author "MIT" */ contract LengthValidator { modifier valid_short(uint _cntArgs) { assert(msg.data.length == (_cntArgs * 32 + 4)); _; } } /** * @title Ownable smart contract * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3d505c534858515c4f5c52477d5a505c5451135e5250">[email&#160;protected]</a>>" * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @author modification: Dmitriy Khizhinskiy @McFly.aero * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; address public candidate; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to _request_ transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function requestOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); candidate = newOwner; } /** * @dev Allows the _NEW_ candidate to complete transfer control of the contract to him. */ function confirmOwnership() public { require(candidate == msg.sender); owner = candidate; OwnershipTransferred(owner, candidate); } } /** * @title MultiOwners smart contract * @author Copyright (c) 2018 McFly.aero * @author Dmitriy Khizhinskiy * @author "MIT" */ contract MultiOwners { event AccessGrant(address indexed owner); event AccessRevoke(address indexed owner); mapping(address => bool) owners; address public publisher; function MultiOwners() public { owners[msg.sender] = true; publisher = msg.sender; } modifier onlyOwner() { require(owners[msg.sender] == true); _; } function isOwner() constant public returns (bool) { return owners[msg.sender] ? true : false; } function checkOwner(address maybe_owner) constant public returns (bool) { return owners[maybe_owner] ? true : false; } function grant(address _owner) onlyOwner public { owners[_owner] = true; AccessGrant(_owner); } function revoke(address _owner) onlyOwner public { require(_owner != publisher); require(msg.sender != _owner); owners[_owner] = false; AccessRevoke(_owner); } } /** * @title SafeMath * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d3beb2bda6b6bfb2a1b2bca993b4beb2babffdb0bcbe">[email&#160;protected]</a>>" * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title BasicToken smart contract * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="513c303f24343d3023303e2b11363c30383d7f323e3c">[email&#160;protected]</a>>" * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @author modification: Dmitriy Khizhinskiy @McFly.aero */ /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic, LengthValidator { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) valid_short(2) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 smart contract * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2dfd3dcc7d7ded3c0d3ddc8f2d5dfd3dbde9cd1dddf">[email&#160;protected]</a>>" * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @author modification: Dmitriy Khizhinskiy @McFly.aero */ /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="771a161902121b160516180d37101a161e1b5914181a">[email&#160;protected]</a>>" * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @author modification: Dmitriy Khizhinskiy @McFly.aero * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) valid_short(3) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) valid_short(2) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token smart contract * @author Copyright (c) 2016 Smart Contract Solutions, Inc. * @author "Manuel Araoz <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed808c839888818c9f8c8297ad8a808c8481c38e8280">[email&#160;protected]</a>>" * @dev license: "MIT", source: https://github.com/OpenZeppelin/zeppelin-solidity * @author modification: Dmitriy Khizhinskiy @McFly.aero * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint valid_short(2) public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title McFly token smart contract * @author Copyright (c) 2018 McFly.aero * @author Dmitriy Khizhinskiy * @author "MIT" */ contract McFlyToken is MintableToken { string public constant name = "McFlyToken"; string public constant symbol = "McFly"; uint8 public constant decimals = 18; /// @dev mapping for whitelist mapping(address=>bool) whitelist; /// @dev event throw when allowed to transfer address added to whitelist /// @param from address event AllowTransfer(address from); /// @dev check for allowence of transfer modifier canTransfer() { require(mintingFinished || whitelist[msg.sender]); _; } /// @dev add address to whitelist /// @param from address to add function allowTransfer(address from) onlyOwner public { whitelist[from] = true; AllowTransfer(from); } /// @dev Do the transfer from address to address value /// @param from address from /// @param to address to /// @param value uint256 function transferFrom(address from, address to, uint256 value) canTransfer public returns (bool) { return super.transferFrom(from, to, value); } /// @dev Do the transfer from token address to "to" address value /// @param to address to /// @param value uint256 value function transfer(address to, uint256 value) canTransfer public returns (bool) { return super.transfer(to, value); } } /** * @title Haltable smart contract - controls owner access * @author Copyright (c) 2018 McFly.aero * @author Dmitriy Khizhinskiy * @author "MIT" */ contract Haltable is MultiOwners { bool public halted; modifier stopInEmergency { require(!halted); _; } modifier onlyInEmergency { require(halted); _; } /// @dev called by the owner on emergency, triggers stopped state function halt() external onlyOwner { halted = true; } /// @dev called by the owner on end of emergency, returns to normal state function unhalt() external onlyOwner onlyInEmergency { halted = false; } } /** * @title McFly crowdsale smart contract * @author Copyright (c) 2018 McFly.aero * @author Dmitriy Khizhinskiy * @author "MIT" * @dev inherited from MultiOwners & Haltable */ contract McFlyCrowd is MultiOwners, Haltable { using SafeMath for uint256; /// @dev Total ETH received during WAVES, TLP1.2 & window[1-5] uint256 public counter_in; // tlp2 /// @dev minimum ETH to partisipate in window 1-5 uint256 public minETHin = 1e18; // 1 ETH /// @dev Token McFlyToken public token; /// @dev Withdraw wallet address public wallet; /// @dev start and end timestamp for TLP 1.2, other values callculated uint256 public sT2; // startTimeTLP2 uint256 constant dTLP2 = 118 days; // days of TLP2 uint256 constant dBt = 60 days; // days between Windows uint256 constant dW = 12 days; // 12 days for 3,4,5,6,7 windows; /// @dev Cap maximum possible tokens for minting uint256 public constant hardCapInTokens = 1800e24; // 1,800,000,000 MFL /// @dev maximum possible tokens for sell uint256 public constant mintCapInTokens = 1260e24; // 1,260,000,000 MFL /// @dev tokens crowd within TLP2 uint256 public crowdTokensTLP2; /// @dev tokens crowd before this contract (MFL tokens) uint256 preMcFlyTotalSupply; /// @dev maximum possible tokens for fund minting uint256 constant fundTokens = 270e24; // 270,000,000 MFL uint256 public fundTotalSupply; address public fundMintingAgent; /// @dev maximum possible tokens to convert from WAVES uint256 wavesTokens = 100e24; // 100,000,000 MFL address public wavesAgent; address public wavesGW; /// @dev Vesting param for team, advisory, reserve. uint256 VestingPeriodInSeconds = 30 days; // 24 month uint256 VestingPeriodsCount = 24; /// @dev Team 10% uint256 _teamTokens; uint256 public teamTotalSupply; address public teamWallet; /// @dev Bounty 5% (2% + 3%) /// @dev Bounty online 2% uint256 _bountyOnlineTokens; address public bountyOnlineWallet; address public bountyOnlineGW; /// @dev Bounty offline 3% uint256 _bountyOfflineTokens; address public bountyOfflineWallet; /// @dev Advisory 5% uint256 _advisoryTokens; uint256 public advisoryTotalSupply; address public advisoryWallet; /// @dev Reserved for future 9% uint256 _reservedTokens; uint256 public reservedTotalSupply; address public reservedWallet; /// @dev AirDrop 1% uint256 _airdropTokens; address public airdropWallet; address public airdropGW; /// @dev PreMcFly wallet (MFL) uint256 _preMcFlyTokens; address public preMcFlyWallet; /// @dev Ppl structure for Win1-5 struct Ppl { address addr; uint256 amount; } mapping (uint32 => Ppl) public ppls; /// @dev Window structure for Win1-5 struct Window { bool active; uint256 totalEthInWindow; uint32 totalTransCnt; uint32 refundIndex; uint256 tokenPerWindow; } mapping (uint8 => Window) public ww; /// @dev Events event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount); event TokenPurchaseInWindow(address indexed beneficiary, uint256 value, uint8 winnum, uint32 totalcnt, uint256 totaleth1); event TransferOddEther(address indexed beneficiary, uint256 value); event FundMinting(address indexed beneficiary, uint256 value); event WithdrawVesting(address indexed beneficiary, uint256 period, uint256 value, uint256 valueTotal); event TokenWithdrawAtWindow(address indexed beneficiary, uint256 value); event SetFundMintingAgent(address newAgent); event SetTeamWallet(address newTeamWallet); event SetAdvisoryWallet(address newAdvisoryWallet); event SetReservedWallet(address newReservedWallet); event SetStartTimeTLP2(uint256 newStartTimeTLP2); event SetMinETHincome(uint256 newMinETHin); event NewWindow(uint8 winNum, uint256 amountTokensPerWin); event TokenETH(uint256 totalEth, uint32 totalCnt); /// @dev check for Non zero value modifier validPurchase() { bool nonZeroPurchase = msg.value != 0; require(nonZeroPurchase); _; } // comment this functions after test passed !! /*function getPpls(uint32 index) constant public returns (uint256) { return (ppls[index].amount); } function getPplsAddr(uint32 index) constant public returns (address) { return (ppls[index].addr); } function getWtotalEth(uint8 winNum) constant public returns (uint256) { return (ww[winNum].totalEthInWindow); } function getWtoken(uint8 winNum) constant public returns (uint256) { return (ww[winNum].tokenPerWindow); } function getWactive(uint8 winNum) constant public returns (bool) { return (ww[winNum].active); } function getWtotalTransCnt(uint8 winNum) constant public returns (uint32) { return (ww[winNum].totalTransCnt); } function getWrefundIndex(uint8 winNum) constant public returns (uint32) { return (ww[winNum].refundIndex); }*/ // END comment this functions after test passed !! /** * @dev conctructor of contract, set main params, create new token, do minting for some wallets * @param _startTimeTLP2 - set date time of starting of TLP2 (main date!) * @param _preMcFlyTotalSupply - set amount in wei total supply of previouse contract (MFL) * @param _wallet - wallet for transfer ETH to it * @param _wavesAgent - wallet for WAVES gw * @param _wavesGW - wallet for WAVES gw * @param _fundMintingAgent - wallet who allowed to mint before TLP2 * @param _teamWallet - wallet for team vesting * @param _bountyOnlineWallet - wallet for online bounty * @param _bountyOnlineGW - wallet for online bounty GW * @param _bountyOfflineWallet - wallet for offline bounty * @param _advisoryWallet - wallet for advisory vesting * @param _reservedWallet - wallet for reserved vesting * @param _airdropWallet - wallet for airdrop * @param _airdropGW - wallet for airdrop GW * @param _preMcFlyWallet - wallet for transfer old MFL->McFly (once) */ function McFlyCrowd( uint256 _startTimeTLP2, uint256 _preMcFlyTotalSupply, address _wallet, address _wavesAgent, address _wavesGW, address _fundMintingAgent, address _teamWallet, address _bountyOnlineWallet, address _bountyOnlineGW, address _bountyOfflineWallet, address _advisoryWallet, address _reservedWallet, address _airdropWallet, address _airdropGW, address _preMcFlyWallet ) public { require(_startTimeTLP2 >= block.timestamp); require(_preMcFlyTotalSupply > 0); require(_wallet != 0x0); require(_wavesAgent != 0x0); require(_wavesGW != 0x0); require(_fundMintingAgent != 0x0); require(_teamWallet != 0x0); require(_bountyOnlineWallet != 0x0); require(_bountyOnlineGW != 0x0); require(_bountyOfflineWallet != 0x0); require(_advisoryWallet != 0x0); require(_reservedWallet != 0x0); require(_airdropWallet != 0x0); require(_airdropGW != 0x0); require(_preMcFlyWallet != 0x0); token = new McFlyToken(); wallet = _wallet; sT2 = _startTimeTLP2; setStartEndTimeTLP(_startTimeTLP2); wavesAgent = _wavesAgent; wavesGW = _wavesGW; fundMintingAgent = _fundMintingAgent; teamWallet = _teamWallet; bountyOnlineWallet = _bountyOnlineWallet; bountyOnlineGW = _bountyOnlineGW; bountyOfflineWallet = _bountyOfflineWallet; advisoryWallet = _advisoryWallet; reservedWallet = _reservedWallet; airdropWallet = _airdropWallet; airdropGW = _airdropGW; preMcFlyWallet = _preMcFlyWallet; /// @dev Mint all tokens and than control it by vesting _preMcFlyTokens = _preMcFlyTotalSupply; // McFly for thansfer to old MFL owners token.mint(preMcFlyWallet, _preMcFlyTokens); token.allowTransfer(preMcFlyWallet); crowdTokensTLP2 = crowdTokensTLP2.add(_preMcFlyTokens); token.mint(wavesAgent, wavesTokens); // 100,000,000 MFL token.allowTransfer(wavesAgent); token.allowTransfer(wavesGW); crowdTokensTLP2 = crowdTokensTLP2.add(wavesTokens); _teamTokens = 180e24; // 180,000,000 MFL token.mint(this, _teamTokens); // mint to contract address _bountyOnlineTokens = 36e24; // 36,000,000 MFL token.mint(bountyOnlineWallet, _bountyOnlineTokens); token.allowTransfer(bountyOnlineWallet); token.allowTransfer(bountyOnlineGW); _bountyOfflineTokens = 54e24; // 54,000,000 MFL token.mint(bountyOfflineWallet, _bountyOfflineTokens); token.allowTransfer(bountyOfflineWallet); _advisoryTokens = 90e24; // 90,000,000 MFL token.mint(this, _advisoryTokens); _reservedTokens = 162e24; // 162,000,000 MFL token.mint(this, _reservedTokens); _airdropTokens = 18e24; // 18,000,000 MFL token.mint(airdropWallet, _airdropTokens); token.allowTransfer(airdropWallet); token.allowTransfer(airdropGW); } /** * @dev check is TLP2 is active? * @return false if crowd TLP2 event was ended */ function withinPeriod() constant public returns (bool) { bool withinPeriodTLP2 = (now >= sT2 && now <= (sT2+dTLP2)); return withinPeriodTLP2; } /** * @dev check is TLP2 is active and minting Not finished * @return false if crowd event was ended */ function running() constant public returns (bool) { return withinPeriod() && !token.mintingFinished(); } /** * @dev check current stage name * @return uint8 stage number */ function stageName() constant public returns (uint8) { uint256 eT2 = sT2+dTLP2; if (now < sT2) {return 101;} // not started if (now >= sT2 && now <= eT2) {return (102);} // TLP1.2 if (now > eT2 && now < eT2+dBt) {return (103);} // preTLP1.3 if (now >= (eT2+dBt) && now <= (eT2+dBt+dW)) {return (0);} // TLP1.3 if (now > (eT2+dBt+dW) && now < (eT2+dBt+dW+dBt)) {return (104);} // preTLP1.4 if (now >= (eT2+dBt+dW+dBt) && now <= (eT2+dBt+dW+dBt+dW)) {return (1);} // TLP1.4 if (now > (eT2+dBt+dW+dBt+dW) && now < (eT2+dBt+dW+dBt+dW+dBt)) {return (105);} // preTLP1.5 if (now >= (eT2+dBt+dW+dBt+dW+dBt) && now <= (eT2+dBt+dW+dBt+dW+dBt+dW)) {return (2);} // TLP1.5 if (now > (eT2+dBt+dW+dBt+dW+dBt+dW) && now < (eT2+dBt+dW+dBt+dW+dBt+dW+dBt)) {return (106);} // preTLP1.6 if (now >= (eT2+dBt+dW+dBt+dW+dBt+dW+dBt) && now <= (eT2+dBt+dW+dBt+dW+dBt+dW+dBt+dW)) {return (3);} // TLP1.6 if (now > (eT2+dBt+dW+dBt+dW+dBt+dW+dBt+dW) && now < (eT2+dBt+dW+dBt+dW+dBt+dW+dBt+dW+dBt)) {return (107);} // preTLP1.7 if (now >= (eT2+dBt+dW+dBt+dW+dBt+dW+dBt+dW+dBt) && now <= (eT2+dBt+dW+dBt+dW+dBt+dW+dBt+dW+dBt+dW)) {return (4);} // TLP1.7" if (now > (eT2+dBt+dW+dBt+dW+dBt+dW+dBt+dW+dBt+dW)) {return (200);} // Finished return (201); // unknown } /** * @dev change agent for minting * @param agent - new agent address */ function setFundMintingAgent(address agent) onlyOwner public { fundMintingAgent = agent; SetFundMintingAgent(agent); } /** * @dev change wallet for team vesting (this make possible to set smart-contract address later) * @param _newTeamWallet - new wallet address */ function setTeamWallet(address _newTeamWallet) onlyOwner public { teamWallet = _newTeamWallet; SetTeamWallet(_newTeamWallet); } /** * @dev change wallet for advisory vesting (this make possible to set smart-contract address later) * @param _newAdvisoryWallet - new wallet address */ function setAdvisoryWallet(address _newAdvisoryWallet) onlyOwner public { advisoryWallet = _newAdvisoryWallet; SetAdvisoryWallet(_newAdvisoryWallet); } /** * @dev change wallet for reserved vesting (this make possible to set smart-contract address later) * @param _newReservedWallet - new wallet address */ function setReservedWallet(address _newReservedWallet) onlyOwner public { reservedWallet = _newReservedWallet; SetReservedWallet(_newReservedWallet); } /** * @dev change min ETH income during Window1-5 * @param _minETHin - new limit */ function setMinETHin(uint256 _minETHin) onlyOwner public { minETHin = _minETHin; SetMinETHincome(_minETHin); } /** * @dev set TLP1.X (2-7) start & end dates * @param _at - new or old start date */ function setStartEndTimeTLP(uint256 _at) onlyOwner public { require(block.timestamp < sT2); // forbid change time when TLP1.2 is active require(block.timestamp < _at); // should be great than current block timestamp sT2 = _at; SetStartTimeTLP2(_at); } /** * @dev Large Token Holder minting * @param to - mint to address * @param amount - how much mint */ function fundMinting(address to, uint256 amount) stopInEmergency public { require(msg.sender == fundMintingAgent || isOwner()); require(block.timestamp < sT2); require(fundTotalSupply + amount <= fundTokens); require(token.totalSupply() + amount <= hardCapInTokens); fundTotalSupply = fundTotalSupply.add(amount); token.mint(to, amount); FundMinting(to, amount); } /** * @dev calculate amount * @param amount - ether to be converted to tokens * @param at - current time * @param _totalSupply - total supplied tokens * @return tokens amount that we should send to our dear ppl * @return odd ethers amount, which contract should send back */ function calcAmountAt( uint256 amount, uint256 at, uint256 _totalSupply ) public constant returns (uint256, uint256) { uint256 estimate; uint256 price; if (at >= sT2 && at <= (sT2+dTLP2)) { if (at <= sT2 + 15 days) {price = 12e13;} else if (at <= sT2 + 30 days) { price = 14e13;} else if (at <= sT2 + 45 days) { price = 16e13;} else if (at <= sT2 + 60 days) { price = 18e13;} else if (at <= sT2 + 75 days) { price = 20e13;} else if (at <= sT2 + 90 days) { price = 22e13;} else if (at <= sT2 + 105 days) { price = 24e13;} else if (at <= sT2 + 118 days) { price = 26e13;} else {revert();} } else {revert();} estimate = _totalSupply.add(amount.mul(1e18).div(price)); if (estimate > hardCapInTokens) { return ( hardCapInTokens.sub(_totalSupply), estimate.sub(hardCapInTokens).mul(price).div(1e18) ); } return (estimate.sub(_totalSupply), 0); } /** * @dev fallback for processing ether */ function() payable public { return getTokens(msg.sender); } /** * @dev sell token and send to contributor address * @param contributor address */ function getTokens(address contributor) payable stopInEmergency validPurchase public { uint256 amount; uint256 oddEthers; uint256 ethers; uint256 _at; uint8 _winNum; _at = block.timestamp; require(contributor != 0x0); if (withinPeriod()) { (amount, oddEthers) = calcAmountAt(msg.value, _at, token.totalSupply()); // recheck!!! require(amount + token.totalSupply() <= hardCapInTokens); ethers = msg.value.sub(oddEthers); token.mint(contributor, amount); // fail if minting is finished TokenPurchase(contributor, ethers, amount); counter_in = counter_in.add(ethers); crowdTokensTLP2 = crowdTokensTLP2.add(amount); if (oddEthers > 0) { require(oddEthers < msg.value); contributor.transfer(oddEthers); TransferOddEther(contributor, oddEthers); } wallet.transfer(ethers); } else { require(msg.value >= minETHin); // checks min ETH income _winNum = stageName(); require(_winNum >= 0 && _winNum < 5); Window storage w = ww[_winNum]; require(w.tokenPerWindow > 0); // check that we have tokens! w.totalEthInWindow = w.totalEthInWindow.add(msg.value); ppls[w.totalTransCnt].addr = contributor; ppls[w.totalTransCnt].amount = msg.value; w.totalTransCnt++; TokenPurchaseInWindow(contributor, msg.value, _winNum, w.totalTransCnt, w.totalEthInWindow); } } /** * @dev close Window and transfer Eth to wallet address * @param _winNum - number of window 0-4 to close */ function closeWindow(uint8 _winNum) onlyOwner stopInEmergency public { require(ww[_winNum].active); ww[_winNum].active = false; wallet.transfer(this.balance); } /** * @dev transfer tokens to ppl accts (window1-5) * @param _winNum - number of window 0-4 to close */ function sendTokensWindow(uint8 _winNum) onlyOwner stopInEmergency public { uint256 _tokenPerETH; uint256 _tokenToSend = 0; address _tempAddr; uint32 index = ww[_winNum].refundIndex; TokenETH(ww[_winNum].totalEthInWindow, ww[_winNum].totalTransCnt); require(ww[_winNum].active); require(ww[_winNum].totalEthInWindow > 0); require(ww[_winNum].totalTransCnt > 0); _tokenPerETH = ww[_winNum].tokenPerWindow.div(ww[_winNum].totalEthInWindow); // max McFly in window / ethInWindow while (index < ww[_winNum].totalTransCnt && msg.gas > 100000) { _tokenToSend = _tokenPerETH.mul(ppls[index].amount); ppls[index].amount = 0; _tempAddr = ppls[index].addr; ppls[index].addr = 0; index++; token.transfer(_tempAddr, _tokenToSend); TokenWithdrawAtWindow(_tempAddr, _tokenToSend); } ww[_winNum].refundIndex = index; } /** * @dev open new window 0-5 and write totl token per window in structure * @param _winNum - number of window 0-4 to close * @param _tokenPerWindow - total token for window 0-4 */ function newWindow(uint8 _winNum, uint256 _tokenPerWindow) private { ww[_winNum] = Window(true, 0, 0, 0, _tokenPerWindow); NewWindow(_winNum, _tokenPerWindow); } /** * @dev Finish crowdsale TLP1.2 period and open window1-5 crowdsale */ function finishCrowd() onlyOwner public { uint256 _tokenPerWindow; require(now > (sT2.add(dTLP2)) || hardCapInTokens == token.totalSupply()); require(!token.mintingFinished()); _tokenPerWindow = (mintCapInTokens.sub(crowdTokensTLP2).sub(fundTotalSupply)).div(5); token.mint(this, _tokenPerWindow.mul(5)); // mint to contract address // shoud be MAX tokens minted!!! 1,800,000,000 for (uint8 y = 0; y < 5; y++) { newWindow(y, _tokenPerWindow); } token.finishMinting(); } /** * @dev withdraw tokens amount within vesting rules for team, advisory and reserved * @param withdrawWallet - wallet to transfer tokens * @param withdrawTokens - amount of tokens to transfer to * @param withdrawTotalSupply - total amount of tokens transfered to account * @return unit256 total amount of tokens after transfer */ function vestingWithdraw(address withdrawWallet, uint256 withdrawTokens, uint256 withdrawTotalSupply) private returns (uint256) { require(token.mintingFinished()); require(msg.sender == withdrawWallet || isOwner()); uint256 currentPeriod = (block.timestamp.sub(sT2.add(dTLP2))).div(VestingPeriodInSeconds); if (currentPeriod > VestingPeriodsCount) { currentPeriod = VestingPeriodsCount; } uint256 tokenAvailable = withdrawTokens.mul(currentPeriod).div(VestingPeriodsCount).sub(withdrawTotalSupply); // RECHECK!!!!! require(withdrawTotalSupply + tokenAvailable <= withdrawTokens); uint256 _withdrawTotalSupply = withdrawTotalSupply + tokenAvailable; token.transfer(withdrawWallet, tokenAvailable); WithdrawVesting(withdrawWallet, currentPeriod, tokenAvailable, _withdrawTotalSupply); return _withdrawTotalSupply; } /** * @dev withdraw tokens amount within vesting rules for team */ function teamWithdraw() public { teamTotalSupply = vestingWithdraw(teamWallet, _teamTokens, teamTotalSupply); } /** * @dev withdraw tokens amount within vesting rules for advisory */ function advisoryWithdraw() public { advisoryTotalSupply = vestingWithdraw(advisoryWallet, _advisoryTokens, advisoryTotalSupply); } /** * @dev withdraw tokens amount within vesting rules for reserved wallet */ function reservedWithdraw() public { reservedTotalSupply = vestingWithdraw(reservedWallet, _reservedTokens, reservedTotalSupply); } }
* @dev withdraw tokens amount within vesting rules for advisory/
function advisoryWithdraw() public { advisoryTotalSupply = vestingWithdraw(advisoryWallet, _advisoryTokens, advisoryTotalSupply); }
2,368,221
[ 1, 1918, 9446, 2430, 3844, 3470, 331, 10100, 2931, 364, 1261, 3516, 630, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1261, 3516, 630, 1190, 9446, 1435, 1071, 288, 203, 3639, 1261, 3516, 630, 5269, 3088, 1283, 273, 331, 10100, 1190, 9446, 12, 361, 3516, 630, 16936, 16, 389, 361, 3516, 630, 5157, 16, 1261, 3516, 630, 5269, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-07-29 */ // File: @openzeppelin/upgrades/contracts/upgradeability/Proxy.sol pragma solidity ^0.5.0; /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. */ contract Proxy { /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ function () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { 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 Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } // File: @openzeppelin/upgrades/contracts/utils/Address.sol pragma solidity ^0.5.0; /** * Utility library of inline functions on addresses * * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the * build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version. */ library OpenZeppelinUpgradesAddress { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: @openzeppelin/upgrades/contracts/upgradeability/BaseUpgradeabilityProxy.sol pragma solidity ^0.5.0; /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ 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 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return Address of the current implementation */ function _implementation() internal view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } // File: @openzeppelin/upgrades/contracts/upgradeability/UpgradeabilityProxy.sol pragma solidity ^0.5.0; /** * @title UpgradeabilityProxy * @dev Extends BaseUpgradeabilityProxy with a constructor for initializing * implementation and init data. */ contract UpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Contract constructor. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, bytes memory _data) public payable { assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)); _setImplementation(_logic); if(_data.length > 0) { (bool success,) = _logic.delegatecall(_data); require(success); } } } // File: @openzeppelin/upgrades/contracts/upgradeability/BaseAdminUpgradeabilityProxy.sol pragma solidity ^0.5.0; /** * @title BaseAdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. */ contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ 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 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address"); emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) external ifAdmin { _upgradeTo(newImplementation); } /** * @dev Upgrade the backing implementation of the proxy and call a function * on the new implementation. * This is useful to initialize the proxied contract. * @param newImplementation Address of the new implementation. * @param data Data to send as msg.data in the low level call. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. */ function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin { _upgradeTo(newImplementation); (bool success,) = newImplementation.delegatecall(data); require(success); } /** * @return The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } /** * @dev Only fall back when the sender is not the admin. */ function _willFallback() internal { require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin"); super._willFallback(); } } // File: contracts/KGLDProxy.sol pragma solidity 0.5.11; /** * @title KGLDProxy * @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for * initializing the implementation and admin. */ contract KGLDProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. */ constructor(address _logic, address _admin) UpgradeabilityProxy(_logic, bytes("")) public payable { assert(ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(_admin); } }
* @title KGLDProxy @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for initializing the implementation and admin./
contract KGLDProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy { constructor(address _logic, address _admin) UpgradeabilityProxy(_logic, bytes("")) public payable { assert(ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1)); _setAdmin(_admin); } }
6,646,700
[ 1, 47, 11261, 40, 3886, 225, 6419, 5839, 628, 3360, 4446, 10784, 2967, 3886, 598, 279, 3885, 364, 22584, 326, 4471, 471, 3981, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1475, 11261, 40, 3886, 353, 3360, 4446, 10784, 2967, 3886, 16, 17699, 2967, 3886, 288, 203, 203, 565, 3885, 12, 2867, 389, 28339, 16, 1758, 389, 3666, 13, 17699, 2967, 3886, 24899, 28339, 16, 1731, 2932, 6, 3719, 1071, 8843, 429, 288, 203, 3639, 1815, 12, 15468, 67, 55, 1502, 56, 422, 1731, 1578, 12, 11890, 5034, 12, 79, 24410, 581, 5034, 2932, 73, 625, 3657, 9599, 18, 5656, 18, 3666, 6, 3719, 300, 404, 10019, 203, 3639, 389, 542, 4446, 24899, 3666, 1769, 203, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import "./NiftyswapExchange20.sol"; import "../utils/Ownable.sol"; import "../interfaces/INiftyswapFactory20.sol"; import "../interfaces/IDelegatedERC1155Metadata.sol"; contract NiftyswapFactory20 is INiftyswapFactory20, Ownable, IDelegatedERC1155Metadata { /***********************************| | Events And Variables | |__________________________________*/ // tokensToExchange[erc1155_token_address][currency_address] mapping(address => mapping(address => mapping(uint256 => address))) public override tokensToExchange; mapping(address => mapping(address => address[])) internal pairExchanges; // Metadata implementation IERC1155Metadata internal metadataContract; // address of the ERC-1155 Metadata contract /** * @notice Will set the initial Niftyswap admin * @param _admin Address of the initial niftyswap admin to set as Owner */ constructor(address _admin) Ownable(_admin) { } /***********************************| | Functions | |__________________________________*/ /** * @notice Creates a NiftySwap Exchange for given token contract * @param _token The address of the ERC-1155 token contract * @param _currency The address of the ERC-20 token contract * @param _lpFee Fee that will go to LPs. * Number between 0 and 1000, where 10 is 1.0% and 100 is 10%. * @param _instance Instance # that allows to deploy new instances of an exchange. * This is mainly meant to be used for tokens that change their ERC-2981 support. */ function createExchange(address _token, address _currency, uint256 _lpFee, uint256 _instance) public override { require(tokensToExchange[_token][_currency][_instance] == address(0x0), "NF20#1"); // NiftyswapFactory20#createExchange: EXCHANGE_ALREADY_CREATED // Create new exchange contract NiftyswapExchange20 exchange = new NiftyswapExchange20(_token, _currency, _lpFee); // Store exchange and token addresses tokensToExchange[_token][_currency][_instance] = address(exchange); pairExchanges[_token][_currency].push(address(exchange)); // Emit event emit NewExchange(_token, _currency, _instance, address(exchange)); } /** * @notice Returns array of exchange instances for a given pair * @param _token The address of the ERC-1155 token contract * @param _currency The address of the ERC-20 token contract */ function getPairExchanges(address _token, address _currency) public override view returns (address[] memory) { return pairExchanges[_token][_currency]; } /***********************************| | Metadata Functions | |__________________________________*/ /** * @notice Changes the implementation of the ERC-1155 Metadata contract * @dev This function changes the implementation for all child exchanges of the factory * @param _contract The address of the ERC-1155 Metadata contract */ function setMetadataContract(IERC1155Metadata _contract) onlyOwner external { emit MetadataContractChanged(address(_contract)); metadataContract = _contract; } /** * @notice Returns the address of the ERC-1155 Metadata contract */ function metadataProvider() external override view returns (IERC1155Metadata) { return metadataContract; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; interface INiftyswapFactory20 { /***********************************| | Events | |__________________________________*/ event NewExchange(address indexed token, address indexed currency, uint256 indexed salt, address exchange); event MetadataContractChanged(address indexed metadataContract); /***********************************| | Public Functions | |__________________________________*/ /** * @notice Creates a NiftySwap Exchange for given token contract * @param _token The address of the ERC-1155 token contract * @param _currency The address of the currency token contract * @param _lpFee Fee that will go to LPs * Number between 0 and 1000, where 10 is 1.0% and 100 is 10%. * @param _instance Instance # that allows to deploy new instances of an exchange. * This is mainly meant to be used for tokens that change their ERC-2981 support. */ function createExchange(address _token, address _currency, uint256 _lpFee, uint256 _instance) external; /** * @notice Return address of exchange for corresponding ERC-1155 token contract * @param _token The address of the ERC-1155 token contract * @param _currency The address of the currency token contract * @param _instance Instance # that allows to deploy new instances of an exchange. * This is mainly meant to be used for tokens that change their ERC-2981 support. */ function tokensToExchange(address _token, address _currency, uint256 _instance) external view returns (address); /** * @notice Returns array of exchange instances for a given pair * @param _token The address of the ERC-1155 token contract * @param _currency The address of the ERC-20 token contract */ function getPairExchanges(address _token, address _currency) external view returns (address[] memory); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "../interfaces/INiftyswapExchange.sol"; import "../utils/ReentrancyGuard.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC165.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC1155.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC1155TokenReceiver.sol"; import "@0xsequence/erc-1155/contracts/tokens/ERC1155/ERC1155MintBurn.sol"; /** * This Uniswap-like implementation supports ERC-1155 standard tokens * with an ERC-1155 based token used as a currency instead of Ether. * * See https://github.com/0xsequence/erc20-meta-token for a generalized * ERC-20 => ERC-1155 token wrapper * * Liquidity tokens are also ERC-1155 tokens you can find the ERC-1155 * implementation used here: * https://github.com/horizon-games/multi-token-standard/tree/master/contracts/tokens/ERC1155 * * @dev Like Uniswap, tokens with 0 decimals and low supply are susceptible to significant rounding * errors when it comes to removing liquidity, possibly preventing them to be withdrawn without * some collaboration between liquidity providers. */ contract NiftyswapExchange is ReentrancyGuard, ERC1155MintBurn, INiftyswapExchange { using SafeMath for uint256; /***********************************| | Variables & Constants | |__________________________________*/ // Variables IERC1155 internal token; // address of the ERC-1155 token contract IERC1155 internal currency; // address of the ERC-1155 currency used for exchange bool internal currencyPoolBanned; // Whether the currency token ID can have a pool or not address internal factory; // address for the factory that created this contract uint256 internal currencyID; // ID of currency token in ERC-1155 currency contract uint256 internal constant FEE_MULTIPLIER = 995; // Multiplier that calculates the fee (1.0%) // Mapping variables mapping(uint256 => uint256) internal totalSupplies; // Liquidity pool token supply per Token id mapping(uint256 => uint256) internal currencyReserves; // currency Token reserve per Token id /***********************************| | Constructor | |__________________________________*/ /** * @notice Create instance of exchange contract with respective token and currency token * @param _tokenAddr The address of the ERC-1155 Token * @param _currencyAddr The address of the ERC-1155 currency Token * @param _currencyID The ID of the ERC-1155 currency Token */ constructor(address _tokenAddr, address _currencyAddr, uint256 _currencyID) public { require( address(_tokenAddr) != address(0) && _currencyAddr != address(0), "NiftyswapExchange#constructor:INVALID_INPUT" ); factory = msg.sender; token = IERC1155(_tokenAddr); currency = IERC1155(_currencyAddr); currencyID = _currencyID; // If token and currency are the same contract, // need to prevent currency/currency pool to be created. currencyPoolBanned = _currencyAddr == _tokenAddr ? true : false; } /***********************************| | Exchange Functions | |__________________________________*/ /** * @notice Convert currency tokens to Tokens _id and transfers Tokens to recipient. * @dev User specifies MAXIMUM inputs (_maxCurrency) and EXACT outputs. * @dev Assumes that all trades will be successful, or revert the whole tx * @dev Exceeding currency tokens sent will be refunded to recipient * @dev Sorting IDs is mandatory for efficient way of preventing duplicated IDs (which would lead to exploit) * @param _tokenIds Array of Tokens ID that are bought * @param _tokensBoughtAmounts Amount of Tokens id bought for each corresponding Token id in _tokenIds * @param _maxCurrency Total maximum amount of currency tokens to spend for all Token ids * @param _deadline Timestamp after which this transaction will be reverted * @param _recipient The address that receives output Tokens and refund * @return currencySold How much currency was actually sold. */ function _currencyToToken( uint256[] memory _tokenIds, uint256[] memory _tokensBoughtAmounts, uint256 _maxCurrency, uint256 _deadline, address _recipient) internal nonReentrant() returns (uint256[] memory currencySold) { // Input validation require(_deadline >= block.timestamp, "NiftyswapExchange#_currencyToToken: DEADLINE_EXCEEDED"); // Number of Token IDs to deposit uint256 nTokens = _tokenIds.length; uint256 totalRefundCurrency = _maxCurrency; // Initialize variables currencySold = new uint256[](nTokens); // Amount of currency tokens sold per ID uint256[] memory tokenReserves = new uint256[](nTokens); // Amount of tokens in reserve for each Token id // Get token reserves tokenReserves = _getTokenReserves(_tokenIds); // Assumes he currency Tokens are already received by contract, but not // the Tokens Ids // Remove liquidity for each Token ID in _tokenIds for (uint256 i = 0; i < nTokens; i++) { // Store current id and amount from argument arrays uint256 idBought = _tokenIds[i]; uint256 amountBought = _tokensBoughtAmounts[i]; uint256 tokenReserve = tokenReserves[i]; require(amountBought > 0, "NiftyswapExchange#_currencyToToken: NULL_TOKENS_BOUGHT"); // Load currency token and Token _id reserves uint256 currencyReserve = currencyReserves[idBought]; // Get amount of currency tokens to send for purchase // Neither reserves amount have been changed so far in this transaction, so // no adjustment to the inputs is needed uint256 currencyAmount = getBuyPrice(amountBought, currencyReserve, tokenReserve); // Calculate currency token amount to refund (if any) where whatever is not used will be returned // Will throw if total cost exceeds _maxCurrency totalRefundCurrency = totalRefundCurrency.sub(currencyAmount); // Append Token id, Token id amount and currency token amount to tracking arrays currencySold[i] = currencyAmount; // Update individual currency reseve amount currencyReserves[idBought] = currencyReserve.add(currencyAmount); } // Refund currency token if any if (totalRefundCurrency > 0) { currency.safeTransferFrom(address(this), _recipient, currencyID, totalRefundCurrency, ""); } // Send Tokens all tokens purchased token.safeBatchTransferFrom(address(this), _recipient, _tokenIds, _tokensBoughtAmounts, ""); return currencySold; } /** * @dev Pricing function used for converting between currency token to Tokens. * @param _assetBoughtAmount Amount of Tokens being bought. * @param _assetSoldReserve Amount of currency tokens in exchange reserves. * @param _assetBoughtReserve Amount of Tokens (output type) in exchange reserves. * @return price Amount of currency tokens to send to Niftyswap. */ function getBuyPrice( uint256 _assetBoughtAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) override public pure returns (uint256 price) { // Reserves must not be empty require(_assetSoldReserve > 0 && _assetBoughtReserve > 0, "NiftyswapExchange#getBuyPrice: EMPTY_RESERVE"); // Calculate price with fee uint256 numerator = _assetSoldReserve.mul(_assetBoughtAmount).mul(1000); uint256 denominator = (_assetBoughtReserve.sub(_assetBoughtAmount)).mul(FEE_MULTIPLIER); (price, ) = divRound(numerator, denominator); return price; // Will add 1 if rounding error } /** * @notice Convert Tokens _id to currency tokens and transfers Tokens to recipient. * @dev User specifies EXACT Tokens _id sold and MINIMUM currency tokens received. * @dev Assumes that all trades will be valid, or the whole tx will fail * @dev Sorting _tokenIds is mandatory for efficient way of preventing duplicated IDs (which would lead to errors) * @param _tokenIds Array of Token IDs that are sold * @param _tokensSoldAmounts Array of Amount of Tokens sold for each id in _tokenIds. * @param _minCurrency Minimum amount of currency tokens to receive * @param _deadline Timestamp after which this transaction will be reverted * @param _recipient The address that receives output currency tokens. * @return currencyBought How much currency was actually purchased. */ function _tokenToCurrency( uint256[] memory _tokenIds, uint256[] memory _tokensSoldAmounts, uint256 _minCurrency, uint256 _deadline, address _recipient) internal nonReentrant() returns (uint256[] memory currencyBought) { // Number of Token IDs to deposit uint256 nTokens = _tokenIds.length; // Input validation require(_deadline >= block.timestamp, "NiftyswapExchange#_tokenToCurrency: DEADLINE_EXCEEDED"); // Initialize variables uint256 totalCurrency = 0; // Total amount of currency tokens to transfer currencyBought = new uint256[](nTokens); uint256[] memory tokenReserves = new uint256[](nTokens); // Get token reserves tokenReserves = _getTokenReserves(_tokenIds); // Assumes the Tokens ids are already received by contract, but not // the Tokens Ids. Will return cards not sold if invalid price. // Remove liquidity for each Token ID in _tokenIds for (uint256 i = 0; i < nTokens; i++) { // Store current id and amount from argument arrays uint256 idSold = _tokenIds[i]; uint256 amountSold = _tokensSoldAmounts[i]; uint256 tokenReserve = tokenReserves[i]; // If 0 tokens send for this ID, revert require(amountSold > 0, "NiftyswapExchange#_tokenToCurrency: NULL_TOKENS_SOLD"); // Load currency token and Token _id reserves uint256 currencyReserve = currencyReserves[idSold]; // Get amount of currency that will be received // Need to sub amountSold because tokens already added in reserve, which would bias the calculation // Don't need to add it for currencyReserve because the amount is added after this calculation uint256 currencyAmount = getSellPrice(amountSold, tokenReserve.sub(amountSold), currencyReserve); // Increase cost of transaction totalCurrency = totalCurrency.add(currencyAmount); // Update individual currency reseve amount currencyReserves[idSold] = currencyReserve.sub(currencyAmount); // Append Token id, Token id amount and currency token amount to tracking arrays currencyBought[i] = currencyAmount; } // If minCurrency is not met require(totalCurrency >= _minCurrency, "NiftyswapExchange#_tokenToCurrency: INSUFFICIENT_CURRENCY_AMOUNT"); // Transfer currency here currency.safeTransferFrom(address(this), _recipient, currencyID, totalCurrency, ""); return currencyBought; } /** * @dev Pricing function used for converting Tokens to currency token. * @param _assetSoldAmount Amount of Tokens being sold. * @param _assetSoldReserve Amount of Tokens in exchange reserves. * @param _assetBoughtReserve Amount of currency tokens in exchange reserves. * @return price Amount of currency tokens to receive from Niftyswap. */ function getSellPrice( uint256 _assetSoldAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) override public pure returns (uint256 price) { //Reserves must not be empty require(_assetSoldReserve > 0 && _assetBoughtReserve > 0, "NiftyswapExchange#getSellPrice: EMPTY_RESERVE"); // Calculate amount to receive (with fee) uint256 _assetSoldAmount_withFee = _assetSoldAmount.mul(FEE_MULTIPLIER); uint256 numerator = _assetSoldAmount_withFee.mul(_assetBoughtReserve); uint256 denominator = _assetSoldReserve.mul(1000).add(_assetSoldAmount_withFee); return numerator / denominator; //Rounding errors will favor Niftyswap, so nothing to do } /***********************************| | Liquidity Functions | |__________________________________*/ /** * @notice Deposit less than max currency tokens && exact Tokens (token ID) at current ratio to mint liquidity pool tokens. * @dev min_liquidity does nothing when total liquidity pool token supply is 0. * @dev Assumes that sender approved this contract on the currency * @dev Sorting _tokenIds is mandatory for efficient way of preventing duplicated IDs (which would lead to errors) * @param _provider Address that provides liquidity to the reserve * @param _tokenIds Array of Token IDs where liquidity is added * @param _tokenAmounts Array of amount of Tokens deposited corresponding to each ID provided in _tokenIds * @param _maxCurrency Array of maximum number of tokens deposited for each ID provided in _tokenIds. * Deposits max amount if total liquidity pool token supply is 0. * @param _deadline Timestamp after which this transaction will be reverted */ function _addLiquidity( address _provider, uint256[] memory _tokenIds, uint256[] memory _tokenAmounts, uint256[] memory _maxCurrency, uint256 _deadline) internal nonReentrant() { // Requirements require(_deadline >= block.timestamp, "NiftyswapExchange#_addLiquidity: DEADLINE_EXCEEDED"); // Initialize variables uint256 nTokens = _tokenIds.length; // Number of Token IDs to deposit uint256 totalCurrency = 0; // Total amount of currency tokens to transfer // Initialize arrays uint256[] memory liquiditiesToMint = new uint256[](nTokens); uint256[] memory currencyAmounts = new uint256[](nTokens); uint256[] memory tokenReserves = new uint256[](nTokens); // Get token reserves tokenReserves = _getTokenReserves(_tokenIds); // Assumes tokens _ids are deposited already, but not currency tokens // as this is calculated and executed below. // Loop over all Token IDs to deposit for (uint256 i = 0; i < nTokens; i ++) { // Store current id and amount from argument arrays uint256 tokenId = _tokenIds[i]; uint256 amount = _tokenAmounts[i]; // Check if input values are acceptable require(_maxCurrency[i] > 0, "NiftyswapExchange#_addLiquidity: NULL_MAX_CURRENCY"); require(amount > 0, "NiftyswapExchange#_addLiquidity: NULL_TOKENS_AMOUNT"); // If the token contract and currency contract are the same, prevent the creation // of a currency pool. if (currencyPoolBanned) { require(tokenId != currencyID, "NiftyswapExchange#_addLiquidity: CURRENCY_POOL_FORBIDDEN"); } // Current total liquidity calculated in currency token uint256 totalLiquidity = totalSupplies[tokenId]; // When reserve for this token already exists if (totalLiquidity > 0) { // Load currency token and Token reserve's supply of Token id uint256 currencyReserve = currencyReserves[tokenId]; // Amount not yet in reserve uint256 tokenReserve = tokenReserves[i]; /** * Amount of currency tokens to send to token id reserve: * X/Y = dx/dy * dx = X*dy/Y * where * X: currency total liquidity * Y: Token _id total liquidity (before tokens were received) * dy: Amount of token _id deposited * dx: Amount of currency to deposit * * Adding .add(1) if rounding errors so to not favor users incorrectly */ (uint256 currencyAmount, bool rounded) = divRound(amount.mul(currencyReserve), tokenReserve.sub(amount)); require(_maxCurrency[i] >= currencyAmount, "NiftyswapExchange#_addLiquidity: MAX_CURRENCY_AMOUNT_EXCEEDED"); // Update currency reserve size for Token id before transfer currencyReserves[tokenId] = currencyReserve.add(currencyAmount); // Update totalCurrency totalCurrency = totalCurrency.add(currencyAmount); // Proportion of the liquidity pool to give to current liquidity provider // If rounding error occured, round down to favor previous liquidity providers // See https://github.com/0xsequence/niftyswap/issues/19 liquiditiesToMint[i] = (currencyAmount.sub(rounded ? 1 : 0)).mul(totalLiquidity) / currencyReserve; currencyAmounts[i] = currencyAmount; // Mint liquidity ownership tokens and increase liquidity supply accordingly totalSupplies[tokenId] = totalLiquidity.add(liquiditiesToMint[i]); } else { uint256 maxCurrency = _maxCurrency[i]; // Otherwise rounding error could end up being significant on second deposit require(maxCurrency >= 1000000000, "NiftyswapExchange#_addLiquidity: INVALID_CURRENCY_AMOUNT"); // Update currency reserve size for Token id before transfer currencyReserves[tokenId] = maxCurrency; // Update totalCurrency totalCurrency = totalCurrency.add(maxCurrency); // Initial liquidity is amount deposited (Incorrect pricing will be arbitraged) // uint256 initialLiquidity = _maxCurrency; totalSupplies[tokenId] = maxCurrency; // Liquidity to mints liquiditiesToMint[i] = maxCurrency; currencyAmounts[i] = maxCurrency; } } // Mint liquidity pool tokens _batchMint(_provider, _tokenIds, liquiditiesToMint, ""); // Transfer all currency to this contract currency.safeTransferFrom(_provider, address(this), currencyID, totalCurrency, abi.encode(DEPOSIT_SIG)); // Emit event emit LiquidityAdded(_provider, _tokenIds, _tokenAmounts, currencyAmounts); } /** * @dev Convert pool participation into amounts of token and currency. * @dev Rounding error of the asset with lower resolution is traded for the other asset. * @param _amountPool Participation to be converted to tokens and currency. * @param _tokenReserve Amount of tokens on the AMM reserve. * @param _currencyReserve Amount of currency on the AMM reserve. * @param _totalLiquidity Total liquidity on the pool. * * @return currencyAmount Currency corresponding to pool amount plus rounded tokens. * @return tokenAmount Token corresponding to pool amount plus rounded currency. */ function _toRoundedLiquidity( uint256 _amountPool, uint256 _tokenReserve, uint256 _currencyReserve, uint256 _totalLiquidity ) internal pure returns ( uint256 currencyAmount, uint256 tokenAmount, uint256 soldTokenNumerator, uint256 boughtCurrencyNumerator ) { uint256 currencyNumerator = _amountPool.mul(_currencyReserve); uint256 tokenNumerator = _amountPool.mul(_tokenReserve); // Convert all tokenProduct rest to currency soldTokenNumerator = tokenNumerator % _totalLiquidity; if (soldTokenNumerator != 0) { // The trade happens "after" funds are out of the pool // so we need to remove these funds before computing the rate uint256 virtualTokenReserve = _tokenReserve.sub(tokenNumerator / _totalLiquidity).mul(_totalLiquidity); uint256 virtualCurrencyReserve = _currencyReserve.sub(currencyNumerator / _totalLiquidity).mul(_totalLiquidity); // Skip process if any of the two reserves is left empty // this step is important to avoid an error withdrawing all left liquidity if (virtualCurrencyReserve != 0 && virtualTokenReserve != 0) { boughtCurrencyNumerator = getSellPrice(soldTokenNumerator, virtualTokenReserve, virtualCurrencyReserve); currencyNumerator = currencyNumerator.add(boughtCurrencyNumerator); } } // Calculate amounts currencyAmount = currencyNumerator / _totalLiquidity; tokenAmount = tokenNumerator / _totalLiquidity; } /** * @dev Burn liquidity pool tokens to withdraw currency && Tokens at current ratio. * @dev Sorting _tokenIds is mandatory for efficient way of preventing duplicated IDs (which would lead to errors) * @param _provider Address that removes liquidity to the reserve * @param _tokenIds Array of Token IDs where liquidity is removed * @param _poolTokenAmounts Array of Amount of liquidity pool tokens burned for each Token id in _tokenIds. * @param _minCurrency Minimum currency withdrawn for each Token id in _tokenIds. * @param _minTokens Minimum Tokens id withdrawn for each Token id in _tokenIds. * @param _deadline Timestamp after which this transaction will be reverted */ function _removeLiquidity( address _provider, uint256[] memory _tokenIds, uint256[] memory _poolTokenAmounts, uint256[] memory _minCurrency, uint256[] memory _minTokens, uint256 _deadline) internal nonReentrant() { // Input validation require(_deadline > block.timestamp, "NiftyswapExchange#_removeLiquidity: DEADLINE_EXCEEDED"); // Initialize variables uint256 nTokens = _tokenIds.length; // Number of Token IDs to deposit uint256 totalCurrency = 0; // Total amount of currency to transfer uint256[] memory tokenAmounts = new uint256[](nTokens); // Amount of Tokens to transfer for each id // Structs contain most information for the event // notice: tokenAmounts and tokenIds are absent because we already // either have those arrays constructed or we need to construct them for other reasons LiquidityRemovedEventObj[] memory eventObjs = new LiquidityRemovedEventObj[](nTokens); // Get token reserves uint256[] memory tokenReserves = _getTokenReserves(_tokenIds); // Assumes NIFTY liquidity tokens are already received by contract, but not // the currency nor the Tokens Ids // Remove liquidity for each Token ID in _tokenIds for (uint256 i = 0; i < nTokens; i++) { // Store current id and amount from argument arrays uint256 id = _tokenIds[i]; uint256 amountPool = _poolTokenAmounts[i]; // Load total liquidity pool token supply for Token _id uint256 totalLiquidity = totalSupplies[id]; require(totalLiquidity > 0, "NiftyswapExchange#_removeLiquidity: NULL_TOTAL_LIQUIDITY"); // Load currency and Token reserve's supply of Token id uint256 currencyReserve = currencyReserves[id]; // Calculate amount to withdraw for currency and Token _id uint256 currencyAmount; uint256 tokenAmount; { uint256 tokenReserve = tokenReserves[i]; uint256 soldTokenNumerator; uint256 boughtCurrencyNumerator; ( currencyAmount, tokenAmount, soldTokenNumerator, boughtCurrencyNumerator ) = _toRoundedLiquidity(amountPool, tokenReserve, currencyReserve, totalLiquidity); // Add trade info to event eventObjs[i].soldTokenNumerator = soldTokenNumerator; eventObjs[i].boughtCurrencyNumerator = boughtCurrencyNumerator; eventObjs[i].totalSupply = totalLiquidity; } // Verify if amounts to withdraw respect minimums specified require(currencyAmount >= _minCurrency[i], "NiftyswapExchange#_removeLiquidity: INSUFFICIENT_CURRENCY_AMOUNT"); require(tokenAmount >= _minTokens[i], "NiftyswapExchange#_removeLiquidity: INSUFFICIENT_TOKENS"); // Update total liquidity pool token supply of Token _id totalSupplies[id] = totalLiquidity.sub(amountPool); // Update currency reserve size for Token id currencyReserves[id] = currencyReserve.sub(currencyAmount); // Update totalCurrency and tokenAmounts totalCurrency = totalCurrency.add(currencyAmount); tokenAmounts[i] = tokenAmount; eventObjs[i].currencyAmount = currencyAmount; } // Burn liquidity pool tokens for offchain supplies _batchBurn(address(this), _tokenIds, _poolTokenAmounts); // Transfer total currency and all Tokens ids currency.safeTransferFrom(address(this), _provider, currencyID, totalCurrency, ""); token.safeBatchTransferFrom(address(this), _provider, _tokenIds, tokenAmounts, ""); // Emit event emit LiquidityRemoved(_provider, _tokenIds, tokenAmounts, eventObjs); } /***********************************| | Receiver Methods Handler | |__________________________________*/ // Method signatures for onReceive control logic // bytes4(keccak256( // "_currencyToToken(uint256[],uint256[],uint256,uint256,address)" // )); bytes4 internal constant BUYTOKENS_SIG = 0xb2d81047; // bytes4(keccak256( // "_tokenToCurrency(uint256[],uint256[],uint256,uint256,address)" // )); bytes4 internal constant SELLTOKENS_SIG = 0xdb08ec97; // bytes4(keccak256( // "_addLiquidity(address,uint256[],uint256[],uint256[],uint256)" // )); bytes4 internal constant ADDLIQUIDITY_SIG = 0x82da2b73; // bytes4(keccak256( // "_removeLiquidity(address,uint256[],uint256[],uint256[],uint256[],uint256)" // )); bytes4 internal constant REMOVELIQUIDITY_SIG = 0x5c0bf259; // bytes4(keccak256( // "DepositTokens()" // )); bytes4 internal constant DEPOSIT_SIG = 0xc8c323f9; /** * @notice Handle which method is being called on transfer * @dev `_data` must be encoded as follow: abi.encode(bytes4, MethodObj) * where bytes4 argument is the MethodObj object signature passed as defined * in the `Signatures for onReceive control logic` section above * @param _from The address which previously owned the Token * @param _ids An array containing ids of each Token being transferred * @param _amounts An array containing amounts of each Token being transferred * @param _data Method signature and corresponding encoded arguments for method to call on *this* contract * @return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)") */ function onERC1155BatchReceived( address, // _operator, address _from, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) override public returns(bytes4) { // This function assumes that the ERC-1155 token contract can // only call `onERC1155BatchReceived()` via a valid token transfer. // Users must be responsible and only use this Niftyswap exchange // contract with ERC-1155 compliant token contracts. // Obtain method to call via object signature bytes4 functionSignature = abi.decode(_data, (bytes4)); /***********************************| | Buying Tokens | |__________________________________*/ if (functionSignature == BUYTOKENS_SIG) { // Tokens received need to be currency contract require(msg.sender == address(currency), "NiftyswapExchange#onERC1155BatchReceived: INVALID_CURRENCY_TRANSFERRED"); require(_ids.length == 1, "NiftyswapExchange#onERC1155BatchReceived: INVALID_CURRENCY_IDS_AMOUNT"); require(_ids[0] == currencyID, "NiftyswapExchange#onERC1155BatchReceived: INVALID_CURRENCY_ID"); // Decode BuyTokensObj from _data to call _currencyToToken() BuyTokensObj memory obj; (, obj) = abi.decode(_data, (bytes4, BuyTokensObj)); address recipient = obj.recipient == address(0x0) ? _from : obj.recipient; // Execute trade and retrieve amount of currency spent uint256[] memory currencySold = _currencyToToken(obj.tokensBoughtIDs, obj.tokensBoughtAmounts, _amounts[0], obj.deadline, recipient); emit TokensPurchase(_from, recipient, obj.tokensBoughtIDs, obj.tokensBoughtAmounts, currencySold); /***********************************| | Selling Tokens | |__________________________________*/ } else if (functionSignature == SELLTOKENS_SIG) { // Tokens received need to be Token contract require(msg.sender == address(token), "NiftyswapExchange#onERC1155BatchReceived: INVALID_TOKENS_TRANSFERRED"); // Decode SellTokensObj from _data to call _tokenToCurrency() SellTokensObj memory obj; (, obj) = abi.decode(_data, (bytes4, SellTokensObj)); address recipient = obj.recipient == address(0x0) ? _from : obj.recipient; // Execute trade and retrieve amount of currency received uint256[] memory currencyBought = _tokenToCurrency(_ids, _amounts, obj.minCurrency, obj.deadline, recipient); emit CurrencyPurchase(_from, recipient, _ids, _amounts, currencyBought); /***********************************| | Adding Liquidity Tokens | |__________________________________*/ } else if (functionSignature == ADDLIQUIDITY_SIG) { // Only allow to receive ERC-1155 tokens from `token` contract require(msg.sender == address(token), "NiftyswapExchange#onERC1155BatchReceived: INVALID_TOKEN_TRANSFERRED"); // Decode AddLiquidityObj from _data to call _addLiquidity() AddLiquidityObj memory obj; (, obj) = abi.decode(_data, (bytes4, AddLiquidityObj)); _addLiquidity(_from, _ids, _amounts, obj.maxCurrency, obj.deadline); /***********************************| | Removing iquidity Tokens | |__________________________________*/ } else if (functionSignature == REMOVELIQUIDITY_SIG) { // Tokens received need to be NIFTY-1155 tokens require(msg.sender == address(this), "NiftyswapExchange#onERC1155BatchReceived: INVALID_NIFTY_TOKENS_TRANSFERRED"); // Decode RemoveLiquidityObj from _data to call _removeLiquidity() RemoveLiquidityObj memory obj; (, obj) = abi.decode(_data, (bytes4, RemoveLiquidityObj)); _removeLiquidity(_from, _ids, _amounts, obj.minCurrency, obj.minTokens, obj.deadline); /***********************************| | Deposits & Invalid Calls | |__________________________________*/ } else if (functionSignature == DEPOSIT_SIG) { // Do nothing for when contract is self depositing // This could be use to deposit currency "by accident", which would be locked require(msg.sender == address(currency), "NiftyswapExchange#onERC1155BatchReceived: INVALID_TOKENS_DEPOSITED"); require(_ids[0] == currencyID, "NiftyswapExchange#onERC1155BatchReceived: INVALID_CURRENCY_ID"); } else { revert("NiftyswapExchange#onERC1155BatchReceived: INVALID_METHOD"); } return ERC1155_BATCH_RECEIVED_VALUE; } /** * @dev Will pass to onERC115Batch5Received */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes memory _data) override public returns(bytes4) { uint256[] memory ids = new uint256[](1); uint256[] memory amounts = new uint256[](1); ids[0] = _id; amounts[0] = _amount; require( ERC1155_BATCH_RECEIVED_VALUE == onERC1155BatchReceived(_operator, _from, ids, amounts, _data), "NiftyswapExchange#onERC1155Received: INVALID_ONRECEIVED_MESSAGE" ); return ERC1155_RECEIVED_VALUE; } /** * @notice Prevents receiving Ether or calls to unsuported methods */ fallback () external { revert("NiftyswapExchange:UNSUPPORTED_METHOD"); } /***********************************| | Getter Functions | |__________________________________*/ /** * @notice Get amount of currency in reserve for each Token _id in _ids * @param _ids Array of ID sto query currency reserve of * @return amount of currency in reserve for each Token _id */ function getCurrencyReserves( uint256[] calldata _ids) override external view returns (uint256[] memory) { uint256 nIds = _ids.length; uint256[] memory currencyReservesReturn = new uint256[](nIds); for (uint256 i = 0; i < nIds; i++) { currencyReservesReturn[i] = currencyReserves[_ids[i]]; } return currencyReservesReturn; } /** * @notice Return price for `currency => Token _id` trades with an exact token amount. * @param _ids Array of ID of tokens bought. * @param _tokensBought Amount of Tokens bought. * @return Amount of currency needed to buy Tokens in _ids for amounts in _tokensBought */ function getPrice_currencyToToken( uint256[] calldata _ids, uint256[] calldata _tokensBought) override external view returns (uint256[] memory) { uint256 nIds = _ids.length; uint256[] memory prices = new uint256[](nIds); for (uint256 i = 0; i < nIds; i++) { // Load Token id reserve uint256 tokenReserve = token.balanceOf(address(this), _ids[i]); prices[i] = getBuyPrice(_tokensBought[i], currencyReserves[_ids[i]], tokenReserve); } // Return prices return prices; } /** * @notice Return price for `Token _id => currency` trades with an exact token amount. * @param _ids Array of IDs token sold. * @param _tokensSold Array of amount of each Token sold. * @return Amount of currency that can be bought for Tokens in _ids for amounts in _tokensSold */ function getPrice_tokenToCurrency( uint256[] calldata _ids, uint256[] calldata _tokensSold) override external view returns (uint256[] memory) { uint256 nIds = _ids.length; uint256[] memory prices = new uint256[](nIds); for (uint256 i = 0; i < nIds; i++) { // Load Token id reserve uint256 tokenReserve = token.balanceOf(address(this), _ids[i]); prices[i] = getSellPrice(_tokensSold[i], tokenReserve, currencyReserves[_ids[i]]); } // Return price return prices; } /** * @return Address of Token that is sold on this exchange. */ function getTokenAddress() override external view returns (address) { return address(token); } /** * @return Address of the currency contract that is used as currency and its corresponding id */ function getCurrencyInfo() override external view returns (address, uint256) { return (address(currency), currencyID); } /** * @notice Get total supply of liquidity tokens * @param _ids ID of the Tokens * @return The total supply of each liquidity token id provided in _ids */ function getTotalSupply(uint256[] calldata _ids) override external view returns (uint256[] memory) { // Number of ids uint256 nIds = _ids.length; // Variables uint256[] memory batchTotalSupplies = new uint256[](nIds); // Iterate over each owner and token ID for (uint256 i = 0; i < nIds; i++) { batchTotalSupplies[i] = totalSupplies[_ids[i]]; } return batchTotalSupplies; } /** * @return Address of factory that created this exchange. */ function getFactoryAddress() override external view returns (address) { return factory; } /***********************************| | Utility Functions | |__________________________________*/ /** * @notice Divides two numbers and add 1 if there is a rounding error * @param a Numerator * @param b Denominator */ function divRound(uint256 a, uint256 b) internal pure returns (uint256, bool) { return a % b == 0 ? (a/b, false) : ((a/b).add(1), true); } /** * @notice Return Token reserves for given Token ids * @dev Assumes that ids are sorted from lowest to highest with no duplicates. * This assumption allows for checking the token reserves only once, otherwise * token reserves need to be re-checked individually or would have to do more expensive * duplication checks. * @param _tokenIds Array of IDs to query their Reserve balance. * @return Array of Token ids' reserves */ function _getTokenReserves( uint256[] memory _tokenIds) internal view returns (uint256[] memory) { uint256 nTokens = _tokenIds.length; // Regular balance query if only 1 token, otherwise batch query if (nTokens == 1) { uint256[] memory tokenReserves = new uint256[](1); tokenReserves[0] = token.balanceOf(address(this), _tokenIds[0]); return tokenReserves; } else { // Lazy check preventing duplicates & build address array for query address[] memory thisAddressArray = new address[](nTokens); thisAddressArray[0] = address(this); for (uint256 i = 1; i < nTokens; i++) { require(_tokenIds[i-1] < _tokenIds[i], "NiftyswapExchange#_getTokenReserves: UNSORTED_OR_DUPLICATE_TOKEN_IDS"); thisAddressArray[i] = address(this); } return token.balanceOfBatch(thisAddressArray, _tokenIds); } } /** * @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types. * @param interfaceID The ERC-165 interface ID that is queried for support.s * @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface. * This function MUST NOT consume more thsan 5,000 gas. * @return Whether a given interface is supported */ function supportsInterface(bytes4 interfaceID) public override pure returns (bool) { return interfaceID == type(IERC165).interfaceId || interfaceID == type(IERC1155).interfaceId || interfaceID == type(IERC1155TokenReceiver).interfaceId; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; interface INiftyswapExchange { /***********************************| | Events | |__________________________________*/ event TokensPurchase( address indexed buyer, address indexed recipient, uint256[] tokensBoughtIds, uint256[] tokensBoughtAmounts, uint256[] currencySoldAmounts ); event CurrencyPurchase( address indexed buyer, address indexed recipient, uint256[] tokensSoldIds, uint256[] tokensSoldAmounts, uint256[] currencyBoughtAmounts ); event LiquidityAdded( address indexed provider, uint256[] tokenIds, uint256[] tokenAmounts, uint256[] currencyAmounts ); struct LiquidityRemovedEventObj { uint256 currencyAmount; uint256 soldTokenNumerator; uint256 boughtCurrencyNumerator; uint256 totalSupply; } event LiquidityRemoved( address indexed provider, uint256[] tokenIds, uint256[] tokenAmounts, LiquidityRemovedEventObj[] details ); // OnReceive Objects struct BuyTokensObj { address recipient; // Who receives the tokens uint256[] tokensBoughtIDs; // Token IDs to buy uint256[] tokensBoughtAmounts; // Amount of token to buy for each ID uint256 deadline; // Timestamp after which the tx isn't valid anymore } struct SellTokensObj { address recipient; // Who receives the currency uint256 minCurrency; // Total minimum number of currency expected for all tokens sold uint256 deadline; // Timestamp after which the tx isn't valid anymore } struct AddLiquidityObj { uint256[] maxCurrency; // Maximum number of currency to deposit with tokens uint256 deadline; // Timestamp after which the tx isn't valid anymore } struct RemoveLiquidityObj { uint256[] minCurrency; // Minimum number of currency to withdraw uint256[] minTokens; // Minimum number of tokens to withdraw uint256 deadline; // Timestamp after which the tx isn't valid anymore } /***********************************| | OnReceive Functions | |__________________________________*/ /** * @notice Handle which method is being called on Token transfer * @dev `_data` must be encoded as follow: abi.encode(bytes4, MethodObj) * where bytes4 argument is the MethodObj object signature passed as defined * in the `Signatures for onReceive control logic` section above * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount The amount of tokens being transferred * @param _data Method signature and corresponding encoded arguments for method to call on *this* contract * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4); /** * @notice Handle which method is being called on transfer * @dev `_data` must be encoded as follow: abi.encode(bytes4, MethodObj) * where bytes4 argument is the MethodObj object signature passed as defined * in the `Signatures for onReceive control logic` section above * @param _from The address which previously owned the Token * @param _ids An array containing ids of each Token being transferred * @param _amounts An array containing amounts of each Token being transferred * @param _data Method signature and corresponding encoded arguments for method to call on *this* contract * @return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)") */ function onERC1155BatchReceived(address, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4); /***********************************| | Getter Functions | |__________________________________*/ /** * @dev Pricing function used for converting between currency token to Tokens. * @param _assetBoughtAmount Amount of Tokens being bought. * @param _assetSoldReserve Amount of currency tokens in exchange reserves. * @param _assetBoughtReserve Amount of Tokens (output type) in exchange reserves. * @return Amount of currency tokens to send to Niftyswap. */ function getBuyPrice(uint256 _assetBoughtAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) external pure returns (uint256); /** * @dev Pricing function used for converting Tokens to currency token. * @param _assetSoldAmount Amount of Tokens being sold. * @param _assetSoldReserve Amount of Tokens in exchange reserves. * @param _assetBoughtReserve Amount of currency tokens in exchange reserves. * @return Amount of currency tokens to receive from Niftyswap. */ function getSellPrice(uint256 _assetSoldAmount,uint256 _assetSoldReserve, uint256 _assetBoughtReserve) external pure returns (uint256); /** * @notice Get amount of currency in reserve for each Token _id in _ids * @param _ids Array of ID sto query currency reserve of * @return amount of currency in reserve for each Token _id */ function getCurrencyReserves(uint256[] calldata _ids) external view returns (uint256[] memory); /** * @notice Return price for `currency => Token _id` trades with an exact token amount. * @param _ids Array of ID of tokens bought. * @param _tokensBought Amount of Tokens bought. * @return Amount of currency needed to buy Tokens in _ids for amounts in _tokensBought */ function getPrice_currencyToToken(uint256[] calldata _ids, uint256[] calldata _tokensBought) external view returns (uint256[] memory); /** * @notice Return price for `Token _id => currency` trades with an exact token amount. * @param _ids Array of IDs token sold. * @param _tokensSold Array of amount of each Token sold. * @return Amount of currency that can be bought for Tokens in _ids for amounts in _tokensSold */ function getPrice_tokenToCurrency(uint256[] calldata _ids, uint256[] calldata _tokensSold) external view returns (uint256[] memory); /** * @notice Get total supply of liquidity tokens * @param _ids ID of the Tokens * @return The total supply of each liquidity token id provided in _ids */ function getTotalSupply(uint256[] calldata _ids) external view returns (uint256[] memory); /** * @return Address of Token that is sold on this exchange. */ function getTokenAddress() external view returns (address); /** * @return Address of the currency contract that is used as currency and its corresponding id */ function getCurrencyInfo() external view returns (address, uint256); /** * @return Address of factory that created this exchange. */ function getFactoryAddress() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity 0.7.4; /** * @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: Apache-2.0 pragma solidity 0.7.4; /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas * @param _interfaceId The interface identifier, as specified in ERC-165 */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import './IERC165.sol'; interface IERC1155 is IERC165 { /****************************************| | Events | |_______________________________________*/ /** * @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning * Operator MUST be msg.sender * When minting/creating tokens, the `_from` field MUST be set to `0x0` * When burning/destroying tokens, the `_to` field MUST be set to `0x0` * The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID * To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0 */ event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount); /** * @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning * Operator MUST be msg.sender * When minting/creating tokens, the `_from` field MUST be set to `0x0` * When burning/destroying tokens, the `_to` field MUST be set to `0x0` * The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID * To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0 */ event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts); /** * @dev MUST emit when an approval is updated */ event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /****************************************| | Functions | |_______________________________________*/ /** * @notice Transfers amount of an _id from the _from address to the _to address specified * @dev MUST emit TransferSingle event on success * Caller must be approved to manage the _from account's tokens (see isApprovedForAll) * MUST throw if `_to` is the zero address * MUST throw if balance of sender for token `_id` is lower than the `_amount` sent * MUST throw on any other error * When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data) external; /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @dev MUST emit TransferBatch event on success * Caller must be approved to manage the _from account's tokens (see isApprovedForAll) * MUST throw if `_to` is the zero address * MUST throw if length of `_ids` is not the same as length of `_amounts` * MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent * MUST throw on any other error * When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external; /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) external view returns (uint256); /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @dev MUST emit the ApprovalForAll event on success * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external; /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return isOperator True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) external view returns (bool isOperator); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; /** * @dev ERC-1155 interface for accepting safe transfers. */ interface IERC1155TokenReceiver { /** * @notice Handle the receipt of a single ERC1155 token type * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value MUST result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount The amount of tokens being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4); /** * @notice Handle the receipt of multiple ERC1155 token types * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value WILL result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeBatchTransferFrom` function * @param _from The address which previously owned the token * @param _ids An array containing ids of each token being transferred * @param _amounts An array containing amounts of each token being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import "./ERC1155.sol"; /** * @dev Multi-Fungible Tokens with minting and burning methods. These methods assume * a parent contract to be executed as they are `internal` functions */ contract ERC1155MintBurn is ERC1155 { using SafeMath for uint256; /****************************************| | Minting Functions | |_______________________________________*/ /** * @notice Mint _amount of tokens of a given id * @param _to The address to mint tokens to * @param _id Token id to mint * @param _amount The amount to be minted * @param _data Data to pass if receiver is contract */ function _mint(address _to, uint256 _id, uint256 _amount, bytes memory _data) internal { // Add _amount balances[_to][_id] = balances[_to][_id].add(_amount); // Emit event emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount); // Calling onReceive method if recipient is contract _callonERC1155Received(address(0x0), _to, _id, _amount, gasleft(), _data); } /** * @notice Mint tokens for each ids in _ids * @param _to The address to mint tokens to * @param _ids Array of ids to mint * @param _amounts Array of amount of tokens to mint per id * @param _data Data to pass if receiver is contract */ function _batchMint(address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) internal { require(_ids.length == _amounts.length, "ERC1155MintBurn#batchMint: INVALID_ARRAYS_LENGTH"); // Number of mints to execute uint256 nMint = _ids.length; // Executing all minting for (uint256 i = 0; i < nMint; i++) { // Update storage balance balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, address(0x0), _to, _ids, _amounts); // Calling onReceive method if recipient is contract _callonERC1155BatchReceived(address(0x0), _to, _ids, _amounts, gasleft(), _data); } /****************************************| | Burning Functions | |_______________________________________*/ /** * @notice Burn _amount of tokens of a given token id * @param _from The address to burn tokens from * @param _id Token id to burn * @param _amount The amount to be burned */ function _burn(address _from, uint256 _id, uint256 _amount) internal { //Substract _amount balances[_from][_id] = balances[_from][_id].sub(_amount); // Emit event emit TransferSingle(msg.sender, _from, address(0x0), _id, _amount); } /** * @notice Burn tokens of given token id for each (_ids[i], _amounts[i]) pair * @param _from The address to burn tokens from * @param _ids Array of token ids to burn * @param _amounts Array of the amount to be burned */ function _batchBurn(address _from, uint256[] memory _ids, uint256[] memory _amounts) internal { // Number of mints to execute uint256 nBurn = _ids.length; require(nBurn == _amounts.length, "ERC1155MintBurn#batchBurn: INVALID_ARRAYS_LENGTH"); // Executing all minting for (uint256 i = 0; i < nBurn; i++) { // Update storage balance balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, _from, address(0x0), _ids, _amounts); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import "../../utils/SafeMath.sol"; import "../../interfaces/IERC1155TokenReceiver.sol"; import "../../interfaces/IERC1155.sol"; import "../../utils/Address.sol"; import "../../utils/ERC165.sol"; /** * @dev Implementation of Multi-Token Standard contract */ contract ERC1155 is IERC1155, ERC165 { using SafeMath for uint256; using Address for address; /***********************************| | Variables and Events | |__________________________________*/ // onReceive function signatures bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61; bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81; // Objects balances mapping (address => mapping(uint256 => uint256)) internal balances; // Operator Functions mapping (address => mapping(address => bool)) internal operators; /***********************************| | Public Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) public override { require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155#safeTransferFrom: INVALID_OPERATOR"); require(_to != address(0),"ERC1155#safeTransferFrom: INVALID_RECIPIENT"); // require(_amount <= balances[_from][_id]) is not necessary since checked with safemath operations _safeTransferFrom(_from, _to, _id, _amount); _callonERC1155Received(_from, _to, _id, _amount, gasleft(), _data); } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) public override { // Requirements require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR"); require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT"); _safeBatchTransferFrom(_from, _to, _ids, _amounts); _callonERC1155BatchReceived(_from, _to, _ids, _amounts, gasleft(), _data); } /***********************************| | Internal Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount */ function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount) internal { // Update balances balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount // Emit event emit TransferSingle(msg.sender, _from, _to, _id, _amount); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...) */ function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, uint256 _gasLimit, bytes memory _data) internal { // Check if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received{gas: _gasLimit}(msg.sender, _from, _id, _amount, _data); require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE"); } } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type */ function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts) internal { require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH"); // Number of transfer to execute uint256 nTransfer = _ids.length; // Executing all transfers for (uint256 i = 0; i < nTransfer; i++) { // Update storage balance of previous bin balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit event emit TransferBatch(msg.sender, _from, _to, _ids, _amounts); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...) */ function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, uint256 _gasLimit, bytes memory _data) internal { // Pass data if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived{gas: _gasLimit}(msg.sender, _from, _ids, _amounts, _data); require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE"); } } /***********************************| | Operator Functions | |__________________________________*/ /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external override { // Update operator status operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return isOperator True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) public override view returns (bool isOperator) { return operators[_owner][_operator]; } /***********************************| | Balance Functions | |__________________________________*/ /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) public override view returns (uint256) { return balances[_owner][_id]; } /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] memory _owners, uint256[] memory _ids) public override view returns (uint256[] memory) { require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH"); // Variables uint256[] memory batchBalances = new uint256[](_owners.length); // Iterate over each owner and token ID for (uint256 i = 0; i < _owners.length; i++) { batchBalances[i] = balances[_owners[i]][_ids[i]]; } return batchBalances; } /***********************************| | ERC165 Functions | |__________________________________*/ /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` and */ function supportsInterface(bytes4 _interfaceID) public override(ERC165, IERC165) virtual pure returns (bool) { if (_interfaceID == type(IERC1155).interfaceId) { return true; } return super.supportsInterface(_interfaceID); } } pragma solidity 0.7.4; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath#mul: OVERFLOW"); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath#div: DIVISION_BY_ZERO"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath#sub: UNDERFLOW"); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath#add: OVERFLOW"); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath#mod: DIVISION_BY_ZERO"); return a % b; } } pragma solidity 0.7.4; /** * Utility library of inline functions on addresses */ library Address { // Default hash for EOA accounts returned by extcodehash bytes32 constant internal ACCOUNT_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract. * @param _address address of the account to check * @return Whether the target address is a contract */ function isContract(address _address) internal view returns (bool) { bytes32 codehash; // Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address or if it has a non-zero code hash or account hash assembly { codehash := extcodehash(_address) } return (codehash != 0x0 && codehash != ACCOUNT_HASH); } } pragma solidity 0.7.4; import "../interfaces/IERC165.sol"; abstract contract ERC165 is IERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` */ function supportsInterface(bytes4 _interfaceID) virtual override public pure returns (bool) { return _interfaceID == this.supportsInterface.selector; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import "./NiftyswapExchange.sol"; import "../interfaces/INiftyswapFactory.sol"; contract NiftyswapFactory is INiftyswapFactory { /***********************************| | Events And Variables | |__________________________________*/ // tokensToExchange[erc1155_token_address][currency_address][currency_token_id] mapping(address => mapping(address => mapping(uint256 => address))) public override tokensToExchange; /***********************************| | Functions | |__________________________________*/ /** * @notice Creates a NiftySwap Exchange for given token contract * @param _token The address of the ERC-1155 token contract * @param _currency The address of the currency token contract * @param _currencyID The id of the currency token */ function createExchange(address _token, address _currency, uint256 _currencyID) public override { require(tokensToExchange[_token][_currency][_currencyID] == address(0x0), "NiftyswapFactory#createExchange: EXCHANGE_ALREADY_CREATED"); // Create new exchange contract NiftyswapExchange exchange = new NiftyswapExchange(_token, _currency, _currencyID); // Store exchange and token addresses tokensToExchange[_token][_currency][_currencyID] = address(exchange); // Emit event emit NewExchange(_token, _currency, _currencyID, address(exchange)); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; interface INiftyswapFactory { /***********************************| | Events | |__________________________________*/ event NewExchange(address indexed token, address indexed currency, uint256 indexed currencyID, address exchange); /***********************************| | Public Functions | |__________________________________*/ /** * @notice Creates a NiftySwap Exchange for given token contract * @param _token The address of the ERC-1155 token contract * @param _currency The address of the currency token contract * @param _currencyID The id of the currency token */ function createExchange(address _token, address _currency, uint256 _currencyID) external; /** * @notice Return address of exchange for corresponding ERC-1155 token contract * @param _token The address of the ERC-1155 token contract * @param _currency The address of the currency token contract * @param _currencyID The id of the currency token */ function tokensToExchange(address _token, address _currency, uint256 _currencyID) external view returns (address); } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@0xsequence/erc-1155/contracts/interfaces/IERC20.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC165.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC1155.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC1155TokenReceiver.sol"; import "@0xsequence/erc-1155/contracts/tokens/ERC1155/ERC1155Meta.sol"; import "@0xsequence/erc-1155/contracts/tokens/ERC1155/ERC1155MintBurn.sol"; /** * @notice Allows users to wrap any amount of any ERC-20 token with a 1:1 ratio * of corresponding ERC-1155 tokens with native metaTransaction methods. Each * ERC-20 is assigned an ERC-1155 id for more efficient CALLDATA usage when * doing transfers. */ contract MetaERC20Wrapper is ERC1155Meta, ERC1155MintBurn { // Variables uint256 internal nTokens = 1; // Number of ERC-20 tokens registered uint256 constant internal ETH_ID = 0x1; // ID fo tokens representing Ether is 1 address constant internal ETH_ADDRESS = address(0x1); // Address for tokens representing Ether is 0x00...01 mapping (address => uint256) internal addressToID; // Maps the ERC-20 addresses to their metaERC20 id mapping (uint256 => address) internal IDtoAddress; // Maps the metaERC20 ids to their ERC-20 address /***********************************| | Events | |__________________________________*/ event TokenRegistration(address token_address, uint256 token_id); /***********************************| | Constructor | |__________________________________*/ // Register ETH as ID #1 and address 0x1 constructor() public { addressToID[ETH_ADDRESS] = ETH_ID; IDtoAddress[ETH_ID] = ETH_ADDRESS; } /***********************************| | Deposit Functions | |__________________________________*/ /** * Fallback function * @dev Deposit ETH in this contract to receive wrapped ETH * No parameters provided */ receive () external payable { // Deposit ETH sent with transaction deposit(ETH_ADDRESS, msg.sender, msg.value); } /** * @dev Deposit ERC20 tokens or ETH in this contract to receive wrapped ERC20s * @param _token The addess of the token to deposit in this contract * @param _recipient Address that will receive the ERC-1155 tokens * @param _value The amount of token to deposit in this contract * Note: Users must first approve this contract addres on the contract of the ERC20 to be deposited */ function deposit(address _token, address _recipient, uint256 _value) public payable { require(_recipient != address(0x0), "MetaERC20Wrapper#deposit: INVALID_RECIPIENT"); // Internal ID of ERC-20 token deposited uint256 id; // Deposit ERC-20 tokens or ETH if (_token != ETH_ADDRESS) { // Check if transfer passes require(msg.value == 0, "MetaERC20Wrapper#deposit: NON_NULL_MSG_VALUE"); IERC20(_token).transferFrom(msg.sender, address(this), _value); require(checkSuccess(), "MetaERC20Wrapper#deposit: TRANSFER_FAILED"); // Load address token ID uint256 addressId = addressToID[_token]; // Register ID if not already done if (addressId == 0) { nTokens += 1; // Increment number of tokens registered id = nTokens; // id of token is the current # of tokens IDtoAddress[id] = _token; // Map id to token address addressToID[_token] = id; // Register token // Emit registration event emit TokenRegistration(_token, id); } else { id = addressId; } } else { require(_value == msg.value, "MetaERC20Wrapper#deposit: INCORRECT_MSG_VALUE"); id = ETH_ID; } // Mint meta tokens _mint(_recipient, id, _value, ""); } /***********************************| | Withdraw Functions | |__________________________________*/ /** * @dev Withdraw wrapped ERC20 tokens in this contract to receive the original ERC20s or ETH * @param _token The addess of the token to withdrww from this contract * @param _to The address where the withdrawn tokens will go to * @param _value The amount of tokens to withdraw */ function withdraw(address _token, address payable _to, uint256 _value) public { uint256 tokenID = getTokenID(_token); _withdraw(msg.sender, _to, tokenID, _value); } /** * @dev Withdraw wrapped ERC20 tokens in this contract to receive the original ERC20s or ETH * @param _from Address of users sending the Meta tokens * @param _to The address where the withdrawn tokens will go to * @param _tokenID The token ID of the ERC-20 token to withdraw from this contract * @param _value The amount of tokens to withdraw */ function _withdraw( address _from, address payable _to, uint256 _tokenID, uint256 _value) internal { // Burn meta tokens _burn(_from, _tokenID, _value); // Withdraw ERC-20 tokens or ETH if (_tokenID != ETH_ID) { address token = IDtoAddress[_tokenID]; IERC20(token).transfer(_to, _value); require(checkSuccess(), "MetaERC20Wrapper#withdraw: TRANSFER_FAILED"); } else { require(_to != address(0), "MetaERC20Wrapper#withdraw: INVALID_RECIPIENT"); (bool success, ) = _to.call{value: _value}(""); require(success, "MetaERC20Wrapper#withdraw: TRANSFER_FAILED"); } } /** * @notice Withdraw ERC-20 tokens when receiving their ERC-1155 counterpart * @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 * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address, address payable _from, uint256 _id, uint256 _value, bytes memory) public returns(bytes4) { // Only ERC-1155 from this contract are valid require(msg.sender == address(this), "MetaERC20Wrapper#onERC1155Received: INVALID_ERC1155_RECEIVED"); getIdAddress(_id); // Checks if id is registered // Tokens are received, hence need to burn them here _withdraw(address(this), _from, _id, _value); return ERC1155_RECEIVED_VALUE; } /** * @notice Withdraw ERC-20 tokens when receiving their ERC-1155 counterpart * @param _from The address which previously owned the token * @param _ids An array containing ids of each token being transferred * @param _values An array containing amounts of each token being transferred * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived(address, address payable _from, uint256[] memory _ids, uint256[] memory _values, bytes memory) public returns(bytes4) { // Only ERC-1155 from this contract are valid require(msg.sender == address(this), "MetaERC20Wrapper#onERC1155BatchReceived: INVALID_ERC1155_RECEIVED"); // Withdraw all tokens for ( uint256 i = 0; i < _ids.length; i++) { // Checks if id is registered getIdAddress(_ids[i]); // Tokens are received, hence need to burn them here _withdraw(address(this), _from, _ids[i], _values[i]); } return ERC1155_BATCH_RECEIVED_VALUE; } /** * @notice Return the Meta-ERC20 token ID for the given ERC-20 token address * @param _token ERC-20 token address to get the corresponding Meta-ERC20 token ID * @return tokenID Meta-ERC20 token ID */ function getTokenID(address _token) public view returns (uint256 tokenID) { tokenID = addressToID[_token]; require(tokenID != 0, "MetaERC20Wrapper#getTokenID: UNREGISTERED_TOKEN"); return tokenID; } /** * @notice Return the ERC-20 token address for the given Meta-ERC20 token ID * @param _id Meta-ERC20 token ID to get the corresponding ERC-20 token address * @return token ERC-20 token address */ function getIdAddress(uint256 _id) public view returns (address token) { token = IDtoAddress[_id]; require(token != address(0x0), "MetaERC20Wrapper#getIdAddress: UNREGISTERED_TOKEN"); return token; } /** * @notice Returns number of tokens currently registered */ function getNTokens() external view returns (uint256) { return nTokens; } /***********************************| | Helper Functions | |__________________________________*/ /** * Checks the return value of the previous function up to 32 bytes. Returns true if the previous * function returned 0 bytes or 32 bytes that are not all-zero. * Code taken from: https://github.com/dydxprotocol/solo/blob/10baf8e4c3fb9db4d0919043d3e6fdd6ba834046/contracts/protocol/lib/Token.sol */ function checkSuccess() private pure returns (bool) { uint256 returnValue = 0; /* solium-disable-next-line security/no-inline-assembly */ assembly { // check number of bytes returned from last function call switch returndatasize() // no bytes returned: assume success case 0x0 { returnValue := 1 } // 32 bytes returned: check if non-zero case 0x20 { // copy 32 bytes into scratch space returndatacopy(0x0, 0x0, 0x20) // load those bytes into returnValue returnValue := mload(0x0) } // not sure what was returned: dont mark as success default { } } return returnValue != 0; } /** * @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types. * @param interfaceID The ERC-165 interface ID that is queried for support.s * @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface. * This function MUST NOT consume more than 5,000 gas. * @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported. */ function supportsInterface(bytes4 interfaceID) public override pure returns (bool) { return interfaceID == type(IERC165).interfaceId || interfaceID == type(IERC1155).interfaceId || interfaceID == type(IERC1155TokenReceiver).interfaceId; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "./ERC1155.sol"; import "../../interfaces/IERC20.sol"; import "../../interfaces/IERC1155.sol"; import "../../utils/LibBytes.sol"; import "../../utils/SignatureValidator.sol"; /** * @dev ERC-1155 with native metatransaction methods. These additional functions allow users * to presign function calls and allow third parties to execute these on their behalf */ contract ERC1155Meta is ERC1155, SignatureValidator { using LibBytes for bytes; /***********************************| | Variables and Structs | |__________________________________*/ /** * Gas Receipt * feeTokenData : (bool, address, ?unit256) * 1st element should be the address of the token * 2nd argument (if ERC-1155) should be the ID of the token * Last element should be a 0x0 if ERC-20 and 0x1 for ERC-1155 */ struct GasReceipt { uint256 gasFee; // Fixed cost for the tx uint256 gasLimitCallback; // Maximum amount of gas the callback in transfer functions can use address feeRecipient; // Address to send payment to bytes feeTokenData; // Data for token to pay for gas } // Which token standard is used to pay gas fee enum FeeTokenType { ERC1155, // 0x00, ERC-1155 token - DEFAULT ERC20, // 0x01, ERC-20 token NTypes // 0x02, number of signature types. Always leave at end. } // Signature nonce per address mapping (address => uint256) internal nonces; /***********************************| | Events | |__________________________________*/ event NonceChange(address indexed signer, uint256 newNonce); /****************************************| | Public Meta Transfer Functions | |_______________________________________*/ /** * @notice Allows anyone with a valid signature to transfer _amount amount of a token _id on the bahalf of _from * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _isGasFee Whether gas is reimbursed to executor or not * @param _data Encodes a meta transfer indicator, signature, gas payment receipt and extra transfer data * _data should be encoded as ( * (bytes32 r, bytes32 s, uint8 v, uint256 nonce, SignatureType sigType), * (GasReceipt g, ?bytes transferData) * ) * i.e. high level encoding should be (bytes, bytes), where the latter bytes array is a nested bytes array */ function metaSafeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount, bool _isGasFee, bytes memory _data) public { require(_to != address(0), "ERC1155Meta#metaSafeTransferFrom: INVALID_RECIPIENT"); // Initializing bytes memory transferData; GasReceipt memory gasReceipt; // Verify signature and extract the signed data bytes memory signedData = _signatureValidation( _from, _data, abi.encode( META_TX_TYPEHASH, _from, // Address as uint256 _to, // Address as uint256 _id, _amount, _isGasFee ? uint256(1) : uint256(0) // Boolean as uint256 ) ); // Transfer asset _safeTransferFrom(_from, _to, _id, _amount); // If Gas is being reimbursed if (_isGasFee) { (gasReceipt, transferData) = abi.decode(signedData, (GasReceipt, bytes)); // We need to somewhat protect relayers against gas griefing attacks in recipient contract. // Hence we only pass the gasLimit to the recipient such that the relayer knows the griefing // limit. Nothing can prevent the receiver to revert the transaction as close to the gasLimit as // possible, but the relayer can now only accept meta-transaction gasLimit within a certain range. _callonERC1155Received(_from, _to, _id, _amount, gasReceipt.gasLimitCallback, transferData); // Transfer gas cost _transferGasFee(_from, gasReceipt); } else { _callonERC1155Received(_from, _to, _id, _amount, gasleft(), signedData); } } /** * @notice Allows anyone with a valid signature to transfer multiple types of tokens on the bahalf of _from * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _isGasFee Whether gas is reimbursed to executor or not * @param _data Encodes a meta transfer indicator, signature, gas payment receipt and extra transfer data * _data should be encoded as ( * (bytes32 r, bytes32 s, uint8 v, uint256 nonce, SignatureType sigType), * (GasReceipt g, ?bytes transferData) * ) * i.e. high level encoding should be (bytes, bytes), where the latter bytes array is a nested bytes array */ function metaSafeBatchTransferFrom( address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bool _isGasFee, bytes memory _data) public { require(_to != address(0), "ERC1155Meta#metaSafeBatchTransferFrom: INVALID_RECIPIENT"); // Initializing bytes memory transferData; GasReceipt memory gasReceipt; // Verify signature and extract the signed data bytes memory signedData = _signatureValidation( _from, _data, abi.encode( META_BATCH_TX_TYPEHASH, _from, // Address as uint256 _to, // Address as uint256 keccak256(abi.encodePacked(_ids)), keccak256(abi.encodePacked(_amounts)), _isGasFee ? uint256(1) : uint256(0) // Boolean as uint256 ) ); // Transfer assets _safeBatchTransferFrom(_from, _to, _ids, _amounts); // If gas fee being reimbursed if (_isGasFee) { (gasReceipt, transferData) = abi.decode(signedData, (GasReceipt, bytes)); // We need to somewhat protect relayers against gas griefing attacks in recipient contract. // Hence we only pass the gasLimit to the recipient such that the relayer knows the griefing // limit. Nothing can prevent the receiver to revert the transaction as close to the gasLimit as // possible, but the relayer can now only accept meta-transaction gasLimit within a certain range. _callonERC1155BatchReceived(_from, _to, _ids, _amounts, gasReceipt.gasLimitCallback, transferData); // Handle gas reimbursement _transferGasFee(_from, gasReceipt); } else { _callonERC1155BatchReceived(_from, _to, _ids, _amounts, gasleft(), signedData); } } /***********************************| | Operator Functions | |__________________________________*/ /** * @notice Approve the passed address to spend on behalf of _from if valid signature is provided * @param _owner Address that wants to set operator status _spender * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval * @param _isGasFee Whether gas will be reimbursed or not, with vlid signature * @param _data Encodes signature and gas payment receipt * _data should be encoded as ( * (bytes32 r, bytes32 s, uint8 v, uint256 nonce, SignatureType sigType), * (GasReceipt g) * ) * i.e. high level encoding should be (bytes, bytes), where the latter bytes array is a nested bytes array */ function metaSetApprovalForAll( address _owner, address _operator, bool _approved, bool _isGasFee, bytes memory _data) public { // Verify signature and extract the signed data bytes memory signedData = _signatureValidation( _owner, _data, abi.encode( META_APPROVAL_TYPEHASH, _owner, // Address as uint256 _operator, // Address as uint256 _approved ? uint256(1) : uint256(0), // Boolean as uint256 _isGasFee ? uint256(1) : uint256(0) // Boolean as uint256 ) ); // Update operator status operators[_owner][_operator] = _approved; // Emit event emit ApprovalForAll(_owner, _operator, _approved); // Handle gas reimbursement if (_isGasFee) { GasReceipt memory gasReceipt = abi.decode(signedData, (GasReceipt)); _transferGasFee(_owner, gasReceipt); } } /****************************************| | Signature Validation Functions | |_______________________________________*/ // keccak256( // "metaSafeTransferFrom(address,address,uint256,uint256,bool,bytes)" // ); bytes32 internal constant META_TX_TYPEHASH = 0xce0b514b3931bdbe4d5d44e4f035afe7113767b7db71949271f6a62d9c60f558; // keccak256( // "metaSafeBatchTransferFrom(address,address,uint256[],uint256[],bool,bytes)" // ); bytes32 internal constant META_BATCH_TX_TYPEHASH = 0xa3d4926e8cf8fe8e020cd29f514c256bc2eec62aa2337e415f1a33a4828af5a0; // keccak256( // "metaSetApprovalForAll(address,address,bool,bool,bytes)" // ); bytes32 internal constant META_APPROVAL_TYPEHASH = 0xf5d4c820494c8595de274c7ff619bead38aac4fbc3d143b5bf956aa4b84fa524; /** * @notice Verifies signatures for this contract * @param _signer Address of signer * @param _sigData Encodes signature, gas payment receipt and transfer data (if any) * @param _encMembers Encoded EIP-712 type members (except nonce and _data), all need to be 32 bytes size * @dev _data should be encoded as ( * (bytes32 r, bytes32 s, uint8 v, uint256 nonce, SignatureType sigType), * (GasReceipt g, ?bytes transferData) * ) * i.e. high level encoding should be (bytes, bytes), where the latter bytes array is a nested bytes array * @dev A valid nonce is a nonce that is within 100 value from the current nonce */ function _signatureValidation( address _signer, bytes memory _sigData, bytes memory _encMembers) internal returns (bytes memory signedData) { bytes memory sig; // Get signature and data to sign (sig, signedData) = abi.decode(_sigData, (bytes, bytes)); // Get current nonce and nonce used for signature uint256 currentNonce = nonces[_signer]; // Lowest valid nonce for signer uint256 nonce = uint256(sig.readBytes32(65)); // Nonce passed in the signature object // Verify if nonce is valid require( (nonce >= currentNonce) && (nonce < (currentNonce + 100)), "ERC1155Meta#_signatureValidation: INVALID_NONCE" ); // Take hash of bytes arrays bytes32 hash = hashEIP712Message(keccak256(abi.encodePacked(_encMembers, nonce, keccak256(signedData)))); // Complete data to pass to signer verifier bytes memory fullData = abi.encodePacked(_encMembers, nonce, signedData); //Update signature nonce nonces[_signer] = nonce + 1; emit NonceChange(_signer, nonce + 1); // Verify if _from is the signer require(isValidSignature(_signer, hash, fullData, sig), "ERC1155Meta#_signatureValidation: INVALID_SIGNATURE"); return signedData; } /** * @notice Returns the current nonce associated with a given address * @param _signer Address to query signature nonce for */ function getNonce(address _signer) public view returns (uint256 nonce) { return nonces[_signer]; } /***********************************| | Gas Reimbursement Functions | |__________________________________*/ /** * @notice Will reimburse tx.origin or fee recipient for the gas spent execution a transaction * Can reimbuse in any ERC-20 or ERC-1155 token * @param _from Address from which the payment will be made from * @param _g GasReceipt object that contains gas reimbursement information */ function _transferGasFee(address _from, GasReceipt memory _g) internal { // Pop last byte to get token fee type uint8 feeTokenTypeRaw = uint8(_g.feeTokenData.popLastByte()); // Ensure valid fee token type require( feeTokenTypeRaw < uint8(FeeTokenType.NTypes), "ERC1155Meta#_transferGasFee: UNSUPPORTED_TOKEN" ); // Convert to FeeTokenType corresponding value FeeTokenType feeTokenType = FeeTokenType(feeTokenTypeRaw); // Declarations address tokenAddress; address feeRecipient; uint256 tokenID; uint256 fee = _g.gasFee; // If receiver is 0x0, then anyone can claim, otherwise, refund addresse provided feeRecipient = _g.feeRecipient == address(0) ? msg.sender : _g.feeRecipient; // Fee token is ERC1155 if (feeTokenType == FeeTokenType.ERC1155) { (tokenAddress, tokenID) = abi.decode(_g.feeTokenData, (address, uint256)); // Fee is paid from this ERC1155 contract if (tokenAddress == address(this)) { _safeTransferFrom(_from, feeRecipient, tokenID, fee); // No need to protect against griefing since recipient (if contract) is most likely owned by the relayer _callonERC1155Received(_from, feeRecipient, tokenID, gasleft(), fee, ""); // Fee is paid from another ERC-1155 contract } else { IERC1155(tokenAddress).safeTransferFrom(_from, feeRecipient, tokenID, fee, ""); } // Fee token is ERC20 } else { tokenAddress = abi.decode(_g.feeTokenData, (address)); require( IERC20(tokenAddress).transferFrom(_from, feeRecipient, fee), "ERC1155Meta#_transferGasFee: ERC20_TRANSFER_FAILED" ); } } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. This is a truncated version of the original LibBytes.sol library from ZeroEx. */ pragma solidity 0.7.4; library LibBytes { using LibBytes for bytes; /***********************************| | Pop Bytes Functions | |__________________________________*/ /** * @dev Pops the last byte off of a byte array by modifying its length. * @param b Byte array that will be modified. * @return result The byte that was popped off. */ function popLastByte(bytes memory b) internal pure returns (bytes1 result) { require( b.length > 0, "LibBytes#popLastByte: GREATER_THAN_ZERO_LENGTH_REQUIRED" ); // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /***********************************| | Read Bytes Functions | |__________________________________*/ /** * @dev Reads a bytes32 value from a position in a byte array. * @param b Byte array containing a bytes32 value. * @param index Index in byte array of bytes32 value. * @return result bytes32 value from byte array. */ function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { require( b.length >= index + 32, "LibBytes#readBytes32: GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED" ); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } } pragma solidity 0.7.4; import "../interfaces/IERC1271Wallet.sol"; import "./LibBytes.sol"; import "./LibEIP712.sol"; /** * @dev Contains logic for signature validation. * Signatures from wallet contracts assume ERC-1271 support (https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1271.md) * Notes: Methods are strongly inspired by contracts in https://github.com/0xProject/0x-monorepo/blob/development/ */ contract SignatureValidator is LibEIP712 { using LibBytes for bytes; /***********************************| | Variables | |__________________________________*/ // bytes4(keccak256("isValidSignature(bytes,bytes)")) bytes4 constant internal ERC1271_MAGICVALUE = 0x20c13b0b; // bytes4(keccak256("isValidSignature(bytes32,bytes)")) bytes4 constant internal ERC1271_MAGICVALUE_BYTES32 = 0x1626ba7e; // Allowed signature types. enum SignatureType { Illegal, // 0x00, default value EIP712, // 0x01 EthSign, // 0x02 WalletBytes, // 0x03 To call isValidSignature(bytes, bytes) on wallet contract WalletBytes32, // 0x04 To call isValidSignature(bytes32, bytes) on wallet contract NSignatureTypes // 0x05, number of signature types. Always leave at end. } /***********************************| | Signature Functions | |__________________________________*/ /** * @dev Verifies that a hash has been signed by the given signer. * @param _signerAddress Address that should have signed the given hash. * @param _hash Hash of the EIP-712 encoded data * @param _data Full EIP-712 data structure that was hashed and signed * @param _sig Proof that the hash has been signed by signer. * For non wallet signatures, _sig is expected to be an array tightly encoded as * (bytes32 r, bytes32 s, uint8 v, uint256 nonce, SignatureType sigType) * @return isValid True if the address recovered from the provided signature matches the input signer address. */ function isValidSignature( address _signerAddress, bytes32 _hash, bytes memory _data, bytes memory _sig ) public view returns (bool isValid) { require( _sig.length > 0, "SignatureValidator#isValidSignature: LENGTH_GREATER_THAN_0_REQUIRED" ); require( _signerAddress != address(0x0), "SignatureValidator#isValidSignature: INVALID_SIGNER" ); // Pop last byte off of signature byte array. uint8 signatureTypeRaw = uint8(_sig.popLastByte()); // Ensure signature is supported require( signatureTypeRaw < uint8(SignatureType.NSignatureTypes), "SignatureValidator#isValidSignature: UNSUPPORTED_SIGNATURE" ); // Extract signature type SignatureType signatureType = SignatureType(signatureTypeRaw); // Variables are not scoped in Solidity. uint8 v; bytes32 r; bytes32 s; address recovered; // Always illegal signature. // This is always an implicit option since a signer can create a // signature array with invalid type or length. We may as well make // it an explicit option. This aids testing and analysis. It is // also the initialization value for the enum type. if (signatureType == SignatureType.Illegal) { revert("SignatureValidator#isValidSignature: ILLEGAL_SIGNATURE"); // Signature using EIP712 } else if (signatureType == SignatureType.EIP712) { require( _sig.length == 97, "SignatureValidator#isValidSignature: LENGTH_97_REQUIRED" ); r = _sig.readBytes32(0); s = _sig.readBytes32(32); v = uint8(_sig[64]); recovered = ecrecover(_hash, v, r, s); isValid = _signerAddress == recovered; return isValid; // Signed using web3.eth_sign() or Ethers wallet.signMessage() } else if (signatureType == SignatureType.EthSign) { require( _sig.length == 97, "SignatureValidator#isValidSignature: LENGTH_97_REQUIRED" ); r = _sig.readBytes32(0); s = _sig.readBytes32(32); v = uint8(_sig[64]); recovered = ecrecover( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)), v, r, s ); isValid = _signerAddress == recovered; return isValid; // Signature verified by wallet contract with data validation. } else if (signatureType == SignatureType.WalletBytes) { isValid = ERC1271_MAGICVALUE == IERC1271Wallet(_signerAddress).isValidSignature(_data, _sig); return isValid; // Signature verified by wallet contract without data validation. } else if (signatureType == SignatureType.WalletBytes32) { isValid = ERC1271_MAGICVALUE_BYTES32 == IERC1271Wallet(_signerAddress).isValidSignature(_hash, _sig); return isValid; } // Anything else is illegal (We do not return false because // the signature may actually be valid, just not in a format // that we currently support. In this case returning false // may lead the caller to incorrectly believe that the // signature was invalid.) revert("SignatureValidator#isValidSignature: UNSUPPORTED_SIGNATURE"); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; interface IERC1271Wallet { /** * @notice Verifies whether the provided signature is valid with respect to the provided data * @dev MUST return the correct magic value if the signature provided is valid for the provided data * > The bytes4 magic value to return when signature is valid is 0x20c13b0b : bytes4(keccak256("isValidSignature(bytes,bytes)") * > This function MAY modify Ethereum's state * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return magicValue Magic value 0x20c13b0b if the signature is valid and 0x0 otherwise * */ function isValidSignature( bytes calldata _data, bytes calldata _signature) external view returns (bytes4 magicValue); /** * @notice Verifies whether the provided signature is valid with respect to the provided hash * @dev MUST return the correct magic value if the signature provided is valid for the provided hash * > The bytes4 magic value to return when signature is valid is 0x20c13b0b : bytes4(keccak256("isValidSignature(bytes,bytes)") * > This function MAY modify Ethereum's state * @param _hash keccak256 hash that was signed * @param _signature Signature byte array associated with _data * @return magicValue Magic value 0x20c13b0b if the signature is valid and 0x0 otherwise */ function isValidSignature( bytes32 _hash, bytes calldata _signature) external view returns (bytes4 magicValue); } /** * Copyright 2018 ZeroEx Intl. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity 0.7.4; contract LibEIP712 { /***********************************| | Constants | |__________________________________*/ // keccak256( // "EIP712Domain(address verifyingContract)" // ); bytes32 internal constant DOMAIN_SEPARATOR_TYPEHASH = 0x035aff83d86937d35b32e04f0ddc6ff469290eef2f1b692d8a815c89404d4749; // EIP-191 Header string constant internal EIP191_HEADER = "\x19\x01"; /***********************************| | Hashing Function | |__________________________________*/ /** * @dev Calculates EIP712 encoding for a hash struct in this EIP712 Domain. * @param hashStruct The EIP712 hash struct. * @return result EIP712 hash applied to this EIP712 Domain. */ function hashEIP712Message(bytes32 hashStruct) internal view returns (bytes32 result) { return keccak256( abi.encodePacked( EIP191_HEADER, keccak256( abi.encode( DOMAIN_SEPARATOR_TYPEHASH, address(this) ) ), hashStruct )); } } pragma solidity 0.7.4; import "@0xsequence/erc-1155/contracts/interfaces/IERC1155.sol"; interface IERC20Wrapper is IERC1155 { /***********************************| | Deposit Functions | |__________________________________*/ /** * Fallback function * @dev Deposit ETH in this contract to receive wrapped ETH */ receive () external payable; /** * @dev Deposit ERC20 tokens or ETH in this contract to receive wrapped ERC20s * @param _token The addess of the token to deposit in this contract * @param _recipient Address that will receive the ERC-1155 tokens * @param _value The amount of token to deposit in this contract * Note: Users must first approve this contract addres on the contract of the ERC20 to be deposited */ function deposit(address _token, address _recipient, uint256 _value) external payable; /***********************************| | Withdraw Functions | |__________________________________*/ /** * @dev Withdraw wrapped ERC20 tokens in this contract to receive the original ERC20s or ETH * @param _token The addess of the token to withdrww from this contract * @param _to The address where the withdrawn tokens will go to * @param _value The amount of tokens to withdraw */ function withdraw(address _token, address payable _to, uint256 _value) external; /***********************************| | Getter Functions | |__________________________________*/ /** * @notice Return the Meta-ERC20 token ID for the given ERC-20 token address * @param _token ERC-20 token address to get the corresponding Meta-ERC20 token ID * @return tokenID Meta-ERC20 token ID */ function getTokenID(address _token) external view returns (uint256 tokenID); /** * @notice Return the ERC-20 token address for the given Meta-ERC20 token ID * @param _id Meta-ERC20 token ID to get the corresponding ERC-20 token address * @return token ERC-20 token address */ function getIdAddress(uint256 _id) external view returns (address token) ; /** * @notice Returns number of tokens currently registered */ function getNTokens() external view; /***********************************| | OnReceive Functions | |__________________________________*/ /** * @notice Withdraw ERC-20 tokens when receiving their ERC-1155 counterpart * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _value The amount of tokens being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address _operator, address payable _from, uint256 _id, uint256 _value, bytes calldata _data ) external returns(bytes4); /** * @notice Withdraw ERC-20 tokens when receiving their ERC-1155 counterpart * @param _operator The address which called the `safeBatchTransferFrom` function * @param _from The address which previously owned the token * @param _ids An array containing ids of each token being transferred * @param _values An array containing amounts of each token being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived(address _operator, address payable _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "../interfaces/INiftyswapExchange.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC20.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC1155.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC1155TokenReceiver.sol"; import "@0xsequence/erc20-meta-token/contracts/interfaces/IERC20Wrapper.sol"; /** * @notice Will allow users to wrap their ERC-20 into ERC-1155 tokens * and pass their order to niftyswap. All funds will be returned * to original owner and this contact should never hold any funds * outside of a given wrap transaction. * @dev Hardcoding addresses for simplicity, easy to generalize if arguments * are passed in functions, but adds a bit of complexity. */ contract WrapAndNiftyswap { IERC20Wrapper immutable public tokenWrapper; // ERC-20 to ERC-1155 token wrapper contract address immutable public exchange; // Niftyswap exchange to use address immutable public erc20; // ERC-20 used in niftyswap exchange address immutable public erc1155; // ERC-1155 used in niftyswap exchange uint256 immutable internal wrappedTokenID; // ID of the wrapped token bool internal isInNiftyswap; // Whether niftyswap is being called /** * @notice Registers contract addresses */ constructor( address payable _tokenWrapper, address _exchange, address _erc20, address _erc1155 ) public { require( _tokenWrapper != address(0x0) && _exchange != address(0x0) && _erc20 != address(0x0) && _erc1155 != address(0x0), "INVALID CONSTRUCTOR ARGUMENT" ); tokenWrapper = IERC20Wrapper(_tokenWrapper); exchange = _exchange; erc20 = _erc20; erc1155 = _erc1155; // Approve wrapper contract for ERC-20 // NOTE: This could potentially fail in some extreme usage as it's only // set once, but can easily redeploy this contract if that's the case. IERC20(_erc20).approve(_tokenWrapper, 2**256-1); // Store wrapped token ID wrappedTokenID = IERC20Wrapper(_tokenWrapper).getTokenID(_erc20); } /** * @notice Wrap ERC-20 to ERC-1155 and swap them * @dev User must approve this contract for ERC-20 first * @param _maxAmount Maximum amount of ERC-20 user wants to spend * @param _recipient Address where to send tokens * @param _niftyswapOrder Encoded Niftyswap order passed in data field of safeTransferFrom() */ function wrapAndSwap( uint256 _maxAmount, address _recipient, bytes calldata _niftyswapOrder ) external { // Decode niftyswap order INiftyswapExchange.BuyTokensObj memory obj; (, obj) = abi.decode(_niftyswapOrder, (bytes4, INiftyswapExchange.BuyTokensObj)); // Force the recipient to not be set, otherwise wrapped token refunded will be // sent to the user and we won't be able to unwrap it. require( obj.recipient == address(0x0) || obj.recipient == address(this), "WrapAndNiftyswap#wrapAndSwap: ORDER RECIPIENT MUST BE THIS CONTRACT" ); // Pull ERC-20 amount specified in order IERC20(erc20).transferFrom(msg.sender, address(this), _maxAmount); // Wrap ERC-20s tokenWrapper.deposit(erc20, address(this), _maxAmount); // Swap on Niftyswap isInNiftyswap = true; tokenWrapper.safeTransferFrom(address(this), exchange, wrappedTokenID, _maxAmount, _niftyswapOrder); isInNiftyswap = false; // Unwrap ERC-20 and send to receiver, if any received uint256 wrapped_token_amount = tokenWrapper.balanceOf(address(this), wrappedTokenID); if (wrapped_token_amount > 0) { tokenWrapper.withdraw(erc20, payable(_recipient), wrapped_token_amount); } // Transfer tokens purchased IERC1155(erc1155).safeBatchTransferFrom(address(this), _recipient, obj.tokensBoughtIDs, obj.tokensBoughtAmounts, ""); } /** * @notice Accepts only tokenWrapper tokens * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155Received(address, address, uint256, uint256, bytes calldata) external returns(bytes4) { if (msg.sender != address(tokenWrapper)) { revert("WrapAndNiftyswap#onERC1155Received: INVALID_ERC1155_RECEIVED"); } return IERC1155TokenReceiver.onERC1155Received.selector; } /** * @notice If receives tracked ERC-1155, it will send a sell order to niftyswap and unwrap received * wrapped token. The unwrapped tokens will be sent to the sender. * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived( address, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _niftyswapOrder ) external returns(bytes4) { // If coming from niftyswap or wrapped token, ignore if (isInNiftyswap || msg.sender == address(tokenWrapper)){ return IERC1155TokenReceiver.onERC1155BatchReceived.selector; } else if (msg.sender != erc1155) { revert("WrapAndNiftyswap#onERC1155BatchReceived: INVALID_ERC1155_RECEIVED"); } // Decode transfer data INiftyswapExchange.SellTokensObj memory obj; (,obj) = abi.decode(_niftyswapOrder, (bytes4, INiftyswapExchange.SellTokensObj)); require( obj.recipient == address(0x0) || obj.recipient == address(this), "WrapAndNiftyswap#onERC1155BatchReceived: ORDER RECIPIENT MUST BE THIS CONTRACT" ); // Swap on Niftyswap isInNiftyswap = true; IERC1155(msg.sender).safeBatchTransferFrom(address(this), exchange, _ids, _amounts, _niftyswapOrder); isInNiftyswap = false; // Send to recipient the unwrapped ERC-20, if any uint256 wrapped_token_amount = tokenWrapper.balanceOf(address(this), wrappedTokenID); if (wrapped_token_amount > 0) { // Doing it in 2 calls so tx history is more consistent tokenWrapper.withdraw(erc20, payable(address(this)), wrapped_token_amount); IERC20(erc20).transfer(_from, wrapped_token_amount); } return IERC1155TokenReceiver.onERC1155BatchReceived.selector; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import "../../utils/SafeMath.sol"; import "../../interfaces/IERC1155TokenReceiver.sol"; import "../../interfaces/IERC1155.sol"; import "../../utils/Address.sol"; import "../../utils/ERC165.sol"; /** * @dev Implementation of Multi-Token Standard contract. This implementation of the ERC-1155 standard * utilizes the fact that balances of different token ids can be concatenated within individual * uint256 storage slots. This allows the contract to batch transfer tokens more efficiently at * the cost of limiting the maximum token balance each address can hold. This limit is * 2^IDS_BITS_SIZE, which can be adjusted below. In practice, using IDS_BITS_SIZE smaller than 16 * did not lead to major efficiency gains. */ contract ERC1155PackedBalance is IERC1155, ERC165 { using SafeMath for uint256; using Address for address; /***********************************| | Variables and Events | |__________________________________*/ // onReceive function signatures bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61; bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81; // Constants regarding bin sizes for balance packing // IDS_BITS_SIZE **MUST** be a power of 2 (e.g. 2, 4, 8, 16, 32, 64, 128) uint256 internal constant IDS_BITS_SIZE = 32; // Max balance amount in bits per token ID uint256 internal constant IDS_PER_UINT256 = 256 / IDS_BITS_SIZE; // Number of ids per uint256 // Operations for _updateIDBalance enum Operations { Add, Sub } // Token IDs balances ; balances[address][id] => balance (using array instead of mapping for efficiency) mapping (address => mapping(uint256 => uint256)) internal balances; // Operators mapping (address => mapping(address => bool)) internal operators; /***********************************| | Public Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) public override { // Requirements require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155PackedBalance#safeTransferFrom: INVALID_OPERATOR"); require(_to != address(0),"ERC1155PackedBalance#safeTransferFrom: INVALID_RECIPIENT"); // require(_amount <= balances); Not necessary since checked with _viewUpdateBinValue() checks _safeTransferFrom(_from, _to, _id, _amount); _callonERC1155Received(_from, _to, _id, _amount, gasleft(), _data); } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @dev Arrays should be sorted so that all ids in a same storage slot are adjacent (more efficient) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) public override { // Requirements require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155PackedBalance#safeBatchTransferFrom: INVALID_OPERATOR"); require(_to != address(0),"ERC1155PackedBalance#safeBatchTransferFrom: INVALID_RECIPIENT"); _safeBatchTransferFrom(_from, _to, _ids, _amounts); _callonERC1155BatchReceived(_from, _to, _ids, _amounts, gasleft(), _data); } /***********************************| | Internal Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount */ function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount) internal { //Update balances _updateIDBalance(_from, _id, _amount, Operations.Sub); // Subtract amount from sender _updateIDBalance(_to, _id, _amount, Operations.Add); // Add amount to recipient // Emit event emit TransferSingle(msg.sender, _from, _to, _id, _amount); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...) */ function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, uint256 _gasLimit, bytes memory _data) internal { // Check if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received{gas:_gasLimit}(msg.sender, _from, _id, _amount, _data); require(retval == ERC1155_RECEIVED_VALUE, "ERC1155PackedBalance#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE"); } } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @dev Arrays should be sorted so that all ids in a same storage slot are adjacent (more efficient) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type */ function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts) internal { uint256 nTransfer = _ids.length; // Number of transfer to execute require(nTransfer == _amounts.length, "ERC1155PackedBalance#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH"); if (_from != _to && nTransfer > 0) { // Load first bin and index where the token ID balance exists (uint256 bin, uint256 index) = getIDBinIndex(_ids[0]); // Balance for current bin in memory (initialized with first transfer) uint256 balFrom = _viewUpdateBinValue(balances[_from][bin], index, _amounts[0], Operations.Sub); uint256 balTo = _viewUpdateBinValue(balances[_to][bin], index, _amounts[0], Operations.Add); // Last bin updated uint256 lastBin = bin; for (uint256 i = 1; i < nTransfer; i++) { (bin, index) = getIDBinIndex(_ids[i]); // If new bin if (bin != lastBin) { // Update storage balance of previous bin balances[_from][lastBin] = balFrom; balances[_to][lastBin] = balTo; balFrom = balances[_from][bin]; balTo = balances[_to][bin]; // Bin will be the most recent bin lastBin = bin; } // Update memory balance balFrom = _viewUpdateBinValue(balFrom, index, _amounts[i], Operations.Sub); balTo = _viewUpdateBinValue(balTo, index, _amounts[i], Operations.Add); } // Update storage of the last bin visited balances[_from][bin] = balFrom; balances[_to][bin] = balTo; // If transfer to self, just make sure all amounts are valid } else { for (uint256 i = 0; i < nTransfer; i++) { require(balanceOf(_from, _ids[i]) >= _amounts[i], "ERC1155PackedBalance#_safeBatchTransferFrom: UNDERFLOW"); } } // Emit event emit TransferBatch(msg.sender, _from, _to, _ids, _amounts); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...) */ function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, uint256 _gasLimit, bytes memory _data) internal { // Pass data if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived{gas: _gasLimit}(msg.sender, _from, _ids, _amounts, _data); require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155PackedBalance#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE"); } } /***********************************| | Operator Functions | |__________________________________*/ /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external override { // Update operator status operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return isOperator True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) public override view returns (bool isOperator) { return operators[_owner][_operator]; } /***********************************| | Public Balance Functions | |__________________________________*/ /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) public override view returns (uint256) { uint256 bin; uint256 index; //Get bin and index of _id (bin, index) = getIDBinIndex(_id); return getValueInBin(balances[_owner][bin], index); } /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders (sorted owners will lead to less gas usage) * @param _ids ID of the Tokens (sorted ids will lead to less gas usage * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] memory _owners, uint256[] memory _ids) public override view returns (uint256[] memory) { uint256 n_owners = _owners.length; require(n_owners == _ids.length, "ERC1155PackedBalance#balanceOfBatch: INVALID_ARRAY_LENGTH"); // First values (uint256 bin, uint256 index) = getIDBinIndex(_ids[0]); uint256 balance_bin = balances[_owners[0]][bin]; uint256 last_bin = bin; // Initialization uint256[] memory batchBalances = new uint256[](n_owners); batchBalances[0] = getValueInBin(balance_bin, index); // Iterate over each owner and token ID for (uint256 i = 1; i < n_owners; i++) { (bin, index) = getIDBinIndex(_ids[i]); // SLOAD if bin changed for the same owner or if owner changed if (bin != last_bin || _owners[i-1] != _owners[i]) { balance_bin = balances[_owners[i]][bin]; last_bin = bin; } batchBalances[i] = getValueInBin(balance_bin, index); } return batchBalances; } /***********************************| | Packed Balance Functions | |__________________________________*/ /** * @notice Update the balance of a id for a given address * @param _address Address to update id balance * @param _id Id to update balance of * @param _amount Amount to update the id balance * @param _operation Which operation to conduct : * Operations.Add: Add _amount to id balance * Operations.Sub: Substract _amount from id balance */ function _updateIDBalance(address _address, uint256 _id, uint256 _amount, Operations _operation) internal { uint256 bin; uint256 index; // Get bin and index of _id (bin, index) = getIDBinIndex(_id); // Update balance balances[_address][bin] = _viewUpdateBinValue(balances[_address][bin], index, _amount, _operation); } /** * @notice Update a value in _binValues * @param _binValues Uint256 containing values of size IDS_BITS_SIZE (the token balances) * @param _index Index of the value in the provided bin * @param _amount Amount to update the id balance * @param _operation Which operation to conduct : * Operations.Add: Add _amount to value in _binValues at _index * Operations.Sub: Substract _amount from value in _binValues at _index */ function _viewUpdateBinValue(uint256 _binValues, uint256 _index, uint256 _amount, Operations _operation) internal pure returns (uint256 newBinValues) { uint256 shift = IDS_BITS_SIZE * _index; uint256 mask = (uint256(1) << IDS_BITS_SIZE) - 1; if (_operation == Operations.Add) { newBinValues = _binValues + (_amount << shift); require(newBinValues >= _binValues, "ERC1155PackedBalance#_viewUpdateBinValue: OVERFLOW"); require( ((_binValues >> shift) & mask) + _amount < 2**IDS_BITS_SIZE, // Checks that no other id changed "ERC1155PackedBalance#_viewUpdateBinValue: OVERFLOW" ); } else if (_operation == Operations.Sub) { newBinValues = _binValues - (_amount << shift); require(newBinValues <= _binValues, "ERC1155PackedBalance#_viewUpdateBinValue: UNDERFLOW"); require( ((_binValues >> shift) & mask) >= _amount, // Checks that no other id changed "ERC1155PackedBalance#_viewUpdateBinValue: UNDERFLOW" ); } else { revert("ERC1155PackedBalance#_viewUpdateBinValue: INVALID_BIN_WRITE_OPERATION"); // Bad operation } return newBinValues; } /** * @notice Return the bin number and index within that bin where ID is * @param _id Token id * @return bin index (Bin number, ID"s index within that bin) */ function getIDBinIndex(uint256 _id) public pure returns (uint256 bin, uint256 index) { bin = _id / IDS_PER_UINT256; index = _id % IDS_PER_UINT256; return (bin, index); } /** * @notice Return amount in _binValues at position _index * @param _binValues uint256 containing the balances of IDS_PER_UINT256 ids * @param _index Index at which to retrieve amount * @return amount at given _index in _bin */ function getValueInBin(uint256 _binValues, uint256 _index) public pure returns (uint256) { // require(_index < IDS_PER_UINT256) is not required since getIDBinIndex ensures `_index < IDS_PER_UINT256` // Mask to retrieve data for a given binData uint256 mask = (uint256(1) << IDS_BITS_SIZE) - 1; // Shift amount uint256 rightShift = IDS_BITS_SIZE * _index; return (_binValues >> rightShift) & mask; } /***********************************| | ERC165 Functions | |__________________________________*/ /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` and */ function supportsInterface(bytes4 _interfaceID) public override(ERC165, IERC165) virtual pure returns (bool) { if (_interfaceID == type(IERC1155).interfaceId) { return true; } return super.supportsInterface(_interfaceID); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import "../../interfaces/IERC1155Metadata.sol"; import "../../utils/ERC165.sol"; /** * @notice Contract that handles metadata related methods. * @dev Methods assume a deterministic generation of URI based on token IDs. * Methods also assume that URI uses hex representation of token IDs. */ contract ERC1155Metadata is IERC1155Metadata, ERC165 { // URI's default URI prefix string public baseURI; string public name; // set the initial name and base URI constructor(string memory _name, string memory _baseURI) { name = _name; baseURI = _baseURI; } /***********************************| | Metadata Public Functions | |__________________________________*/ /** * @notice A distinct Uniform Resource Identifier (URI) for a given token. * @dev URIs are defined in RFC 3986. * URIs are assumed to be deterministically generated based on token ID * @return URI string */ function uri(uint256 _id) public override view returns (string memory) { return string(abi.encodePacked(baseURI, _uint2str(_id), ".json")); } /***********************************| | Metadata Internal Functions | |__________________________________*/ /** * @notice Will emit default URI log event for corresponding token _id * @param _tokenIDs Array of IDs of tokens to log default URI */ function _logURIs(uint256[] memory _tokenIDs) internal { string memory baseURL = baseURI; string memory tokenURI; for (uint256 i = 0; i < _tokenIDs.length; i++) { tokenURI = string(abi.encodePacked(baseURL, _uint2str(_tokenIDs[i]), ".json")); emit URI(tokenURI, _tokenIDs[i]); } } /** * @notice Will update the base URL of token's URI * @param _newBaseMetadataURI New base URL of token's URI */ function _setBaseMetadataURI(string memory _newBaseMetadataURI) internal { baseURI = _newBaseMetadataURI; } /** * @notice Will update the name of the contract * @param _newName New contract name */ function _setContractName(string memory _newName) internal { name = _newName; } /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` and */ function supportsInterface(bytes4 _interfaceID) public override virtual pure returns (bool) { if (_interfaceID == type(IERC1155Metadata).interfaceId) { return true; } return super.supportsInterface(_interfaceID); } /***********************************| | Utility Internal Functions | |__________________________________*/ /** * @notice Convert uint256 to string * @param _i Unsigned integer to convert to string */ function _uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 ii = _i; uint256 len; // Get number of bytes while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; // Get each individual ASCII while (ii != 0) { bstr[k--] = byte(uint8(48 + ii % 10)); ii /= 10; } // Convert to string return string(bstr); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; interface IERC1155Metadata { event URI(string _uri, uint256 indexed _id); /****************************************| | Functions | |_______________________________________*/ /** * @notice A distinct Uniform Resource Identifier (URI) for a given token. * @dev URIs are defined in RFC 3986. * URIs are assumed to be deterministically generated based on token ID * Token IDs are assumed to be represented in their hex format in URIs * @return URI string */ function uri(uint256 _id) external view returns (string memory); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "../tokens/ERC1155PackedBalance/ERC1155MintBurnPackedBalance.sol"; import "../tokens/ERC1155/ERC1155Metadata.sol"; contract ERC1155MintBurnPackedBalanceMock is ERC1155MintBurnPackedBalance, ERC1155Metadata { // set the initial name and base URI constructor(string memory _name, string memory _baseURI) ERC1155Metadata(_name, _baseURI) {} /***********************************| | ERC165 | |__________________________________*/ /** * @notice Query if a contract implements an interface * @dev Parent contract inheriting multiple contracts with supportsInterface() * need to implement an overriding supportsInterface() function specifying * all inheriting contracts that have a supportsInterface() function. * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` */ function supportsInterface( bytes4 _interfaceID ) public override( ERC1155PackedBalance, ERC1155Metadata ) pure virtual returns (bool) { return super.supportsInterface(_interfaceID); } /***********************************| | Minting Functions | |__________________________________*/ /** * @dev Mint _value of tokens of a given id * @param _to The address to mint tokens to. * @param _id token id to mint * @param _value The amount to be minted * @param _data Data to be passed if receiver is contract */ function mintMock(address _to, uint256 _id, uint256 _value, bytes memory _data) public { _mint(_to, _id, _value, _data); } /** * @dev Mint tokens for each ids in _ids * @param _to The address to mint tokens to. * @param _ids Array of ids to mint * @param _values Array of amount of tokens to mint per id * @param _data Data to be passed if receiver is contract */ function batchMintMock(address _to, uint256[] memory _ids, uint256[] memory _values, bytes memory _data) public { _batchMint(_to, _ids, _values, _data); } /***********************************| | Burning Functions | |__________________________________*/ /** * @dev burn _value of tokens of a given token id * @param _from The address to burn tokens from. * @param _id token id to burn * @param _value The amount to be burned */ function burnMock(address _from, uint256 _id, uint256 _value) public { _burn(_from, _id, _value); } /** * @dev burn _value of tokens of a given token id * @param _from The address to burn tokens from. * @param _ids Array of token ids to burn * @param _values Array of the amount to be burned */ function batchBurnMock(address _from, uint256[] memory _ids, uint256[] memory _values) public { _batchBurn(_from, _ids, _values); } /***********************************| | Unsupported Functions | |__________________________________*/ fallback () external { revert("ERC1155MetaMintBurnPackedBalanceMock: INVALID_METHOD"); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import "./ERC1155PackedBalance.sol"; /** * @dev Multi-Fungible Tokens with minting and burning methods. These methods assume * a parent contract to be executed as they are `internal` functions. */ contract ERC1155MintBurnPackedBalance is ERC1155PackedBalance { /****************************************| | Minting Functions | |_______________________________________*/ /** * @notice Mint _amount of tokens of a given id * @param _to The address to mint tokens to * @param _id Token id to mint * @param _amount The amount to be minted * @param _data Data to pass if receiver is contract */ function _mint(address _to, uint256 _id, uint256 _amount, bytes memory _data) internal { //Add _amount _updateIDBalance(_to, _id, _amount, Operations.Add); // Add amount to recipient // Emit event emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount); // Calling onReceive method if recipient is contract _callonERC1155Received(address(0x0), _to, _id, _amount, gasleft(), _data); } /** * @notice Mint tokens for each (_ids[i], _amounts[i]) pair * @param _to The address to mint tokens to * @param _ids Array of ids to mint * @param _amounts Array of amount of tokens to mint per id * @param _data Data to pass if receiver is contract */ function _batchMint(address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) internal { require(_ids.length == _amounts.length, "ERC1155MintBurnPackedBalance#_batchMint: INVALID_ARRAYS_LENGTH"); if (_ids.length > 0) { // Load first bin and index where the token ID balance exists (uint256 bin, uint256 index) = getIDBinIndex(_ids[0]); // Balance for current bin in memory (initialized with first transfer) uint256 balTo = _viewUpdateBinValue(balances[_to][bin], index, _amounts[0], Operations.Add); // Number of transfer to execute uint256 nTransfer = _ids.length; // Last bin updated uint256 lastBin = bin; for (uint256 i = 1; i < nTransfer; i++) { (bin, index) = getIDBinIndex(_ids[i]); // If new bin if (bin != lastBin) { // Update storage balance of previous bin balances[_to][lastBin] = balTo; balTo = balances[_to][bin]; // Bin will be the most recent bin lastBin = bin; } // Update memory balance balTo = _viewUpdateBinValue(balTo, index, _amounts[i], Operations.Add); } // Update storage of the last bin visited balances[_to][bin] = balTo; } // //Emit event emit TransferBatch(msg.sender, address(0x0), _to, _ids, _amounts); // Calling onReceive method if recipient is contract _callonERC1155BatchReceived(address(0x0), _to, _ids, _amounts, gasleft(), _data); } /****************************************| | Burning Functions | |_______________________________________*/ /** * @notice Burn _amount of tokens of a given token id * @param _from The address to burn tokens from * @param _id Token id to burn * @param _amount The amount to be burned */ function _burn(address _from, uint256 _id, uint256 _amount) internal { // Substract _amount _updateIDBalance(_from, _id, _amount, Operations.Sub); // Emit event emit TransferSingle(msg.sender, _from, address(0x0), _id, _amount); } /** * @notice Burn tokens of given token id for each (_ids[i], _amounts[i]) pair * @dev This batchBurn method does not implement the most efficient way of updating * balances to reduce the potential bug surface as this function is expected to * be less common than transfers. EIP-2200 makes this method significantly * more efficient already for packed balances. * @param _from The address to burn tokens from * @param _ids Array of token ids to burn * @param _amounts Array of the amount to be burned */ function _batchBurn(address _from, uint256[] memory _ids, uint256[] memory _amounts) internal { // Number of burning to execute uint256 nBurn = _ids.length; require(nBurn == _amounts.length, "ERC1155MintBurnPackedBalance#batchBurn: INVALID_ARRAYS_LENGTH"); // Executing all burning for (uint256 i = 0; i < nBurn; i++) { // Update storage balance _updateIDBalance(_from, _ids[i], _amounts[i], Operations.Sub); // Add amount to recipient } // Emit batch burn event emit TransferBatch(msg.sender, _from, address(0x0), _ids, _amounts); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@0xsequence/erc-1155/contracts/mocks/ERC1155MintBurnPackedBalanceMock.sol"; contract ERC1155PackedBalanceMock is ERC1155MintBurnPackedBalanceMock { constructor() ERC1155MintBurnPackedBalanceMock("TestERC1155", "") {} } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "../tokens/ERC1155/ERC1155MintBurn.sol"; import "../tokens/ERC1155/ERC1155Metadata.sol"; contract ERC1155MintBurnMock is ERC1155MintBurn, ERC1155Metadata { // set the initial name and base URI constructor(string memory _name, string memory _baseURI) ERC1155Metadata(_name, _baseURI) {} /** * @notice Query if a contract implements an interface * @dev Parent contract inheriting multiple contracts with supportsInterface() * need to implement an overriding supportsInterface() function specifying * all inheriting contracts that have a supportsInterface() function. * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` */ function supportsInterface( bytes4 _interfaceID ) public override( ERC1155, ERC1155Metadata ) pure virtual returns (bool) { return super.supportsInterface(_interfaceID); } /***********************************| | Minting Functions | |__________________________________*/ /** * @dev Mint _value of tokens of a given id * @param _to The address to mint tokens to. * @param _id token id to mint * @param _value The amount to be minted * @param _data Data to be passed if receiver is contract */ function mintMock(address _to, uint256 _id, uint256 _value, bytes memory _data) public { super._mint(_to, _id, _value, _data); } /** * @dev Mint tokens for each ids in _ids * @param _to The address to mint tokens to. * @param _ids Array of ids to mint * @param _values Array of amount of tokens to mint per id * @param _data Data to be passed if receiver is contract */ function batchMintMock(address _to, uint256[] memory _ids, uint256[] memory _values, bytes memory _data) public { super._batchMint(_to, _ids, _values, _data); } /***********************************| | Burning Functions | |__________________________________*/ /** * @dev burn _value of tokens of a given token id * @param _from The address to burn tokens from. * @param _id token id to burn * @param _value The amount to be burned */ function burnMock(address _from, uint256 _id, uint256 _value) public { super._burn(_from, _id, _value); } /** * @dev burn _value of tokens of a given token id * @param _from The address to burn tokens from. * @param _ids Array of token ids to burn * @param _values Array of the amount to be burned */ function batchBurnMock(address _from, uint256[] memory _ids, uint256[] memory _values) public { super._batchBurn(_from, _ids, _values); } /***********************************| | Unsupported Functions | |__________________________________*/ fallback () virtual external { revert("ERC1155MetaMintBurnMock: INVALID_METHOD"); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@0xsequence/erc-1155/contracts/mocks/ERC1155MintBurnMock.sol"; import "../interfaces/IERC2981.sol"; contract ERC1155RoyaltyMock is ERC1155MintBurnMock { constructor() ERC1155MintBurnMock("TestERC1155", "") {} using SafeMath for uint256; uint256 public royaltyFee; address public royaltyRecipient; uint256 public royaltyFee666; address public royaltyRecipient666; /** * @notice Called with the sale price to determine how much royalty * is owed and to whom. * @param _tokenId - the NFT asset queried for royalty information * @param _salePrice - the sale price of the NFT asset specified by _tokenId * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for _salePrice */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) { if (_tokenId == 666) { uint256 fee = _salePrice.mul(royaltyFee666).div(10000); return (royaltyRecipient666, fee); } else { uint256 fee = _salePrice.mul(royaltyFee).div(10000); return (royaltyRecipient, fee); } } function setFee(uint256 _fee) public { require(_fee < 10000, "FEE IS TOO HIGH"); royaltyFee = _fee; } function set666Fee(uint256 _fee) public { require(_fee < 10000, "FEE IS TOO HIGH"); royaltyFee666 = _fee; } function setFeeRecipient(address _recipient) public { royaltyRecipient = _recipient; } function set666FeeRecipient(address _recipient) public { royaltyRecipient666 = _recipient; } bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` and */ function supportsInterface(bytes4 _interfaceID) public override(ERC1155MintBurnMock) virtual pure returns (bool) { // Should be 0x2a55205a if (_interfaceID == _INTERFACE_ID_ERC2981) { return true; } return super.supportsInterface(_interfaceID); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import "@0xsequence/erc-1155/contracts/interfaces/IERC165.sol"; /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981 is IERC165 { /** * @notice Called with the sale price to determine how much royalty * is owed and to whom. * @param _tokenId - the NFT asset queried for royalty information * @param _salePrice - the sale price of the NFT asset specified by _tokenId * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for _salePrice */ function royaltyInfo( uint256 _tokenId, uint256 _salePrice ) external view returns ( address receiver, uint256 royaltyAmount ); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "../interfaces/INiftyswapExchange20.sol"; import "../utils/ReentrancyGuard.sol"; import "../utils/DelegatedOwnable.sol"; import "../interfaces/IERC2981.sol"; import "../interfaces/IERC1155Metadata.sol"; import "../interfaces/IDelegatedERC1155Metadata.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC20.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC165.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC1155.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC1155TokenReceiver.sol"; import "@0xsequence/erc-1155/contracts/tokens/ERC1155/ERC1155MintBurn.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; /** * This Uniswap-like implementation supports ERC-1155 standard tokens * with an ERC-20 based token used as a currency instead of Ether. * * Liquidity tokens are also ERC-1155 tokens you can find the ERC-1155 * implementation used here: * https://github.com/horizon-games/multi-token-standard/tree/master/contracts/tokens/ERC1155 * * @dev Like Uniswap, tokens with 0 decimals and low supply are susceptible to significant rounding * errors when it comes to removing liquidity, possibly preventing them to be withdrawn without * some collaboration between liquidity providers. * * @dev ERC-777 tokens may be vulnerable if used as currency in Niftyswap. Please review the code * carefully before using it with ERC-777 tokens. */ contract NiftyswapExchange20 is ReentrancyGuard, ERC1155MintBurn, INiftyswapExchange20, IERC1155Metadata, DelegatedOwnable { using SafeMath for uint256; /***********************************| | Variables & Constants | |__________________________________*/ // Variables IERC1155 internal immutable token; // address of the ERC-1155 token contract address internal immutable currency; // address of the ERC-20 currency used for exchange address internal immutable factory; // address for the factory that created this contract uint256 internal immutable FEE_MULTIPLIER; // multiplier that calculates the LP fee (1.0%) // Royalty variables bool internal immutable IS_ERC2981; // whether token contract supports ERC-2981 uint256 internal globalRoyaltyFee; // global royalty fee multiplier if ERC2981 is not used address internal globalRoyaltyRecipient; // global royalty fee recipient if ERC2981 is not used // Mapping variables mapping(uint256 => uint256) internal totalSupplies; // Liquidity pool token supply per Token id mapping(uint256 => uint256) internal currencyReserves; // currency Token reserve per Token id mapping(address => uint256) internal royaltiesNumerator; // Mapping tracking how much royalties can be claimed per address uint256 internal constant ROYALTIES_DENOMINATOR = 10000; uint256 internal constant MAX_ROYALTY = ROYALTIES_DENOMINATOR / 4; /***********************************| | Constructor | |__________________________________*/ /** * @notice Create instance of exchange contract with respective token and currency token * @dev If token supports ERC-2981, then royalty fee will be queried per token on the * token contract. Else royalty fee will need to be manually set by admin. * @param _tokenAddr The address of the ERC-1155 Token * @param _currencyAddr The address of the ERC-20 currency Token * @param _currencyAddr Address of the admin, which should be the same as the factory owner * @param _lpFee Fee that will go to LPs. * Number between 0 and 1000, where 10 is 1.0% and 100 is 10%. */ constructor(address _tokenAddr, address _currencyAddr, uint256 _lpFee) DelegatedOwnable(msg.sender) { require( _tokenAddr != address(0) && _currencyAddr != address(0), "NE20#1" // NiftyswapExchange20#constructor:INVALID_INPUT ); require( _lpFee >= 0 && _lpFee <= 1000, "NE20#2" // NiftyswapExchange20#constructor:INVALID_LP_FEE ); factory = msg.sender; token = IERC1155(_tokenAddr); currency = _currencyAddr; FEE_MULTIPLIER = 1000 - _lpFee; // If global royalty, lets check for ERC-2981 support try IERC1155(_tokenAddr).supportsInterface(type(IERC2981).interfaceId) returns (bool supported) { IS_ERC2981 = supported; } catch {} } /***********************************| | Metadata Functions | |__________________________________*/ /** @notice A distinct Uniform Resource Identifier (URI) for a given token. @dev URIs are defined in RFC 3986. The URI MUST point to a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema". @return URI string */ function uri(uint256 _id) external override view returns (string memory) { return IDelegatedERC1155Metadata(factory).metadataProvider().uri(_id); } /***********************************| | Exchange Functions | |__________________________________*/ /** * @notice Convert currency tokens to Tokens _id and transfers Tokens to recipient. */ function _currencyToToken( uint256[] memory _tokenIds, uint256[] memory _tokensBoughtAmounts, uint256 _maxCurrency, uint256 _deadline, address _recipient ) internal nonReentrant() returns (uint256[] memory currencySold) { // Input validation require(_deadline >= block.timestamp, "NE20#3"); // NiftyswapExchange20#_currencyToToken: DEADLINE_EXCEEDED // Number of Token IDs to deposit uint256 nTokens = _tokenIds.length; uint256 totalRefundCurrency = _maxCurrency; // Initialize variables currencySold = new uint256[](nTokens); // Amount of currency tokens sold per ID // Get token reserves uint256[] memory tokenReserves = _getTokenReserves(_tokenIds); // Assumes the currency Tokens are already received by contract, but not // the Tokens Ids // Remove liquidity for each Token ID in _tokenIds for (uint256 i = 0; i < nTokens; i++) { // Store current id and amount from argument arrays uint256 idBought = _tokenIds[i]; uint256 amountBought = _tokensBoughtAmounts[i]; uint256 tokenReserve = tokenReserves[i]; require(amountBought > 0, "NE20#4"); // NiftyswapExchange20#_currencyToToken: NULL_TOKENS_BOUGHT // Load currency token and Token _id reserves uint256 currencyReserve = currencyReserves[idBought]; // Get amount of currency tokens to send for purchase // Neither reserves amount have been changed so far in this transaction, so // no adjustment to the inputs is needed uint256 currencyAmount = getBuyPrice(amountBought, currencyReserve, tokenReserve); // If royalty, increase amount buyer will need to pay after LP fees were calculated // Note: Royalty will be a bit higher since LF fees are added first (address royaltyRecipient, uint256 royaltyAmount) = getRoyaltyInfo(idBought, currencyAmount); if (royaltyAmount > 0) { royaltiesNumerator[royaltyRecipient] = royaltiesNumerator[royaltyRecipient].add(royaltyAmount.mul(ROYALTIES_DENOMINATOR)); } // Calculate currency token amount to refund (if any) where whatever is not used will be returned // Will throw if total cost exceeds _maxCurrency totalRefundCurrency = totalRefundCurrency.sub(currencyAmount).sub(royaltyAmount); // Append Token id, Token id amount and currency token amount to tracking arrays currencySold[i] = currencyAmount.add(royaltyAmount); // Update individual currency reseve amount (royalty is not added to liquidity) currencyReserves[idBought] = currencyReserve.add(currencyAmount); } // Send Tokens all tokens purchased token.safeBatchTransferFrom(address(this), _recipient, _tokenIds, _tokensBoughtAmounts, ""); // Refund currency token if any if (totalRefundCurrency > 0) { TransferHelper.safeTransfer(currency, _recipient, totalRefundCurrency); } return currencySold; } /** * @dev Pricing function used for converting between currency token to Tokens. * @param _assetBoughtAmount Amount of Tokens being bought. * @param _assetSoldReserve Amount of currency tokens in exchange reserves. * @param _assetBoughtReserve Amount of Tokens (output type) in exchange reserves. * @return price Amount of currency tokens to send to Niftyswap. */ function getBuyPrice( uint256 _assetBoughtAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) override public view returns (uint256 price) { // Reserves must not be empty require(_assetSoldReserve > 0 && _assetBoughtReserve > 0, "NE20#5"); // NiftyswapExchange20#getBuyPrice: EMPTY_RESERVE // Calculate price with fee uint256 numerator = _assetSoldReserve.mul(_assetBoughtAmount).mul(1000); uint256 denominator = (_assetBoughtReserve.sub(_assetBoughtAmount)).mul(FEE_MULTIPLIER); (price, ) = divRound(numerator, denominator); return price; // Will add 1 if rounding error } /** * @dev Pricing function used for converting Tokens to currency token (including royalty fee) * @param _tokenId Id ot token being sold * @param _assetBoughtAmount Amount of Tokens being bought. * @param _assetSoldReserve Amount of currency tokens in exchange reserves. * @param _assetBoughtReserve Amount of Tokens (output type) in exchange reserves. * @return price Amount of currency tokens to send to Niftyswap. */ function getBuyPriceWithRoyalty( uint256 _tokenId, uint256 _assetBoughtAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) override public view returns (uint256 price) { uint256 cost = getBuyPrice(_assetBoughtAmount, _assetSoldReserve, _assetBoughtReserve); (, uint256 royaltyAmount) = getRoyaltyInfo(_tokenId, cost); return cost.add(royaltyAmount); } /** * @notice Convert Tokens _id to currency tokens and transfers Tokens to recipient. * @dev User specifies EXACT Tokens _id sold and MINIMUM currency tokens received. * @dev Assumes that all trades will be valid, or the whole tx will fail * @dev Sorting _tokenIds is mandatory for efficient way of preventing duplicated IDs (which would lead to errors) * @param _tokenIds Array of Token IDs that are sold * @param _tokensSoldAmounts Array of Amount of Tokens sold for each id in _tokenIds. * @param _minCurrency Minimum amount of currency tokens to receive * @param _deadline Timestamp after which this transaction will be reverted * @param _recipient The address that receives output currency tokens. * @param _extraFeeRecipients Array of addresses that will receive extra fee * @param _extraFeeAmounts Array of amounts of currency that will be sent as extra fee * @return currencyBought How much currency was actually purchased. */ function _tokenToCurrency( uint256[] memory _tokenIds, uint256[] memory _tokensSoldAmounts, uint256 _minCurrency, uint256 _deadline, address _recipient, address[] memory _extraFeeRecipients, uint256[] memory _extraFeeAmounts ) internal nonReentrant() returns (uint256[] memory currencyBought) { // Number of Token IDs to deposit uint256 nTokens = _tokenIds.length; // Input validation require(_deadline >= block.timestamp, "NE20#6"); // NiftyswapExchange20#_tokenToCurrency: DEADLINE_EXCEEDED // Initialize variables uint256 totalCurrency = 0; // Total amount of currency tokens to transfer currencyBought = new uint256[](nTokens); // Get token reserves uint256[] memory tokenReserves = _getTokenReserves(_tokenIds); // Assumes the Tokens ids are already received by contract, but not // the Tokens Ids. Will return cards not sold if invalid price. // Remove liquidity for each Token ID in _tokenIds for (uint256 i = 0; i < nTokens; i++) { // Store current id and amount from argument arrays uint256 idSold = _tokenIds[i]; uint256 amountSold = _tokensSoldAmounts[i]; uint256 tokenReserve = tokenReserves[i]; // If 0 tokens send for this ID, revert require(amountSold > 0, "NE20#7"); // NiftyswapExchange20#_tokenToCurrency: NULL_TOKENS_SOLD // Load currency token and Token _id reserves uint256 currencyReserve = currencyReserves[idSold]; // Get amount of currency that will be received // Need to sub amountSold because tokens already added in reserve, which would bias the calculation // Don't need to add it for currencyReserve because the amount is added after this calculation uint256 currencyAmount = getSellPrice(amountSold, tokenReserve.sub(amountSold), currencyReserve); // If royalty, substract amount seller will receive after LP fees were calculated // Note: Royalty will be a bit lower since LF fees are substracted first (address royaltyRecipient, uint256 royaltyAmount) = getRoyaltyInfo(idSold, currencyAmount); if (royaltyAmount > 0) { royaltiesNumerator[royaltyRecipient] = royaltiesNumerator[royaltyRecipient].add(royaltyAmount.mul(ROYALTIES_DENOMINATOR)); } // Increase total amount of currency to receive (minus royalty to pay) totalCurrency = totalCurrency.add(currencyAmount.sub(royaltyAmount)); // Update individual currency reseve amount currencyReserves[idSold] = currencyReserve.sub(currencyAmount); // Append Token id, Token id amount and currency token amount to tracking arrays currencyBought[i] = currencyAmount.sub(royaltyAmount); } // Set the extra fees aside to recipients after sale for (uint256 i = 0; i < _extraFeeAmounts.length; i++) { if (_extraFeeAmounts[i] > 0) { totalCurrency = totalCurrency.sub(_extraFeeAmounts[i]); royaltiesNumerator[_extraFeeRecipients[i]] = royaltiesNumerator[_extraFeeRecipients[i]].add(_extraFeeAmounts[i].mul(ROYALTIES_DENOMINATOR)); } } // If minCurrency is not met require(totalCurrency >= _minCurrency, "NE20#8"); // NiftyswapExchange20#_tokenToCurrency: INSUFFICIENT_CURRENCY_AMOUNT // Transfer currency here TransferHelper.safeTransfer(currency, _recipient, totalCurrency); return currencyBought; } /** * @dev Pricing function used for converting Tokens to currency token. * @param _assetSoldAmount Amount of Tokens being sold. * @param _assetSoldReserve Amount of Tokens in exchange reserves. * @param _assetBoughtReserve Amount of currency tokens in exchange reserves. * @return price Amount of currency tokens to receive from Niftyswap. */ function getSellPrice( uint256 _assetSoldAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) override public view returns (uint256 price) { //Reserves must not be empty require(_assetSoldReserve > 0 && _assetBoughtReserve > 0, "NE20#9"); // NiftyswapExchange20#getSellPrice: EMPTY_RESERVE // Calculate amount to receive (with fee) before royalty uint256 _assetSoldAmount_withFee = _assetSoldAmount.mul(FEE_MULTIPLIER); uint256 numerator = _assetSoldAmount_withFee.mul(_assetBoughtReserve); uint256 denominator = _assetSoldReserve.mul(1000).add(_assetSoldAmount_withFee); return numerator / denominator; //Rounding errors will favor Niftyswap, so nothing to do } /** * @dev Pricing function used for converting Tokens to currency token (including royalty fee) * @param _tokenId Id ot token being sold * @param _assetSoldAmount Amount of Tokens being sold. * @param _assetSoldReserve Amount of Tokens in exchange reserves. * @param _assetBoughtReserve Amount of currency tokens in exchange reserves. * @return price Amount of currency tokens to receive from Niftyswap. */ function getSellPriceWithRoyalty( uint256 _tokenId, uint256 _assetSoldAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) override public view returns (uint256 price) { uint256 sellAmount = getSellPrice(_assetSoldAmount, _assetSoldReserve, _assetBoughtReserve); (, uint256 royaltyAmount) = getRoyaltyInfo(_tokenId, sellAmount); return sellAmount.sub(royaltyAmount); } /***********************************| | Liquidity Functions | |__________________________________*/ /** * @notice Deposit less than max currency tokens && exact Tokens (token ID) at current ratio to mint liquidity pool tokens. * @dev min_liquidity does nothing when total liquidity pool token supply is 0. * @dev Assumes that sender approved this contract on the currency * @dev Sorting _tokenIds is mandatory for efficient way of preventing duplicated IDs (which would lead to errors) * @param _provider Address that provides liquidity to the reserve * @param _tokenIds Array of Token IDs where liquidity is added * @param _tokenAmounts Array of amount of Tokens deposited corresponding to each ID provided in _tokenIds * @param _maxCurrency Array of maximum number of tokens deposited for each ID provided in _tokenIds. * Deposits max amount if total liquidity pool token supply is 0. * @param _deadline Timestamp after which this transaction will be reverted */ function _addLiquidity( address _provider, uint256[] memory _tokenIds, uint256[] memory _tokenAmounts, uint256[] memory _maxCurrency, uint256 _deadline) internal nonReentrant() { // Requirements require(_deadline >= block.timestamp, "NE20#10"); // NiftyswapExchange20#_addLiquidity: DEADLINE_EXCEEDED // Initialize variables uint256 nTokens = _tokenIds.length; // Number of Token IDs to deposit uint256 totalCurrency = 0; // Total amount of currency tokens to transfer // Initialize arrays uint256[] memory liquiditiesToMint = new uint256[](nTokens); uint256[] memory currencyAmounts = new uint256[](nTokens); // Get token reserves uint256[] memory tokenReserves = _getTokenReserves(_tokenIds); // Assumes tokens _ids are deposited already, but not currency tokens // as this is calculated and executed below. // Loop over all Token IDs to deposit for (uint256 i = 0; i < nTokens; i ++) { // Store current id and amount from argument arrays uint256 tokenId = _tokenIds[i]; uint256 amount = _tokenAmounts[i]; // Check if input values are acceptable require(_maxCurrency[i] > 0, "NE20#11"); // NiftyswapExchange20#_addLiquidity: NULL_MAX_CURRENCY require(amount > 0, "NE20#12"); // NiftyswapExchange20#_addLiquidity: NULL_TOKENS_AMOUNT // Current total liquidity calculated in currency token uint256 totalLiquidity = totalSupplies[tokenId]; // When reserve for this token already exists if (totalLiquidity > 0) { // Load currency token and Token reserve's supply of Token id uint256 currencyReserve = currencyReserves[tokenId]; // Amount not yet in reserve uint256 tokenReserve = tokenReserves[i]; /** * Amount of currency tokens to send to token id reserve: * X/Y = dx/dy * dx = X*dy/Y * where * X: currency total liquidity * Y: Token _id total liquidity (before tokens were received) * dy: Amount of token _id deposited * dx: Amount of currency to deposit * * Adding .add(1) if rounding errors so to not favor users incorrectly */ (uint256 currencyAmount, bool rounded) = divRound(amount.mul(currencyReserve), tokenReserve.sub(amount)); require(_maxCurrency[i] >= currencyAmount, "NE20#13"); // NiftyswapExchange20#_addLiquidity: MAX_CURRENCY_AMOUNT_EXCEEDED // Update currency reserve size for Token id before transfer currencyReserves[tokenId] = currencyReserve.add(currencyAmount); // Update totalCurrency totalCurrency = totalCurrency.add(currencyAmount); // Proportion of the liquidity pool to give to current liquidity provider // If rounding error occured, round down to favor previous liquidity providers // See https://github.com/0xsequence/niftyswap/issues/19 liquiditiesToMint[i] = (currencyAmount.sub(rounded ? 1 : 0)).mul(totalLiquidity) / currencyReserve; currencyAmounts[i] = currencyAmount; // Mint liquidity ownership tokens and increase liquidity supply accordingly totalSupplies[tokenId] = totalLiquidity.add(liquiditiesToMint[i]); } else { uint256 maxCurrency = _maxCurrency[i]; // Otherwise rounding error could end up being significant on second deposit require(maxCurrency >= 1000, "NE20#14"); // NiftyswapExchange20#_addLiquidity: INVALID_CURRENCY_AMOUNT // Update currency reserve size for Token id before transfer currencyReserves[tokenId] = maxCurrency; // Update totalCurrency totalCurrency = totalCurrency.add(maxCurrency); // Initial liquidity is amount deposited (Incorrect pricing will be arbitraged) // uint256 initialLiquidity = _maxCurrency; totalSupplies[tokenId] = maxCurrency; // Liquidity to mints liquiditiesToMint[i] = maxCurrency; currencyAmounts[i] = maxCurrency; } } // Transfer all currency to this contract TransferHelper.safeTransferFrom(currency, _provider, address(this), totalCurrency); // Mint liquidity pool tokens _batchMint(_provider, _tokenIds, liquiditiesToMint, ""); // Emit event emit LiquidityAdded(_provider, _tokenIds, _tokenAmounts, currencyAmounts); } /** * @dev Convert pool participation into amounts of token and currency. * @dev Rounding error of the asset with lower resolution is traded for the other asset. * @param _amountPool Participation to be converted to tokens and currency. * @param _tokenReserve Amount of tokens on the AMM reserve. * @param _currencyReserve Amount of currency on the AMM reserve. * @param _totalLiquidity Total liquidity on the pool. * * @return currencyAmount Currency corresponding to pool amount plus rounded tokens. * @return tokenAmount Token corresponding to pool amount plus rounded currency. */ function _toRoundedLiquidity( uint256 _tokenId, uint256 _amountPool, uint256 _tokenReserve, uint256 _currencyReserve, uint256 _totalLiquidity ) internal view returns ( uint256 currencyAmount, uint256 tokenAmount, uint256 soldTokenNumerator, uint256 boughtCurrencyNumerator, address royaltyRecipient, uint256 royaltyNumerator ) { uint256 currencyNumerator = _amountPool.mul(_currencyReserve); uint256 tokenNumerator = _amountPool.mul(_tokenReserve); // Convert all tokenProduct rest to currency soldTokenNumerator = tokenNumerator % _totalLiquidity; if (soldTokenNumerator != 0) { // The trade happens "after" funds are out of the pool // so we need to remove these funds before computing the rate uint256 virtualTokenReserve = _tokenReserve.sub(tokenNumerator / _totalLiquidity).mul(_totalLiquidity); uint256 virtualCurrencyReserve = _currencyReserve.sub(currencyNumerator / _totalLiquidity).mul(_totalLiquidity); // Skip process if any of the two reserves is left empty // this step is important to avoid an error withdrawing all left liquidity if (virtualCurrencyReserve != 0 && virtualTokenReserve != 0) { boughtCurrencyNumerator = getSellPrice(soldTokenNumerator, virtualTokenReserve, virtualCurrencyReserve); // Discount royalty currency (royaltyRecipient, royaltyNumerator) = getRoyaltyInfo(_tokenId, boughtCurrencyNumerator); boughtCurrencyNumerator = boughtCurrencyNumerator.sub(royaltyNumerator); currencyNumerator = currencyNumerator.add(boughtCurrencyNumerator); // Add royalty numerator (needs to be converted to ROYALTIES_DENOMINATOR) royaltyNumerator = royaltyNumerator.mul(ROYALTIES_DENOMINATOR) / _totalLiquidity; } } // Calculate amounts currencyAmount = currencyNumerator / _totalLiquidity; tokenAmount = tokenNumerator / _totalLiquidity; } /** * @dev Burn liquidity pool tokens to withdraw currency && Tokens at current ratio. * @dev Sorting _tokenIds is mandatory for efficient way of preventing duplicated IDs (which would lead to errors) * @param _provider Address that removes liquidity to the reserve * @param _tokenIds Array of Token IDs where liquidity is removed * @param _poolTokenAmounts Array of Amount of liquidity pool tokens burned for each Token id in _tokenIds. * @param _minCurrency Minimum currency withdrawn for each Token id in _tokenIds. * @param _minTokens Minimum Tokens id withdrawn for each Token id in _tokenIds. * @param _deadline Timestamp after which this transaction will be reverted */ function _removeLiquidity( address _provider, uint256[] memory _tokenIds, uint256[] memory _poolTokenAmounts, uint256[] memory _minCurrency, uint256[] memory _minTokens, uint256 _deadline) internal nonReentrant() { // Input validation require(_deadline > block.timestamp, "NE20#15"); // NiftyswapExchange20#_removeLiquidity: DEADLINE_EXCEEDED // Initialize variables uint256 nTokens = _tokenIds.length; // Number of Token IDs to deposit uint256 totalCurrency = 0; // Total amount of currency to transfer uint256[] memory tokenAmounts = new uint256[](nTokens); // Amount of Tokens to transfer for each id // Structs contain most information for the event // notice: tokenAmounts and tokenIds are absent because we already // either have those arrays constructed or we need to construct them for other reasons LiquidityRemovedEventObj[] memory eventObjs = new LiquidityRemovedEventObj[](nTokens); // Get token reserves uint256[] memory tokenReserves = _getTokenReserves(_tokenIds); // Assumes NIFTY liquidity tokens are already received by contract, but not // the currency nor the Tokens Ids // Remove liquidity for each Token ID in _tokenIds for (uint256 i = 0; i < nTokens; i++) { // Store current id and amount from argument arrays uint256 id = _tokenIds[i]; uint256 amountPool = _poolTokenAmounts[i]; // Load total liquidity pool token supply for Token _id uint256 totalLiquidity = totalSupplies[id]; require(totalLiquidity > 0, "NE20#16"); // NiftyswapExchange20#_removeLiquidity: NULL_TOTAL_LIQUIDITY // Load currency and Token reserve's supply of Token id uint256 currencyReserve = currencyReserves[id]; // Calculate amount to withdraw for currency and Token _id uint256 currencyAmount; uint256 tokenAmount; { uint256 tokenReserve = tokenReserves[i]; uint256 soldTokenNumerator; uint256 boughtCurrencyNumerator; address royaltyRecipient; uint256 royaltyNumerator; ( currencyAmount, tokenAmount, soldTokenNumerator, boughtCurrencyNumerator, royaltyRecipient, royaltyNumerator ) = _toRoundedLiquidity(id, amountPool, tokenReserve, currencyReserve, totalLiquidity); // Add royalties royaltiesNumerator[royaltyRecipient] = royaltiesNumerator[royaltyRecipient].add(royaltyNumerator); // Add trade info to event eventObjs[i].soldTokenNumerator = soldTokenNumerator; eventObjs[i].boughtCurrencyNumerator = boughtCurrencyNumerator; eventObjs[i].totalSupply = totalLiquidity; } // Verify if amounts to withdraw respect minimums specified require(currencyAmount >= _minCurrency[i], "NE20#17"); // NiftyswapExchange20#_removeLiquidity: INSUFFICIENT_CURRENCY_AMOUNT require(tokenAmount >= _minTokens[i], "NE20#18"); // NiftyswapExchange20#_removeLiquidity: INSUFFICIENT_TOKENS // Update total liquidity pool token supply of Token _id totalSupplies[id] = totalLiquidity.sub(amountPool); // Update currency reserve size for Token id currencyReserves[id] = currencyReserve.sub(currencyAmount); // Update totalCurrency and tokenAmounts totalCurrency = totalCurrency.add(currencyAmount); tokenAmounts[i] = tokenAmount; eventObjs[i].currencyAmount = currencyAmount; } // Burn liquidity pool tokens for offchain supplies _batchBurn(address(this), _tokenIds, _poolTokenAmounts); // Transfer total currency and all Tokens ids TransferHelper.safeTransfer(currency, _provider, totalCurrency); token.safeBatchTransferFrom(address(this), _provider, _tokenIds, tokenAmounts, ""); // Emit event emit LiquidityRemoved(_provider, _tokenIds, tokenAmounts, eventObjs); } /***********************************| | Receiver Methods Handler | |__________________________________*/ // Method signatures for onReceive control logic // bytes4(keccak256( // "_tokenToCurrency(uint256[],uint256[],uint256,uint256,address,address[],uint256[])" // )); bytes4 internal constant SELLTOKENS_SIG = 0xade79c7a; // bytes4(keccak256( // "_addLiquidity(address,uint256[],uint256[],uint256[],uint256)" // )); bytes4 internal constant ADDLIQUIDITY_SIG = 0x82da2b73; // bytes4(keccak256( // "_removeLiquidity(address,uint256[],uint256[],uint256[],uint256[],uint256)" // )); bytes4 internal constant REMOVELIQUIDITY_SIG = 0x5c0bf259; // bytes4(keccak256( // "DepositTokens()" // )); bytes4 internal constant DEPOSIT_SIG = 0xc8c323f9; /***********************************| | Buying Tokens | |__________________________________*/ /** * @notice Convert currency tokens to Tokens _id and transfers Tokens to recipient. * @dev User specifies MAXIMUM inputs (_maxCurrency) and EXACT outputs. * @dev Assumes that all trades will be successful, or revert the whole tx * @dev Exceeding currency tokens sent will be refunded to recipient * @dev Sorting IDs is mandatory for efficient way of preventing duplicated IDs (which would lead to exploit) * @param _tokenIds Array of Tokens ID that are bought * @param _tokensBoughtAmounts Amount of Tokens id bought for each corresponding Token id in _tokenIds * @param _maxCurrency Total maximum amount of currency tokens to spend for all Token ids * @param _deadline Timestamp after which this transaction will be reverted * @param _recipient The address that receives output Tokens and refund * @param _extraFeeRecipients Array of addresses that will receive extra fee * @param _extraFeeAmounts Array of amounts of currency that will be sent as extra fee * @return currencySold How much currency was actually sold. */ function buyTokens( uint256[] memory _tokenIds, uint256[] memory _tokensBoughtAmounts, uint256 _maxCurrency, uint256 _deadline, address _recipient, address[] memory _extraFeeRecipients, uint256[] memory _extraFeeAmounts ) override external returns (uint256[] memory) { require(_deadline >= block.timestamp, "NE20#19"); // NiftyswapExchange20#buyTokens: DEADLINE_EXCEEDED require(_tokenIds.length > 0, "NE20#20"); // NiftyswapExchange20#buyTokens: INVALID_CURRENCY_IDS_AMOUNT // Transfer the tokens for purchase TransferHelper.safeTransferFrom(currency, msg.sender, address(this), _maxCurrency); address recipient = _recipient == address(0x0) ? msg.sender : _recipient; // Set the extra fee aside to recipients ahead of purchase, if any. uint256 maxCurrency = _maxCurrency; uint256 nExtraFees = _extraFeeRecipients.length; require(nExtraFees == _extraFeeAmounts.length, "NE20#21"); // NiftyswapExchange20#buyTokens: EXTRA_FEES_ARRAYS_ARE_NOT_SAME_LENGTH for (uint256 i = 0; i < nExtraFees; i++) { if (_extraFeeAmounts[i] > 0) { maxCurrency = maxCurrency.sub(_extraFeeAmounts[i]); royaltiesNumerator[_extraFeeRecipients[i]] = royaltiesNumerator[_extraFeeRecipients[i]].add(_extraFeeAmounts[i].mul(ROYALTIES_DENOMINATOR)); } } // Execute trade and retrieve amount of currency spent uint256[] memory currencySold = _currencyToToken(_tokenIds, _tokensBoughtAmounts, maxCurrency, _deadline, recipient); emit TokensPurchase(msg.sender, recipient, _tokenIds, _tokensBoughtAmounts, currencySold, _extraFeeRecipients, _extraFeeAmounts); return currencySold; } /** * @notice Handle which method is being called on transfer * @dev `_data` must be encoded as follow: abi.encode(bytes4, MethodObj) * where bytes4 argument is the MethodObj object signature passed as defined * in the `Signatures for onReceive control logic` section above * @param _from The address which previously owned the Token * @param _ids An array containing ids of each Token being transferred * @param _amounts An array containing amounts of each Token being transferred * @param _data Method signature and corresponding encoded arguments for method to call on *this* contract * @return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)") */ function onERC1155BatchReceived( address, // _operator, address _from, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) override public returns(bytes4) { // This function assumes that the ERC-1155 token contract can // only call `onERC1155BatchReceived()` via a valid token transfer. // Users must be responsible and only use this Niftyswap exchange // contract with ERC-1155 compliant token contracts. // Obtain method to call via object signature bytes4 functionSignature = abi.decode(_data, (bytes4)); /***********************************| | Selling Tokens | |__________________________________*/ if (functionSignature == SELLTOKENS_SIG) { // Tokens received need to be Token contract require(msg.sender == address(token), "NE20#22"); // NiftyswapExchange20#onERC1155BatchReceived: INVALID_TOKENS_TRANSFERRED // Decode SellTokensObj from _data to call _tokenToCurrency() SellTokensObj memory obj; (, obj) = abi.decode(_data, (bytes4, SellTokensObj)); address recipient = obj.recipient == address(0x0) ? _from : obj.recipient; // Validate fee arrays require(obj.extraFeeRecipients.length == obj.extraFeeAmounts.length, "NE20#23"); // NiftyswapExchange20#buyTokens: EXTRA_FEES_ARRAYS_ARE_NOT_SAME_LENGTH // Execute trade and retrieve amount of currency received uint256[] memory currencyBought = _tokenToCurrency(_ids, _amounts, obj.minCurrency, obj.deadline, recipient, obj.extraFeeRecipients, obj.extraFeeAmounts); emit CurrencyPurchase(_from, recipient, _ids, _amounts, currencyBought, obj.extraFeeRecipients, obj.extraFeeAmounts); /***********************************| | Adding Liquidity Tokens | |__________________________________*/ } else if (functionSignature == ADDLIQUIDITY_SIG) { // Only allow to receive ERC-1155 tokens from `token` contract require(msg.sender == address(token), "NE20#24"); // NiftyswapExchange20#onERC1155BatchReceived: INVALID_TOKEN_TRANSFERRED // Decode AddLiquidityObj from _data to call _addLiquidity() AddLiquidityObj memory obj; (, obj) = abi.decode(_data, (bytes4, AddLiquidityObj)); _addLiquidity(_from, _ids, _amounts, obj.maxCurrency, obj.deadline); /***********************************| | Removing iquidity Tokens | |__________________________________*/ } else if (functionSignature == REMOVELIQUIDITY_SIG) { // Tokens received need to be NIFTY-1155 tokens require(msg.sender == address(this), "NE20#25"); // NiftyswapExchange20#onERC1155BatchReceived: INVALID_NIFTY_TOKENS_TRANSFERRED // Decode RemoveLiquidityObj from _data to call _removeLiquidity() RemoveLiquidityObj memory obj; (, obj) = abi.decode(_data, (bytes4, RemoveLiquidityObj)); _removeLiquidity(_from, _ids, _amounts, obj.minCurrency, obj.minTokens, obj.deadline); /***********************************| | Deposits & Invalid Calls | |__________________________________*/ } else if (functionSignature == DEPOSIT_SIG) { // Do nothing for when contract is self depositing // This could be use to deposit currency "by accident", which would be locked require(msg.sender == address(currency), "NE20#26"); // NiftyswapExchange20#onERC1155BatchReceived: INVALID_TOKENS_DEPOSITED } else { revert("NE20#27"); // NiftyswapExchange20#onERC1155BatchReceived: INVALID_METHOD } return ERC1155_BATCH_RECEIVED_VALUE; } /** * @dev Will pass to onERC115Batch5Received */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes memory _data) override public returns(bytes4) { uint256[] memory ids = new uint256[](1); uint256[] memory amounts = new uint256[](1); ids[0] = _id; amounts[0] = _amount; require( ERC1155_BATCH_RECEIVED_VALUE == onERC1155BatchReceived(_operator, _from, ids, amounts, _data), "NE20#28" // NiftyswapExchange20#onERC1155Received: INVALID_ONRECEIVED_MESSAGE ); return ERC1155_RECEIVED_VALUE; } /** * @notice Prevents receiving Ether or calls to unsuported methods */ fallback () external { revert("NE20#29"); // NiftyswapExchange20:UNSUPPORTED_METHOD } /***********************************| | Royalty Functions | |__________________________________*/ /** * @notice Will set the royalties fees and recipient for contracts that don't support ERC-2981 * @param _fee Fee pourcentage with a 10000 basis (e.g. 0.3% is 3 and 1% is 10 and 100% is 1000) * @param _recipient Address where to send the fees to */ function setRoyaltyInfo(uint256 _fee, address _recipient) onlyOwner public { // Don't use IS_ERC2981 in case token contract was updated bool isERC2981 = token.supportsInterface(type(IERC2981).interfaceId); require(!isERC2981, "NE20#30"); // NiftyswapExchange20#setRoyaltyInfo: TOKEN SUPPORTS ERC-2981 require(_fee <= MAX_ROYALTY, "NE20#31"); // NiftyswapExchange20#setRoyaltyInfo: ROYALTY_FEE_IS_TOO_HIGH globalRoyaltyFee = _fee; globalRoyaltyRecipient = _recipient; emit RoyaltyChanged(_recipient, _fee); } /** * @notice Will send the royalties that _royaltyRecipient can claim, if any * @dev Anyone can call this function such that payout could be distributed * regularly instead of being claimed. * @param _royaltyRecipient Address that is able to claim royalties */ function sendRoyalties(address _royaltyRecipient) override external { uint256 royaltyAmount = royaltiesNumerator[_royaltyRecipient] / ROYALTIES_DENOMINATOR; royaltiesNumerator[_royaltyRecipient] = royaltiesNumerator[_royaltyRecipient] % ROYALTIES_DENOMINATOR; TransferHelper.safeTransfer(currency, _royaltyRecipient, royaltyAmount); } /** * @notice Will return how much of currency need to be paid for the royalty * @notice Royalty is capped at 25% of the total amount of currency * @param _tokenId ID of the erc-1155 token being traded * @param _cost Amount of currency sent/received for the trade * @return recipient Address that will be able to claim the royalty * @return royalty Amount of currency that will be sent to royalty recipient */ function getRoyaltyInfo(uint256 _tokenId, uint256 _cost) public view returns (address recipient, uint256 royalty) { if (IS_ERC2981) { // Add a try/catch in-case token *removed* ERC-2981 support try IERC2981(address(token)).royaltyInfo(_tokenId, _cost) returns(address _r, uint256 _c) { // Cap to 25% of the total amount of currency uint256 max = _cost.mul(MAX_ROYALTY) / ROYALTIES_DENOMINATOR; return (_r, _c > max ? max : _c); } catch { // Default back to global setting if error occurs return (globalRoyaltyRecipient, (_cost.mul(globalRoyaltyFee)) / ROYALTIES_DENOMINATOR); } } else { return (globalRoyaltyRecipient, (_cost.mul(globalRoyaltyFee)) / ROYALTIES_DENOMINATOR); } } /***********************************| | Getter Functions | |__________________________________*/ /** * @notice Get amount of currency in reserve for each Token _id in _ids * @param _ids Array of ID sto query currency reserve of * @return amount of currency in reserve for each Token _id */ function getCurrencyReserves( uint256[] calldata _ids) override external view returns (uint256[] memory) { uint256 nIds = _ids.length; uint256[] memory currencyReservesReturn = new uint256[](nIds); for (uint256 i = 0; i < nIds; i++) { currencyReservesReturn[i] = currencyReserves[_ids[i]]; } return currencyReservesReturn; } /** * @notice Return price for `currency => Token _id` trades with an exact token amount. * @param _ids Array of ID of tokens bought. * @param _tokensBought Amount of Tokens bought. * @return Amount of currency needed to buy Tokens in _ids for amounts in _tokensBought */ function getPrice_currencyToToken( uint256[] calldata _ids, uint256[] calldata _tokensBought) override external view returns (uint256[] memory) { uint256 nIds = _ids.length; uint256[] memory prices = new uint256[](nIds); for (uint256 i = 0; i < nIds; i++) { // Load Token id reserve uint256 tokenReserve = token.balanceOf(address(this), _ids[i]); prices[i] = getBuyPriceWithRoyalty(_ids[i], _tokensBought[i], currencyReserves[_ids[i]], tokenReserve); } // Return prices return prices; } /** * @notice Return price for `Token _id => currency` trades with an exact token amount. * @param _ids Array of IDs token sold. * @param _tokensSold Array of amount of each Token sold. * @return Amount of currency that can be bought for Tokens in _ids for amounts in _tokensSold */ function getPrice_tokenToCurrency( uint256[] calldata _ids, uint256[] calldata _tokensSold) override external view returns (uint256[] memory) { uint256 nIds = _ids.length; uint256[] memory prices = new uint256[](nIds); for (uint256 i = 0; i < nIds; i++) { // Load Token id reserve uint256 tokenReserve = token.balanceOf(address(this), _ids[i]); prices[i] = getSellPriceWithRoyalty(_ids[i], _tokensSold[i], tokenReserve, currencyReserves[_ids[i]]); } // Return price return prices; } /** * @return Address of Token that is sold on this exchange. */ function getTokenAddress() override external view returns (address) { return address(token); } /** * @return LP fee per 1000 units */ function getLPFee() override external view returns (uint256) { return 1000-FEE_MULTIPLIER; } /** * @return Address of the currency contract that is used as currency */ function getCurrencyInfo() override external view returns (address) { return (address(currency)); } /** * @notice Get total supply of liquidity tokens * @param _ids ID of the Tokens * @return The total supply of each liquidity token id provided in _ids */ function getTotalSupply(uint256[] calldata _ids) override external view returns (uint256[] memory) { // Number of ids uint256 nIds = _ids.length; // Variables uint256[] memory batchTotalSupplies = new uint256[](nIds); // Iterate over each owner and token ID for (uint256 i = 0; i < nIds; i++) { batchTotalSupplies[i] = totalSupplies[_ids[i]]; } return batchTotalSupplies; } /** * @return Address of factory that created this exchange. */ function getFactoryAddress() override external view returns (address) { return factory; } /** * @return Global royalty fee % if not supporting ERC-2981 */ function getGlobalRoyaltyFee() override external view returns (uint256) { return globalRoyaltyFee; } /** * @return Global royalty recipient if token not supporting ERC-2981 */ function getGlobalRoyaltyRecipient() override external view returns (address) { return globalRoyaltyRecipient; } /** * @return Get amount of currency in royalty an address can claim * @param _royaltyRecipient Address to check the claimable royalties */ function getRoyalties(address _royaltyRecipient) override external view returns (uint256) { return royaltiesNumerator[_royaltyRecipient] / ROYALTIES_DENOMINATOR; } function getRoyaltiesNumerator(address _royaltyRecipient) override external view returns (uint256) { return royaltiesNumerator[_royaltyRecipient]; } /***********************************| | Utility Functions | |__________________________________*/ /** * @notice Divides two numbers and add 1 if there is a rounding error * @param a Numerator * @param b Denominator */ function divRound(uint256 a, uint256 b) internal pure returns (uint256, bool) { return a % b == 0 ? (a/b, false) : ((a/b).add(1), true); } /** * @notice Return Token reserves for given Token ids * @dev Assumes that ids are sorted from lowest to highest with no duplicates. * This assumption allows for checking the token reserves only once, otherwise * token reserves need to be re-checked individually or would have to do more expensive * duplication checks. * @param _tokenIds Array of IDs to query their Reserve balance. * @return Array of Token ids' reserves */ function _getTokenReserves( uint256[] memory _tokenIds) internal view returns (uint256[] memory) { uint256 nTokens = _tokenIds.length; // Regular balance query if only 1 token, otherwise batch query if (nTokens == 1) { uint256[] memory tokenReserves = new uint256[](1); tokenReserves[0] = token.balanceOf(address(this), _tokenIds[0]); return tokenReserves; } else { // Lazy check preventing duplicates & build address array for query address[] memory thisAddressArray = new address[](nTokens); thisAddressArray[0] = address(this); for (uint256 i = 1; i < nTokens; i++) { require(_tokenIds[i-1] < _tokenIds[i], "NE20#32"); // NiftyswapExchange20#_getTokenReserves: UNSORTED_OR_DUPLICATE_TOKEN_IDS thisAddressArray[i] = address(this); } return token.balanceOfBatch(thisAddressArray, _tokenIds); } } /** * @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types. * @param interfaceID The ERC-165 interface ID that is queried for support.s * @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface. * This function MUST NOT consume more thsan 5,000 gas. * @return Whether a given interface is supported */ function supportsInterface(bytes4 interfaceID) public override pure returns (bool) { return interfaceID == type(IERC20).interfaceId || interfaceID == type(IERC165).interfaceId || interfaceID == type(IERC1155).interfaceId || interfaceID == type(IERC1155TokenReceiver).interfaceId || interfaceID == type(IERC1155Metadata).interfaceId; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; interface INiftyswapExchange20 { /***********************************| | Events | |__________________________________*/ event TokensPurchase( address indexed buyer, address indexed recipient, uint256[] tokensBoughtIds, uint256[] tokensBoughtAmounts, uint256[] currencySoldAmounts, address[] extraFeeRecipients, uint256[] extraFeeAmounts ); event CurrencyPurchase( address indexed buyer, address indexed recipient, uint256[] tokensSoldIds, uint256[] tokensSoldAmounts, uint256[] currencyBoughtAmounts, address[] extraFeeRecipients, uint256[] extraFeeAmounts ); event LiquidityAdded( address indexed provider, uint256[] tokenIds, uint256[] tokenAmounts, uint256[] currencyAmounts ); struct LiquidityRemovedEventObj { uint256 currencyAmount; uint256 soldTokenNumerator; uint256 boughtCurrencyNumerator; uint256 totalSupply; } event LiquidityRemoved( address indexed provider, uint256[] tokenIds, uint256[] tokenAmounts, LiquidityRemovedEventObj[] details ); event RoyaltyChanged( address indexed royaltyRecipient, uint256 royaltyFee ); struct SellTokensObj { address recipient; // Who receives the currency uint256 minCurrency; // Total minimum number of currency expected for all tokens sold address[] extraFeeRecipients; // Array of addresses that will receive extra fee uint256[] extraFeeAmounts; // Array of amounts of currency that will be sent as extra fee uint256 deadline; // Timestamp after which the tx isn't valid anymore } struct AddLiquidityObj { uint256[] maxCurrency; // Maximum number of currency to deposit with tokens uint256 deadline; // Timestamp after which the tx isn't valid anymore } struct RemoveLiquidityObj { uint256[] minCurrency; // Minimum number of currency to withdraw uint256[] minTokens; // Minimum number of tokens to withdraw uint256 deadline; // Timestamp after which the tx isn't valid anymore } /***********************************| | Purchasing Functions | |__________________________________*/ /** * @notice Convert currency tokens to Tokens _id and transfers Tokens to recipient. * @dev User specifies MAXIMUM inputs (_maxCurrency) and EXACT outputs. * @dev Assumes that all trades will be successful, or revert the whole tx * @dev Exceeding currency tokens sent will be refunded to recipient * @dev Sorting IDs is mandatory for efficient way of preventing duplicated IDs (which would lead to exploit) * @param _tokenIds Array of Tokens ID that are bought * @param _tokensBoughtAmounts Amount of Tokens id bought for each corresponding Token id in _tokenIds * @param _maxCurrency Total maximum amount of currency tokens to spend for all Token ids * @param _deadline Timestamp after which this transaction will be reverted * @param _recipient The address that receives output Tokens and refund * @param _extraFeeRecipients Array of addresses that will receive extra fee * @param _extraFeeAmounts Array of amounts of currency that will be sent as extra fee * @return currencySold How much currency was actually sold. */ function buyTokens( uint256[] memory _tokenIds, uint256[] memory _tokensBoughtAmounts, uint256 _maxCurrency, uint256 _deadline, address _recipient, address[] memory _extraFeeRecipients, uint256[] memory _extraFeeAmounts ) external returns (uint256[] memory); /***********************************| | Royalties Functions | |__________________________________*/ /** * @notice Will send the royalties that _royaltyRecipient can claim, if any * @dev Anyone can call this function such that payout could be distributed * regularly instead of being claimed. * @param _royaltyRecipient Address that is able to claim royalties */ function sendRoyalties(address _royaltyRecipient) external; /***********************************| | OnReceive Functions | |__________________________________*/ /** * @notice Handle which method is being called on Token transfer * @dev `_data` must be encoded as follow: abi.encode(bytes4, MethodObj) * where bytes4 argument is the MethodObj object signature passed as defined * in the `Signatures for onReceive control logic` section above * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount The amount of tokens being transferred * @param _data Method signature and corresponding encoded arguments for method to call on *this* contract * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4); /** * @notice Handle which method is being called on transfer * @dev `_data` must be encoded as follow: abi.encode(bytes4, MethodObj) * where bytes4 argument is the MethodObj object signature passed as defined * in the `Signatures for onReceive control logic` section above * @param _from The address which previously owned the Token * @param _ids An array containing ids of each Token being transferred * @param _amounts An array containing amounts of each Token being transferred * @param _data Method signature and corresponding encoded arguments for method to call on *this* contract * @return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)") */ function onERC1155BatchReceived(address, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4); /***********************************| | Getter Functions | |__________________________________*/ /** * @dev Pricing function used for converting between currency token to Tokens. * @param _assetBoughtAmount Amount of Tokens being bought. * @param _assetSoldReserve Amount of currency tokens in exchange reserves. * @param _assetBoughtReserve Amount of Tokens (output type) in exchange reserves. * @return Amount of currency tokens to send to Niftyswap. */ function getBuyPrice(uint256 _assetBoughtAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) external view returns (uint256); /** * @dev Pricing function used for converting Tokens to currency token (including royalty fee) * @param _tokenId Id ot token being sold * @param _assetBoughtAmount Amount of Tokens being bought. * @param _assetSoldReserve Amount of currency tokens in exchange reserves. * @param _assetBoughtReserve Amount of Tokens (output type) in exchange reserves. * @return price Amount of currency tokens to send to Niftyswap. */ function getBuyPriceWithRoyalty(uint256 _tokenId, uint256 _assetBoughtAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) external view returns (uint256 price); /** * @dev Pricing function used for converting Tokens to currency token. * @param _assetSoldAmount Amount of Tokens being sold. * @param _assetSoldReserve Amount of Tokens in exchange reserves. * @param _assetBoughtReserve Amount of currency tokens in exchange reserves. * @return Amount of currency tokens to receive from Niftyswap. */ function getSellPrice(uint256 _assetSoldAmount,uint256 _assetSoldReserve, uint256 _assetBoughtReserve) external view returns (uint256); /** * @dev Pricing function used for converting Tokens to currency token (including royalty fee) * @param _tokenId Id ot token being sold * @param _assetSoldAmount Amount of Tokens being sold. * @param _assetSoldReserve Amount of Tokens in exchange reserves. * @param _assetBoughtReserve Amount of currency tokens in exchange reserves. * @return price Amount of currency tokens to receive from Niftyswap. */ function getSellPriceWithRoyalty(uint256 _tokenId, uint256 _assetSoldAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) external view returns (uint256 price); /** * @notice Get amount of currency in reserve for each Token _id in _ids * @param _ids Array of ID sto query currency reserve of * @return amount of currency in reserve for each Token _id */ function getCurrencyReserves(uint256[] calldata _ids) external view returns (uint256[] memory); /** * @notice Return price for `currency => Token _id` trades with an exact token amount. * @param _ids Array of ID of tokens bought. * @param _tokensBought Amount of Tokens bought. * @return Amount of currency needed to buy Tokens in _ids for amounts in _tokensBought */ function getPrice_currencyToToken(uint256[] calldata _ids, uint256[] calldata _tokensBought) external view returns (uint256[] memory); /** * @notice Return price for `Token _id => currency` trades with an exact token amount. * @param _ids Array of IDs token sold. * @param _tokensSold Array of amount of each Token sold. * @return Amount of currency that can be bought for Tokens in _ids for amounts in _tokensSold */ function getPrice_tokenToCurrency(uint256[] calldata _ids, uint256[] calldata _tokensSold) external view returns (uint256[] memory); /** * @notice Get total supply of liquidity tokens * @param _ids ID of the Tokens * @return The total supply of each liquidity token id provided in _ids */ function getTotalSupply(uint256[] calldata _ids) external view returns (uint256[] memory); /** * @return Address of Token that is sold on this exchange. */ function getTokenAddress() external view returns (address); /** * @return LP fee per 1000 units */ function getLPFee() external view returns (uint256); /** * @return Address of the currency contract that is used as currency */ function getCurrencyInfo() external view returns (address); /** * @return Address of factory that created this exchange. */ function getFactoryAddress() external view returns (address); /** * @return Global royalty fee % if not supporting ERC-2981 */ function getGlobalRoyaltyFee() external view returns (uint256); /** * @return Global royalty recipient if token not supporting ERC-2981 */ function getGlobalRoyaltyRecipient() external view returns (address); /** * @return Get amount of currency in royalty an address can claim * @param _royaltyRecipient Address to check the claimable royalties */ function getRoyalties(address _royaltyRecipient) external view returns (uint256); function getRoyaltiesNumerator(address _royaltyRecipient) external view returns (uint256); } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "../interfaces/IOwnable.sol"; /** * @title Ownable * @dev The Ownable contract inherits the owner of a parent contract as its owner, * and provides basic authorization control functions, this simplifies the * implementation of "user permissions". */ contract DelegatedOwnable { address internal ownableParent; event ParentOwnerChanged(address indexed previousParent, address indexed newParent); /** * @dev The Ownable constructor sets the original `ownableParent` of the contract to the specied address * @param _firstOwnableParent Address of the first ownable parent contract */ constructor (address _firstOwnableParent) { try IOwnable(_firstOwnableParent).getOwner() { // Do nothing if parent has ownable function } catch { revert("DO#1"); // PARENT IS NOT OWNABLE } ownableParent = _firstOwnableParent; emit ParentOwnerChanged(address(0), _firstOwnableParent); } /** * @dev Throws if called by any account other than the master owner. */ modifier onlyOwner() { require(msg.sender == getOwner(), "DO#2"); // DelegatedOwnable#onlyOwner: SENDER_IS_NOT_OWNER _; } /** * @notice Will use the owner address of another parent contract * @param _newParent Address of the new owner */ function changeOwnableParent(address _newParent) public onlyOwner { require(_newParent != address(0), "D3"); // DelegatedOwnable#changeOwnableParent: INVALID_ADDRESS ownableParent = _newParent; emit ParentOwnerChanged(ownableParent, _newParent); } /** * @notice Returns the address of the owner. */ function getOwner() public view returns (address) { return IOwnable(ownableParent).getOwner(); } } pragma solidity ^0.7.4; /** Note: The ERC-165 identifier for this interface is 0x0e89341c. */ interface IERC1155Metadata { /** @notice A distinct Uniform Resource Identifier (URI) for a given token. @dev URIs are defined in RFC 3986. The URI MUST point to a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema". @return URI string */ function uri(uint256 _id) external view returns (string memory); } pragma solidity ^0.7.4; import "./IERC1155Metadata.sol"; interface IDelegatedERC1155Metadata { function metadataProvider() external view returns (IERC1155Metadata); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; interface IOwnable { /** * @notice Transfers the ownership of the contract to new address * @param _newOwner Address of the new owner */ function transferOwnership(address _newOwner) external; /** * @notice Returns the address of the owner. */ function getOwner() external view returns (address); } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; /** * @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 internal owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the specied address * @param _firstOwner Address of the first owner */ constructor (address _firstOwner) { owner = _firstOwner; emit OwnershipTransferred(address(0), _firstOwner); } /** * @dev Throws if called by any account other than the master owner. */ modifier onlyOwner() { require(msg.sender == owner, "Ownable#onlyOwner: SENDER_IS_NOT_OWNER"); _; } /** * @notice Transfers the ownership of the contract to new address * @param _newOwner Address of the new owner */ function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0), "Ownable#transferOwnership: INVALID_ADDRESS"); owner = _newOwner; emit OwnershipTransferred(owner, _newOwner); } /** * @notice Returns the address of the owner. */ function getOwner() public view returns (address) { return owner; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import "../interfaces/IERC1155Metadata.sol"; import "./Ownable.sol"; contract ERC1155MetadataPrefix is IERC1155Metadata, Ownable { string public uriPrefix; event URIPrefixChanged(string _uriPrefix); bool immutable includeAddress; constructor(string memory _prefix, bool _includeAddress) Ownable(msg.sender) { emit URIPrefixChanged(_prefix); uriPrefix = _prefix; includeAddress = _includeAddress; } function setUriPrefix(string calldata _uriPrefix) external onlyOwner { emit URIPrefixChanged(_uriPrefix); uriPrefix = _uriPrefix; } function uri(uint256 _id) external override view returns (string memory) { string memory suffix = _uint256toString(_id); if (includeAddress) { suffix = string(abi.encodePacked(suffix, "@", _addressToString(msg.sender))); } return string(abi.encodePacked(uriPrefix, suffix)); } function _addressToString(address account) public pure returns(string memory) { return _bytesToString(abi.encodePacked(account)); } function _bytesToString(bytes memory data) public pure returns(string memory) { bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(2 + data.length * 2); str[0] = "0"; str[1] = "x"; for (uint i = 0; i < data.length; i++) { str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))]; str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))]; } return string(str); } function _uint256toString(uint256 _id) internal pure returns (string memory) { bytes memory reversed = new bytes(78); uint256 v = _id; uint256 i = 0; while (v != 0) { uint256 remainder = v % 10; v = v / 10; reversed[i++] = byte(uint8(48 + remainder)); } bytes memory s = new bytes(i); for (uint256 j = 0; j < i; j++) { s[j] = reversed[i - 1 - j]; } return string(s); } } pragma solidity 0.7.4; import "@0xsequence/erc-1155/contracts/interfaces/IERC20.sol"; import "@0xsequence/erc-1155/contracts/utils/SafeMath.sol"; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public override view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token to a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public override returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public override returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public override returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * Emits an Approval event. * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } contract ERC20Mock is ERC20 { constructor() public { } function mockMint(address _address, uint256 _amount) public { _mint(_address, _amount); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import "@0xsequence/erc20-meta-token/contracts/mocks/ERC20Mock.sol"; contract ERC20TokenMock is ERC20Mock { } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@0xsequence/erc-1155/contracts/mocks/ERC1155MintBurnMock.sol"; contract ERC1155Mock is ERC1155MintBurnMock { constructor() ERC1155MintBurnMock("TestERC1155", "") {} } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@0xsequence/erc20-meta-token/contracts/wrapper/MetaERC20Wrapper.sol"; contract ERC20WrapperMock is MetaERC20Wrapper { }
* @notice Handle which method is being called on Token transfer @dev `_data` must be encoded as follow: abi.encode(bytes4, MethodObj) where bytes4 argument is the MethodObj object signature passed as defined in the `Signatures for onReceive control logic` section above @param _operator The address which called the `safeTransferFrom` function @param _from The address which previously owned the token @param _id The id of the token being transferred @param _amount The amount of tokens being transferred @param _data Method signature and corresponding encoded arguments for method to call on this contract @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`/* @notice Handle which method is being called on transfer @dev `_data` must be encoded as follow: abi.encode(bytes4, MethodObj) where bytes4 argument is the MethodObj object signature passed as defined in the `Signatures for onReceive control logic` section above @param _from The address which previously owned the Token @param _ids An array containing ids of each Token being transferred @param _amounts An array containing amounts of each Token being transferred @param _data Method signature and corresponding encoded arguments for method to call on this contract @return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)")/**********************************|* @dev Pricing function used for converting between currency token to Tokens. @param _assetBoughtAmount Amount of Tokens being bought. @param _assetSoldReserve Amount of currency tokens in exchange reserves. @param _assetBoughtReserve Amount of Tokens (output type) in exchange reserves. @return Amount of currency tokens to send to Niftyswap./* @dev Pricing function used for converting Tokens to currency token. @param _assetSoldAmount Amount of Tokens being sold. @param _assetSoldReserve Amount of Tokens in exchange reserves. @param _assetBoughtReserve Amount of currency tokens in exchange reserves. @return Amount of currency tokens to receive from Niftyswap./* @notice Get amount of currency in reserve for each Token _id in _ids @param _ids Array of ID sto query currency reserve of @return amount of currency in reserve for each Token _id/* @notice Return price for `currency => Token _id` trades with an exact token amount. @param _ids Array of ID of tokens bought. @param _tokensBought Amount of Tokens bought. @return Amount of currency needed to buy Tokens in _ids for amounts in _tokensBought/* @notice Return price for `Token _id => currency` trades with an exact token amount. @param _ids Array of IDs token sold. @param _tokensSold Array of amount of each Token sold. @return Amount of currency that can be bought for Tokens in _ids for amounts in _tokensSold/* @notice Get total supply of liquidity tokens @param _ids ID of the Tokens @return The total supply of each liquidity token id provided in _ids/* @return Address of Token that is sold on this exchange./* @return Address of the currency contract that is used as currency and its corresponding id/* @return Address of factory that created this exchange./ SPDX-License-Identifier: MIT OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.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/ 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.
abstract contract ReentrancyGuard { uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4); function onERC1155BatchReceived(address, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4); | Getter Functions | |__________________________________*/ function getBuyPrice(uint256 _assetBoughtAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) external pure returns (uint256); function getSellPrice(uint256 _assetSoldAmount,uint256 _assetSoldReserve, uint256 _assetBoughtReserve) external pure returns (uint256); function getCurrencyReserves(uint256[] calldata _ids) external view returns (uint256[] memory); function getPrice_currencyToToken(uint256[] calldata _ids, uint256[] calldata _tokensBought) external view returns (uint256[] memory); function getPrice_tokenToCurrency(uint256[] calldata _ids, uint256[] calldata _tokensSold) external view returns (uint256[] memory); function getTotalSupply(uint256[] calldata _ids) external view returns (uint256[] memory); function getTokenAddress() external view returns (address); function getCurrencyInfo() external view returns (address, uint256); function getFactoryAddress() external view returns (address); } pragma solidity 0.7.4; constructor() { _status = _NOT_ENTERED; } modifier nonReentrant() { require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); _status = _ENTERED; _; _status = _NOT_ENTERED; } }
13,573,480
[ 1, 3259, 1492, 707, 353, 3832, 2566, 603, 3155, 7412, 225, 1375, 67, 892, 68, 1297, 506, 3749, 487, 2805, 30, 24126, 18, 3015, 12, 3890, 24, 16, 2985, 2675, 13, 282, 1625, 1731, 24, 1237, 353, 326, 2985, 2675, 733, 3372, 2275, 487, 2553, 282, 316, 326, 1375, 23918, 364, 603, 11323, 3325, 4058, 68, 2442, 5721, 225, 389, 9497, 1021, 1758, 1492, 2566, 326, 1375, 4626, 5912, 1265, 68, 445, 225, 389, 2080, 377, 1021, 1758, 1492, 7243, 16199, 326, 1147, 225, 389, 350, 4202, 1021, 612, 434, 326, 1147, 3832, 906, 4193, 225, 389, 8949, 282, 1021, 3844, 434, 2430, 3832, 906, 4193, 225, 389, 892, 377, 2985, 3372, 471, 4656, 3749, 1775, 364, 707, 358, 745, 603, 333, 6835, 327, 1375, 3890, 24, 12, 79, 24410, 581, 5034, 2932, 265, 654, 39, 2499, 2539, 8872, 12, 2867, 16, 2867, 16, 11890, 5034, 16, 11890, 5034, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 17801, 6835, 868, 8230, 12514, 16709, 288, 203, 203, 565, 2254, 5034, 3238, 5381, 389, 4400, 67, 12278, 2056, 273, 404, 31, 203, 565, 2254, 5034, 3238, 5381, 389, 12278, 2056, 273, 576, 31, 203, 203, 565, 2254, 5034, 3238, 389, 2327, 31, 203, 203, 225, 445, 603, 654, 39, 2499, 2539, 8872, 12, 2867, 389, 9497, 16, 1758, 389, 2080, 16, 2254, 5034, 389, 350, 16, 2254, 5034, 389, 8949, 16, 1731, 745, 892, 389, 892, 13, 3903, 1135, 12, 3890, 24, 1769, 203, 203, 225, 445, 603, 654, 39, 2499, 2539, 4497, 8872, 12, 2867, 16, 1758, 389, 2080, 16, 2254, 5034, 8526, 745, 892, 389, 2232, 16, 2254, 5034, 8526, 745, 892, 389, 8949, 87, 16, 1731, 745, 892, 389, 892, 13, 3903, 1135, 12, 3890, 24, 1769, 203, 203, 203, 225, 571, 540, 968, 387, 15486, 1850, 571, 203, 225, 571, 21157, 21157, 972, 5549, 203, 203, 225, 445, 2882, 9835, 5147, 12, 11890, 5034, 389, 9406, 13809, 9540, 6275, 16, 2254, 5034, 389, 9406, 55, 1673, 607, 6527, 16, 2254, 5034, 389, 9406, 13809, 9540, 607, 6527, 13, 3903, 16618, 1135, 261, 11890, 5034, 1769, 203, 203, 225, 445, 1322, 1165, 5147, 12, 11890, 5034, 389, 9406, 55, 1673, 6275, 16, 11890, 5034, 389, 9406, 55, 1673, 607, 6527, 16, 2254, 5034, 389, 9406, 13809, 9540, 607, 6527, 13, 3903, 16618, 1135, 261, 11890, 5034, 1769, 203, 203, 225, 445, 17910, 607, 264, 3324, 12, 11890, 5034, 8526, 745, 892, 389, 2232, 13, 3903, 1476, 1135, 261, 11890, 5034, 2 ]
// File: contracts/token/DMCGovernanceStorage.sol pragma solidity 0.5.17; contract DMCGovernanceStorage { /// @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; } // File: contracts/lib/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.5.17; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/token/DMCTokenStorage.sol pragma solidity 0.5.17; // Storage for a DMC token contract DMCTokenStorage { using SafeMath for uint256; /** * @dev Guard variable for re-entrancy checks. Not currently used */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Governor for this contract */ address public gov; /** * @notice Pending governance for this contract */ address public pendingGov; /** * @notice Total supply of DMCs */ uint256 public totalSupply; mapping (address => uint256) internal _DMCBalances; mapping (address => mapping (address => uint256)) internal _allowedFragments; } // File: contracts/token/DMCTokenInterface.sol pragma solidity 0.5.17; contract DMCTokenInterface is DMCTokenStorage, DMCGovernanceStorage { /// @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); /*** Gov Events ***/ /** * @notice Event emitted when pendingGov is changed */ event NewPendingGov(address oldPendingGov, address newPendingGov); /** * @notice Event emitted when gov is changed */ event NewGov(address oldGov, address newGov); /* - ERC20 Events - */ /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Tokens minted event */ event Mint(address to, uint256 amount); // Public functions function transfer(address to, uint256 value) external returns(bool); function transferFrom(address from, address to, uint256 value) external returns(bool); function balanceOf(address who) external view returns(uint256); function allowance(address owner_, address spender) external view returns(uint256); function approve(address spender, uint256 value) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); /* - Governance Functions - */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256); function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external; function delegate(address delegatee) external; function delegates(address delegator) external view returns (address); function getCurrentVotes(address account) external view returns (uint256); /* - Permissioned/Governance functions - */ function _setPendingGov(address pendingGov_) external; function _acceptGov() external; } // File: contracts/token/DMCGovernance.sol pragma solidity 0.5.17; contract DMCGovernanceToken is DMCTokenInterface { /// @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), "DMC::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "DMC::delegateBySig: invalid nonce"); require(now <= expiry, "DMC::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, "DMC::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 = _DMCBalances[delegator]; _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "DMC::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts/token/DMC.sol pragma solidity 0.5.17; contract DMCToken is DMCGovernanceToken { // Modifiers modifier onlyGov() { require(msg.sender == gov); _; } modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } function initialize( string memory name_, string memory symbol_, uint8 decimals_ ) public { name = name_; symbol = symbol_; decimals = decimals_; } /** * @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance. * @dev Limited to onlyMinter modifier */ function mint(address to, uint256 amount) external onlyGov returns (bool) { require(totalSupply + amount <= 88_000_000 * 1e18, 'max supply reached'); _mint(to, amount); return true; } function _mint(address to, uint256 amount) internal { // increase totalSupply totalSupply = totalSupply.add(amount); // add balance _DMCBalances[to] = _DMCBalances[to].add(amount); // add delegates to the minter _moveDelegates(address(0), _delegates[to], amount); emit Mint(to, amount); } /* - ERC20 functionality - */ /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) external validRecipient(to) returns (bool) { // sub from balance of sender _DMCBalances[msg.sender] = _DMCBalances[msg.sender].sub(value); // add to balance of receiver _DMCBalances[to] = _DMCBalances[to].add(value); emit Transfer(msg.sender, to, value); _moveDelegates(_delegates[msg.sender], _delegates[to], value); return true; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) external validRecipient(to) returns (bool) { // decrease allowance _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); // sub from from _DMCBalances[from] = _DMCBalances[from].sub(value); _DMCBalances[to] = _DMCBalances[to].add(value); emit Transfer(from, to, value); _moveDelegates(_delegates[from], _delegates[to], value); return true; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) external view returns (uint256) { return _DMCBalances[who]; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) external view returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) external returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /* - Governance Functions - */ /** @notice sets the pendingGov * @param pendingGov_ The address of the rebaser contract to use for authentication. */ function _setPendingGov(address pendingGov_) external onlyGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } /** @notice lets msg.sender accept governance * */ function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } } contract DMC is DMCToken { /** * @notice Initialize the new money market * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize( string memory name_, string memory symbol_, uint8 decimals_, address initial_owner, uint256 initSupply_ ) public { require(initSupply_ > 0, "0 init supply"); super.initialize(name_, symbol_, decimals_); totalSupply = initSupply_; _DMCBalances[initial_owner] = initSupply_; // owner renounces ownership after deployment as they need to set // rebaser and incentivizer // gov = gov_; } } // File: contracts/token/DMCDelegate.sol pragma solidity 0.5.17; contract DMCDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract DMCDelegatorInterface is DMCDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the gov to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } contract DMCDelegateInterface is DMCDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } contract DMCDelegate is DMC, DMCDelegateInterface { /** * @notice Construct an empty delegate */ constructor() public {} /** * @notice Called by the delegator on a delegate to initialize it for duty * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public { // Shh -- currently unused data; // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == gov, "only the gov may call _becomeImplementation"); } /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public { // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == gov, "only the gov may call _resignImplementation"); } }
Storage for a DMC token
contract DMCTokenStorage { using SafeMath for uint256; bool internal _notEntered; string public name; string public symbol; uint8 public decimals; address public gov; address public pendingGov; uint256 public totalSupply; mapping (address => uint256) internal _DMCBalances; mapping (address => mapping (address => uint256)) internal _allowedFragments; }
1,327,815
[ 1, 3245, 364, 279, 463, 20022, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 30072, 1268, 969, 3245, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 1426, 2713, 389, 902, 10237, 329, 31, 203, 203, 565, 533, 1071, 508, 31, 203, 203, 565, 533, 1071, 3273, 31, 203, 203, 565, 2254, 28, 1071, 15105, 31, 203, 203, 565, 1758, 1071, 31841, 31, 203, 203, 565, 1758, 1071, 4634, 43, 1527, 31, 203, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 2713, 389, 16125, 8876, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 2713, 389, 8151, 27588, 31, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xE83B94ECA0e76D9cE0119Fe6D37a539623C097D4/sources/contracts/staking/StakingPoolRewarder.sol
* @notice Calculate the amount of tokens that haven't vested at the current step for a specific user and pool. @dev This function uses the timestamp to identify the current step and returns the unvested amount of tokens. @param user The address of the user. @param poolId The id of the pool. @param timestamp The current timestamp. @return The unvested amount./
function _calculateUnvestedAmountAtCurrentStep( address user, uint256 poolId, uint256 timestamp ) private view returns (uint256) { if (timestamp < uint256(vestingSchedules[user][poolId].startTime) || vestingSchedules[user][poolId].amount == 0) return 0; uint256 currentStepTime = MathUpgradeable.min( timestamp .sub(uint256(vestingSchedules[user][poolId].startTime)) .div(uint256(vestingSchedules[user][poolId].step)) .mul(uint256(vestingSchedules[user][poolId].step)) .add(uint256(vestingSchedules[user][poolId].startTime)), uint256(vestingSchedules[user][poolId].endTime) ); return _calculateUnvestedAmount(user, poolId, currentStepTime); }
8,402,203
[ 1, 8695, 326, 3844, 434, 2430, 716, 15032, 1404, 331, 3149, 622, 326, 783, 2235, 364, 279, 2923, 729, 471, 2845, 18, 225, 1220, 445, 4692, 326, 2858, 358, 9786, 326, 783, 2235, 471, 1135, 326, 640, 90, 3149, 3844, 434, 2430, 18, 225, 729, 1021, 1758, 434, 326, 729, 18, 225, 2845, 548, 1021, 612, 434, 326, 2845, 18, 225, 2858, 1021, 783, 2858, 18, 327, 1021, 640, 90, 3149, 3844, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 11162, 984, 90, 3149, 6275, 861, 3935, 4160, 12, 203, 3639, 1758, 729, 16, 203, 3639, 2254, 5034, 2845, 548, 16, 203, 3639, 2254, 5034, 2858, 203, 565, 262, 3238, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 5508, 411, 2254, 5034, 12, 90, 10100, 27073, 63, 1355, 6362, 6011, 548, 8009, 1937, 950, 13, 747, 331, 10100, 27073, 63, 1355, 6362, 6011, 548, 8009, 8949, 422, 374, 13, 203, 5411, 327, 374, 31, 203, 3639, 2254, 5034, 783, 4160, 950, 273, 2361, 10784, 429, 18, 1154, 12, 203, 5411, 2858, 203, 5411, 263, 1717, 12, 11890, 5034, 12, 90, 10100, 27073, 63, 1355, 6362, 6011, 548, 8009, 1937, 950, 3719, 203, 5411, 263, 2892, 12, 11890, 5034, 12, 90, 10100, 27073, 63, 1355, 6362, 6011, 548, 8009, 4119, 3719, 203, 5411, 263, 16411, 12, 11890, 5034, 12, 90, 10100, 27073, 63, 1355, 6362, 6011, 548, 8009, 4119, 3719, 203, 5411, 263, 1289, 12, 11890, 5034, 12, 90, 10100, 27073, 63, 1355, 6362, 6011, 548, 8009, 1937, 950, 13, 3631, 203, 5411, 2254, 5034, 12, 90, 10100, 27073, 63, 1355, 6362, 6011, 548, 8009, 409, 950, 13, 203, 3639, 11272, 203, 3639, 327, 389, 11162, 984, 90, 3149, 6275, 12, 1355, 16, 2845, 548, 16, 783, 4160, 950, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x9eCcf572E999B4cbeD2B06a64b38dB48E2101982/sources/Trader.sol
T1 - T4: OK V1 - V5: OK V1 - V5: OK
contract OwnableData { address public owner; address public pendingOwner; pragma solidity 0.6.12; }
14,218,945
[ 1, 56, 21, 300, 399, 24, 30, 7791, 776, 21, 300, 776, 25, 30, 7791, 776, 21, 300, 776, 25, 30, 7791, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14223, 6914, 751, 288, 203, 565, 1758, 1071, 3410, 31, 203, 565, 1758, 1071, 4634, 5541, 31, 203, 203, 203, 203, 683, 9454, 18035, 560, 374, 18, 26, 18, 2138, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xBe27CB8FCD8633D9b8Ef2707C90E6238935CEE60/sources/project_/contracts/RealTokenizado.sol
Participant name associated with the token
string public participant;
7,073,463
[ 1, 22540, 508, 3627, 598, 326, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 533, 1071, 14188, 31, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/introspection/IERC165.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC1155/IERC1155.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transfered from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // File: contracts/root/RootToken/IMintableERC1155.sol pragma solidity 0.6.6; interface IMintableERC1155 is IERC1155 { /** * @notice Creates `amount` tokens of token type `id`, and assigns them to `account`. * @dev Should be callable only by MintableERC1155Predicate * Make sure minting is done only by this function * @param account user address for whom token is being minted * @param id token which is being minted * @param amount amount of token being minted * @param data extra byte data to be accompanied with minted tokens */ function mint(address account, uint256 id, uint256 amount, bytes calldata data) external; /** * @notice Batched version of singular token minting, where * for each token in `ids` respective amount to be minted from `amounts` * array, for address `to`. * @dev Should be callable only by MintableERC1155Predicate * Make sure minting is done only by this function * @param to user address for whom token is being minted * @param ids tokens which are being minted * @param amounts amount of each token being minted * @param data extra byte data to be accompanied with minted tokens */ function mintBatch(address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // File: @openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // File: @openzeppelin/contracts/introspection/ERC165.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File: @openzeppelin/contracts/token/ERC1155/ERC1155Receiver.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev _Available since v3.1._ */ abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { constructor() public { _registerInterface( ERC1155Receiver(0).onERC1155Received.selector ^ ERC1155Receiver(0).onERC1155BatchReceived.selector ); } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/Address.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/GSN/Context.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/AccessControl.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts/common/AccessControlMixin.sol pragma solidity 0.6.6; contract AccessControlMixin is AccessControl { string private _revertMsg; function _setupContractId(string memory contractId) internal { _revertMsg = string(abi.encodePacked(contractId, ": INSUFFICIENT_PERMISSIONS")); } modifier only(bytes32 role) { require( hasRole(role, _msgSender()), _revertMsg ); _; } } // File: contracts/lib/RLPReader.sol /* * @author Hamdi Allam [email protected] * Please reach out with any questions or concerns * https://github.com/hamdiallam/Solidity-RLP/blob/e681e25a376dbd5426b509380bc03446f05d0f97/contracts/RLPReader.sol */ pragma solidity 0.6.6; library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint len; uint memPtr; } struct Iterator { RLPItem item; // Item that's being iterated over. uint nextPtr; // Position of the next item in the list. } /* * @dev Returns the next element in the iteration. Reverts if it has not next element. * @param self The iterator. * @return The next element in the iteration. */ function next(Iterator memory self) internal pure returns (RLPItem memory) { require(hasNext(self)); uint ptr = self.nextPtr; uint itemLength = _itemLength(ptr); self.nextPtr = ptr + itemLength; return RLPItem(itemLength, ptr); } /* * @dev Returns true if the iteration has more elements. * @param self The iterator. * @return true if the iteration has more elements. */ function hasNext(Iterator memory self) internal pure returns (bool) { RLPItem memory item = self.item; return self.nextPtr < item.memPtr + item.len; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { uint memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @dev Create an iterator. Reverts if item is not a list. * @param self The RLP item. * @return An 'Iterator' over the item. */ function iterator(RLPItem memory self) internal pure returns (Iterator memory) { require(isList(self)); uint ptr = self.memPtr + _payloadOffset(self.memPtr); return Iterator(self, ptr); } /* * @param the RLP item. */ function rlpLen(RLPItem memory item) internal pure returns (uint) { return item.len; } /* * @param the RLP item. * @return (memPtr, len) pair: location of the item's payload in memory. */ function payloadLocation(RLPItem memory item) internal pure returns (uint, uint) { uint offset = _payloadOffset(item.memPtr); uint memPtr = item.memPtr + offset; uint len = item.len - offset; // data length return (memPtr, len); } /* * @param the RLP item. */ function payloadLen(RLPItem memory item) internal pure returns (uint) { (, uint len) = payloadLocation(item); return len; } /* * @param the RLP item containing the encoded list. */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item)); uint items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { if (item.len == 0) return false; uint8 byte0; uint memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /* * @dev A cheaper version of keccak256(toRlpBytes(item)) that avoids copying memory. * @return keccak256 hash of RLP encoded bytes. */ function rlpBytesKeccak256(RLPItem memory item) internal pure returns (bytes32) { uint256 ptr = item.memPtr; uint256 len = item.len; bytes32 result; assembly { result := keccak256(ptr, len) } return result; } /* * @dev A cheaper version of keccak256(toBytes(item)) that avoids copying memory. * @return keccak256 hash of the item payload. */ function payloadKeccak256(RLPItem memory item) internal pure returns (bytes32) { (uint memPtr, uint len) = payloadLocation(item); bytes32 result; assembly { result := keccak256(memPtr, len) } return result; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); if (result.length == 0) return result; uint ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } // any non-zero byte except "0x80" is considered true function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1); uint result; uint memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } // SEE Github Issue #5. // Summary: Most commonly used RLP libraries (i.e Geth) will encode // "0" as "0x80" instead of as "0". We handle this edge case explicitly // here. if (result == 0 || result == STRING_SHORT_START) { return false; } else { return true; } } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix require(item.len == 21); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint) { require(item.len > 0 && item.len <= 33); (uint memPtr, uint len) = payloadLocation(item); uint result; assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint) { // one byte prefix require(item.len == 33); uint result; uint memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { require(item.len > 0); (uint memPtr, uint len) = payloadLocation(item); bytes memory result = new bytes(len); uint destPtr; assembly { destPtr := add(0x20, result) } copy(memPtr, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint) { if (item.len == 0) return 0; uint count = 0; uint currPtr = item.memPtr + _payloadOffset(item.memPtr); uint endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint memPtr) private pure returns (uint) { uint itemLen; uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint memPtr) private pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy(uint src, uint dest, uint len) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } if (len > 0) { // left over bytes. Mask is used to remove unwanted bytes from the word uint mask = 256 ** (WORD_SIZE - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } } // File: contracts/root/TokenPredicates/ITokenPredicate.sol pragma solidity 0.6.6; /// @title Token predicate interface for all pos portal predicates /// @notice Abstract interface that defines methods for custom predicates interface ITokenPredicate { /** * @notice Deposit tokens into pos portal * @dev When `depositor` deposits tokens into pos portal, tokens get locked into predicate contract. * @param depositor Address who wants to deposit tokens * @param depositReceiver Address (address) who wants to receive tokens on side chain * @param rootToken Token which gets deposited * @param depositData Extra data for deposit (amount for ERC20, token id for ERC721 etc.) [ABI encoded] */ function lockTokens( address depositor, address depositReceiver, address rootToken, bytes calldata depositData ) external; /** * @notice Validates and processes exit while withdraw process * @dev Validates exit log emitted on sidechain. Reverts if validation fails. * @dev Processes withdraw based on custom logic. Example: transfer ERC20/ERC721, mint ERC721 if mintable withdraw * @param sender Address * @param rootToken Token which gets withdrawn * @param logRLPList Valid sidechain log for data like amount, token id etc. */ function exitTokens( address sender, address rootToken, bytes calldata logRLPList ) external; } // File: contracts/common/Initializable.sol pragma solidity 0.6.6; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } contract MintableERC1155Predicate is ITokenPredicate, ERC1155Receiver, AccessControlMixin, Initializable { using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE"); bytes32 public constant TOKEN_TYPE = keccak256("MintableERC1155"); bytes32 public constant TRANSFER_SINGLE_EVENT_SIG = keccak256( "TransferSingle(address,address,address,uint256,uint256)" ); bytes32 public constant TRANSFER_BATCH_EVENT_SIG = keccak256( "TransferBatch(address,address,address,uint256[],uint256[])" ); event LockedBatchMintableERC1155( address indexed depositor, address indexed depositReceiver, address indexed rootToken, uint256[] ids, uint256[] amounts ); constructor() public {} function initialize(address _owner) external initializer { _setupContractId("MintableERC1155Predicate"); _setupRole(DEFAULT_ADMIN_ROLE, _owner); _setupRole(MANAGER_ROLE, _owner); } /** * @notice rejects single transfer */ function onERC1155Received( address, address, uint256, uint256, bytes calldata ) external override returns (bytes4) { return 0; } /** * @notice accepts batch transfer */ function onERC1155BatchReceived( address, address, uint256[] calldata, uint256[] calldata, bytes calldata ) external override returns (bytes4) { return ERC1155Receiver(0).onERC1155BatchReceived.selector; } /** * @notice Lock ERC1155 tokens for deposit, callable only by manager * @param depositor Address who wants to deposit tokens * @param depositReceiver Address (address) who wants to receive tokens on child chain * @param rootToken Token which gets deposited * @param depositData ABI encoded id array and amount array */ function lockTokens( address depositor, address depositReceiver, address rootToken, bytes calldata depositData ) external override only(MANAGER_ROLE) { // forcing batch deposit since supporting both single and batch deposit introduces too much complexity ( uint256[] memory ids, uint256[] memory amounts, bytes memory data ) = abi.decode(depositData, (uint256[], uint256[], bytes)); emit LockedBatchMintableERC1155( depositor, depositReceiver, rootToken, ids, amounts ); IMintableERC1155(rootToken).safeBatchTransferFrom( depositor, address(this), ids, amounts, data ); } // Used when attempting to exit with single token, single amount/ id is converted into // slice of amounts/ ids // Generally size is going to be `1` i.e. single element array, but it's kept generic function makeArrayWithValue(uint256 val, uint size) internal pure returns(uint256[] memory) { require( size > 0, "MintableERC1155Predicate: Invalid resulting array length" ); uint256[] memory vals = new uint256[](size); for (uint256 i = 0; i < size; i++) { vals[i] = val; } return vals; } /** * @notice Creates an array of `size` by repeating provided address, * to be required for passing to batch balance checking function of ERC1155 tokens. * @param addr Address to be repeated `size` times in resulting array * @param size Size of resulting array */ function makeArrayWithAddress(address addr, uint256 size) internal pure returns (address[] memory) { require( addr != address(0), "MintableERC1155Predicate: Invalid address" ); require( size > 0, "MintableERC1155Predicate: Invalid resulting array length" ); address[] memory addresses = new address[](size); for (uint256 i = 0; i < size; i++) { addresses[i] = addr; } return addresses; } /** * @notice Calculates amount of tokens to be minted, by subtracting available * token balances from amount of tokens to be exited * @param tokenBalances Token balances this contract holds for some ordered token ids * @param amountsToBeExited Amount of tokens being exited */ function calculateAmountsToBeMinted( uint256[] memory tokenBalances, uint256[] memory amountsToBeExited ) internal pure returns (uint256[] memory, uint256[] memory, bool) { require( tokenBalances.length == amountsToBeExited.length, "MintableERC1155Predicate: Array length mismatch found" ); // all cells zero initialized uint256[] memory toBeMintedAmounts = new uint256[]( tokenBalances.length ); // all cells zero initialized uint256[] memory toBeTransferredAmounts = new uint256[]( tokenBalances.length ); bool needMintStep; // Iteratively calculating amounts of token to be minted/ transferred // // Please note, in some cases it can be 0, but that will not // be a problem, due to implementation of mint/ transfer logic for ERC1155 for (uint256 i = 0; i < tokenBalances.length; i++) { if (tokenBalances[i] < amountsToBeExited[i]) { toBeMintedAmounts[i] = amountsToBeExited[i] - tokenBalances[i]; toBeTransferredAmounts[i] = tokenBalances[i]; needMintStep = true; } else { toBeTransferredAmounts[i] = amountsToBeExited[i]; } } return (toBeMintedAmounts, toBeTransferredAmounts, needMintStep); } /** * @notice Validates log signature, from and to address * then sends the correct tokenId, amount to withdrawer * callable only by manager * @param rootToken Token which gets withdrawn * @param log Valid ERC1155 TransferSingle burn or TransferBatch burn log from child chain */ function exitTokens( address, address rootToken, bytes memory log ) public override only(MANAGER_ROLE) { RLPReader.RLPItem[] memory logRLPList = log.toRlpItem().toList(); RLPReader.RLPItem[] memory logTopicRLPList = logRLPList[1].toList(); // topics bytes memory logData = logRLPList[2].toBytes(); address withdrawer = address(logTopicRLPList[2].toUint()); // topic2 is from address require( address(logTopicRLPList[3].toUint()) == address(0), // topic3 is to address "MintableERC1155Predicate: INVALID_RECEIVER" ); bytes32 eventSig = bytes32(logTopicRLPList[0].toUint()); if (eventSig == TRANSFER_SINGLE_EVENT_SIG) { (uint256 id, uint256 amount) = abi.decode( logData, (uint256, uint256) ); IMintableERC1155 token = IMintableERC1155(rootToken); uint256 balance = token.balanceOf(address(this), id); if (balance < amount) { token.mint(withdrawer, id, amount - balance, bytes("")); token.safeTransferFrom( address(this), withdrawer, id, balance, bytes("") ); } else { token.safeTransferFrom( address(this), withdrawer, id, amount, bytes("") ); } } else if (eventSig == TRANSFER_BATCH_EVENT_SIG) { (uint256[] memory ids, uint256[] memory amounts) = abi.decode( logData, (uint256[], uint256[]) ); IMintableERC1155 token = IMintableERC1155(rootToken); uint256[] memory balances = token.balanceOfBatch(makeArrayWithAddress(address(this), ids.length), ids); (uint256[] memory toBeMinted, uint256[] memory toBeTransferred, bool needMintStep) = calculateAmountsToBeMinted(balances, amounts); if(needMintStep) { token.mintBatch( withdrawer, ids, toBeMinted, bytes("") ); } token.safeBatchTransferFrom( address(this), withdrawer, ids, toBeTransferred, bytes("") ); } else { revert("MintableERC1155Predicate: INVALID_WITHDRAW_SIG"); } } }
* @notice Calculates amount of tokens to be minted, by subtracting available token balances from amount of tokens to be exited @param tokenBalances Token balances this contract holds for some ordered token ids @param amountsToBeExited Amount of tokens being exited/ all cells zero initialized all cells zero initialized Iteratively calculating amounts of token to be minted/ transferred Please note, in some cases it can be 0, but that will not be a problem, due to implementation of mint/ transfer logic for ERC1155
function calculateAmountsToBeMinted( uint256[] memory tokenBalances, uint256[] memory amountsToBeExited ) internal pure returns (uint256[] memory, uint256[] memory, bool) { require( tokenBalances.length == amountsToBeExited.length, "MintableERC1155Predicate: Array length mismatch found" ); uint256[] memory toBeMintedAmounts = new uint256[]( tokenBalances.length ); uint256[] memory toBeTransferredAmounts = new uint256[]( tokenBalances.length ); bool needMintStep; for (uint256 i = 0; i < tokenBalances.length; i++) { if (tokenBalances[i] < amountsToBeExited[i]) { toBeMintedAmounts[i] = amountsToBeExited[i] - tokenBalances[i]; toBeTransferredAmounts[i] = tokenBalances[i]; needMintStep = true; toBeTransferredAmounts[i] = amountsToBeExited[i]; } } return (toBeMintedAmounts, toBeTransferredAmounts, needMintStep); }
14,889,785
[ 1, 10587, 3844, 434, 2430, 358, 506, 312, 474, 329, 16, 635, 10418, 310, 2319, 1147, 324, 26488, 628, 3844, 434, 2430, 358, 506, 21590, 225, 1147, 38, 26488, 3155, 324, 26488, 333, 6835, 14798, 364, 2690, 5901, 1147, 3258, 225, 3844, 11634, 1919, 6767, 329, 16811, 434, 2430, 3832, 21590, 19, 777, 5983, 3634, 6454, 777, 5983, 3634, 6454, 3016, 17526, 21046, 30980, 434, 1147, 358, 506, 312, 474, 329, 19, 906, 4193, 7801, 4721, 16, 316, 2690, 6088, 518, 848, 506, 374, 16, 1496, 716, 903, 486, 506, 279, 6199, 16, 6541, 358, 4471, 434, 312, 474, 19, 7412, 4058, 364, 4232, 39, 2499, 2539, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4604, 6275, 11634, 1919, 49, 474, 329, 12, 203, 3639, 2254, 5034, 8526, 3778, 1147, 38, 26488, 16, 203, 3639, 2254, 5034, 8526, 3778, 3844, 11634, 1919, 6767, 329, 203, 565, 262, 2713, 16618, 1135, 261, 11890, 5034, 8526, 3778, 16, 2254, 5034, 8526, 3778, 16, 1426, 13, 288, 203, 3639, 2583, 12, 203, 5411, 1147, 38, 26488, 18, 2469, 422, 3844, 11634, 1919, 6767, 329, 18, 2469, 16, 203, 5411, 315, 49, 474, 429, 654, 39, 2499, 2539, 8634, 30, 1510, 769, 13484, 1392, 6, 203, 3639, 11272, 203, 203, 3639, 2254, 5034, 8526, 3778, 21333, 49, 474, 329, 6275, 87, 273, 394, 2254, 5034, 8526, 12, 203, 5411, 1147, 38, 26488, 18, 2469, 203, 3639, 11272, 203, 3639, 2254, 5034, 8526, 3778, 21333, 1429, 4193, 6275, 87, 273, 394, 2254, 5034, 8526, 12, 203, 5411, 1147, 38, 26488, 18, 2469, 203, 3639, 11272, 203, 3639, 1426, 1608, 49, 474, 4160, 31, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1147, 38, 26488, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 2316, 38, 26488, 63, 77, 65, 411, 3844, 11634, 1919, 6767, 329, 63, 77, 5717, 288, 203, 7734, 21333, 49, 474, 329, 6275, 87, 63, 77, 65, 273, 3844, 11634, 1919, 6767, 329, 63, 77, 65, 300, 1147, 38, 26488, 63, 77, 15533, 203, 7734, 21333, 1429, 4193, 6275, 87, 63, 77, 65, 273, 1147, 38, 26488, 63, 77, 15533, 203, 7734, 1608, 49, 474, 4160, 273, 638, 31, 203, 7734, 21333, 1429, 2 ]
./full_match/42161/0x26EFF6c28EB96330BE02d1C2CA1fF68Ae3b4bC08/sources/project_/contracts/Darwin721.sol
* @title Proxy @dev Implements delegation of calls to other contracts, with proper forwarding of return values and bubbling of failures. It defines a fallback function that delegates all calls to the address returned by the abstract _implementation() internal function./
abstract contract Proxy { function implementation() public virtual view returns (address); function _delegate(address impl) internal { assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result } } function _delegate(address impl) internal { assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result } } case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } function _willFallback() internal virtual { } function _fallback() internal { _willFallback(); _delegate(implementation()); } }
16,305,513
[ 1, 3886, 225, 29704, 23595, 434, 4097, 358, 1308, 20092, 16, 598, 5338, 20635, 434, 327, 924, 471, 324, 22298, 2456, 434, 11720, 18, 2597, 11164, 279, 5922, 445, 716, 22310, 777, 4097, 358, 326, 1758, 2106, 635, 326, 8770, 389, 30810, 1435, 2713, 445, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 7659, 288, 203, 203, 225, 445, 4471, 1435, 1071, 5024, 1476, 1135, 261, 2867, 1769, 203, 203, 225, 445, 389, 22216, 12, 2867, 9380, 13, 2713, 288, 203, 565, 19931, 288, 203, 1377, 745, 892, 3530, 12, 20, 16, 374, 16, 745, 13178, 554, 10756, 203, 203, 1377, 2231, 563, 519, 7152, 1991, 12, 31604, 9334, 9380, 16, 374, 16, 745, 13178, 554, 9334, 374, 16, 374, 13, 203, 203, 1377, 327, 892, 3530, 12, 20, 16, 374, 16, 327, 13178, 554, 10756, 203, 203, 1377, 1620, 563, 203, 565, 289, 203, 225, 289, 203, 203, 225, 445, 389, 22216, 12, 2867, 9380, 13, 2713, 288, 203, 565, 19931, 288, 203, 1377, 745, 892, 3530, 12, 20, 16, 374, 16, 745, 13178, 554, 10756, 203, 203, 1377, 2231, 563, 519, 7152, 1991, 12, 31604, 9334, 9380, 16, 374, 16, 745, 13178, 554, 9334, 374, 16, 374, 13, 203, 203, 1377, 327, 892, 3530, 12, 20, 16, 374, 16, 327, 13178, 554, 10756, 203, 203, 1377, 1620, 563, 203, 565, 289, 203, 225, 289, 203, 203, 1377, 648, 374, 288, 15226, 12, 20, 16, 327, 13178, 554, 10756, 289, 203, 1377, 805, 288, 327, 12, 20, 16, 327, 13178, 554, 10756, 289, 203, 225, 445, 389, 20194, 12355, 1435, 2713, 5024, 288, 203, 225, 289, 203, 203, 225, 445, 389, 16471, 1435, 2713, 288, 203, 565, 389, 20194, 12355, 5621, 203, 565, 389, 22216, 12, 30810, 10663, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.1; import "./math/SafeMath.sol"; import "./MultiSigSecured.sol"; import "./Pausable.sol"; /* * @title LedgeriumIndexContract * @author Vivek <https://github.com/bvivek777> * The LedgeriumIndexContract Contract hold the details of the controller and the data contracts * and allows various contracts to function concurrently while referencing each other's * address and providing a mechanism to ensure secure transactions between contracts * */ contract LedgeriumIndexContract is MultiSigSecured, Pausable { using SafeMath for uint32; using SafeMath for uint256; struct Contract{ address currentAddress; uint32 version; address[] addressHistory; bool status; } enum Status { INACTIVE, PENDING, ACTIVE } struct StakeHolder { bool isActive; Status status; } address[] private stakeHolders; mapping(address => StakeHolder) private activeStakeHolders; mapping(string => Contract) private contractMapping; mapping(address => bool) private exists; uint32 private totalStakeHoldersCount; //Total count of active Admin Validators uint32 public activeStakeHoldersCount; bool private isInit; //To check if initial owners are set or not already //List of events event UpdateContractAddress(address indexed proposer, string indexed _contractName, address indexed newAddress); event UpdateContractAddressRejected(address indexed proposer, string indexed _contractName); event AddStakeHolder(address indexed proposer, address indexed stakeHolder); event RemoveStakeHolder(address indexed proposer, address indexed stakeHolder); event GlobalPause(address indexed proposer); event UnPauseGlobal(address indexed proposer); event MinStakeHoldersNeeded(uint8 minNoOfStakeHolders); event RangeStakeHoldersNeeded(uint32 minNoOfStakeHolders, uint32 maxNoOfStakeHolders); event TotalNoOfStakeHolders(uint32 noOfStakeHolders); event InitStakeHolderAdded(address stakeHolderAddress); /** * @dev check whether msg.sender is one of the active admin */ modifier isStakeHolder() { // make sure only activeAdmin can operate require(activeStakeHolders[msg.sender].isActive); _; } /** * @dev check whether isInit is set true or not */ modifier isInitalised() { // make sure isInit flag is set before any logical execution on the contract if(isInit) {_;} } /** * @dev Ensure isInit is set before any logical execution on the contract */ modifier ifNotInitalised() { // if(!isInit) {_;} } /** * @dev Function to initiate contract with adding first admins. The pre-deployed contract will be the owner * @return A success flag */ function init(address[] memory addresses) public { require (addresses.length <= 5); require (!isInit); uint32 len = uint32(addresses.length); for ( uint8 i = 0; i < len; i++ ){ exists[addresses[i]] = true; activeStakeHolders[addresses[i]].isActive = true; activeStakeHolders[addresses[i]].status = Status.ACTIVE; stakeHolders.push(addresses[i]); emit InitStakeHolderAdded(addresses[i]); } activeStakeHoldersCount = len; totalStakeHoldersCount = len; emit TotalNoOfStakeHolders(len); isInit = true; //Important flag! } /** * @dev Internal Function to just append the strings * @return returns the appended string */ function toString(address _address) internal pure returns(string memory s) { return string(abi.encodePacked(_address)); } /** * @dev Function to create proposal to upgrade the contract. It checks validity of msg.sender with isStakeHolder modifier * msg.sender address should be one of the active admin * @param _contractName string, name of the contract * @param _newAddress address, name of the contract * @param _minVotes uint32, name of the contract * @return Emits event RangeStakeHoldersNeeded() for sending the range * @return A success flag */ function createAddressUpdateProposal(string memory _contractName, address _newAddress, uint32 _minVotes) public isContractActive returns(bool res) { require(exists[msg.sender]); require(getMethodStatus("updateAddress")); string memory _temp = append("updateAddress-", _contractName); require(!isBallotActive(_temp)); if(_minVotes > 1 && _minVotes < activeStakeHoldersCount) { emit RangeStakeHoldersNeeded(1, activeStakeHoldersCount); return false; } // assert(! contractMapping[_contractName].status); createBallot( _temp, _newAddress, true, _minVotes, msg.sender ); contractMapping[_contractName].status = true; return true; } /** * @dev Function to vote FOR or AGAINST for a proposal to upgrade the contract. It checks validity of msg.sender with isStakeHolder modifier * msg.sender address should be one of the active admin * @param _contractName string, name of the contract * @param _decision bool, flag to vote FOR or AGAINST * @return Emits event UpdateContractAddress() once the contract address is updated * @return Emits event UpdateContractAddressRejected() if the contract address is rejected due to more no of against votes * @return A success flag */ function voteContractAddress(string memory _contractName, bool _decision) public isContractActive returns(bool res) { require(exists[msg.sender]); require(getMethodStatus("updateAddress")); string memory _temp = append("updateAddress-", _contractName); //string memory message = append("Ballot should exist with ", _temp); require(isBallotActive(_temp)); //string memory message1 = append("Contract update status should be true with ", _contractName); require(contractMapping[_contractName].status); if(_decision) voteFor(_temp, msg.sender); else voteAgainst(_temp, msg.sender); uint32 minVotes = getAcceptThreshold(_temp); uint32[2] memory votes = getVotes(_temp); if(votes[0] >= minVotes) { address oldAddress = contractMapping[_contractName].currentAddress; uint32 version = contractMapping[_contractName].version.add32(1); contractMapping[_contractName].currentAddress = getProposedAddress(_temp); contractMapping[_contractName].version = version; contractMapping[_contractName].addressHistory.push(oldAddress); contractMapping[_contractName].status = false; emit UpdateContractAddress(getProposerAddress(_contractName), _contractName, contractMapping[_contractName].currentAddress); clearBallot(_temp); return true; } if(votes[1] + minVotes > activeStakeHoldersCount) { emit UpdateContractAddressRejected(getProposerAddress(_temp), _contractName); clearBallot(_temp); } return true; } /** * @dev Function to return list of all StakeHolders * @return returns the list */ function createStakeHolderUpdate(address _stakeHolder, bool _decision) public isContractActive isInitalised returns(bool res) { require(exists[msg.sender]); require(getMethodStatus("updateStakeHolder")); string memory _temp = append("updateStakeHolder-", toString(_stakeHolder)); /*string memory message = append("Ballot exists with ", _temp); require(!isBallotActive(_temp), message);*/ // assert(_minVotes > 1); uint32 _minVotes =(activeStakeHoldersCount / 2) + 1; if(!_decision && activeStakeHoldersCount < 3) return false; if(_decision && activeStakeHoldersCount > 21) return false; require(createBallot( _temp, _stakeHolder, _decision, _minVotes, msg.sender )); if(_decision) emit AddStakeHolder(msg.sender, _stakeHolder); else if(!_decision) emit RemoveStakeHolder(msg.sender, _stakeHolder); return true; } /** * @dev Function to create proposal to upgrade the contract. It checks validity of msg.sender with isStakeHolder modifier * msg.sender address should be one of the active admin * @param _newStakeHolder address, concerned stakeholder address * @param _decision bool, flag to vote FOR or AGAINST * @return Emits event UpdateContractAddress() once the contract address is updated * @return Emits event UpdateContractAddressRejected() if the contract address is rejected due to more no of against votes * @return A success flag */ function voteStakeHolder(address _newStakeHolder, bool _decision) public isContractActive isInitalised returns(bool res) { require(exists[msg.sender]); require(getMethodStatus("updateStakeHolder")); string memory _temp = append("updateStakeHolder-", toString(_newStakeHolder)); /* string memory message = append("Ballot should exist with ", _temp); require(isBallotActive(_temp), message);*/ if(_decision) voteFor(_temp, msg.sender); else voteAgainst(_temp, msg.sender); uint32 minVotes = getAcceptThreshold(_temp); uint32[2] memory votes = getVotes(_temp); if(votes[0] >= minVotes) { if(!exists[getProposedAddress(_temp)]) { stakeHolders.push(getProposedAddress(_temp)); exists[getProposedAddress(_temp)] = true; totalStakeHoldersCount = totalStakeHoldersCount.add32(1); } activeStakeHolders[getProposedAddress(_temp)].isActive = true; activeStakeHolders[getProposedAddress(_temp)].status = Status.ACTIVE; activeStakeHoldersCount = activeStakeHoldersCount.add32(1); require(clearBallot(_temp)); return true; } if(votes[1] + minVotes > activeStakeHoldersCount) { activeStakeHolders[getProposedAddress(_temp)].isActive = false; activeStakeHolders[getProposedAddress(_temp)].status = Status.INACTIVE; activeStakeHoldersCount = activeStakeHoldersCount.sub32(1); //emit RemoveAdmin(votes[_address].proposer, _address); exists[ getProposedAddress(_temp) ] = false; require(clearBallot(_temp)); } return true; } /** * @dev Function to return list of all StakeHolders * @return returns the list */ function createGlobalPauseProposal(uint32 _minVotes, bool _decision) public returns(bool) { require(exists[msg.sender]); require(!isBallotActive("stop")); require((_minVotes > 1)); createBallot( "stop", 0x0000000000000000000000000000000000000000, _decision, _minVotes, msg.sender ); return true; } /** * @dev Function to return list of all StakeHolders * @return returns the list */ function votePauseProposal(bool _decision) public returns(bool) { require(exists[msg.sender]); string memory STOP = "stop"; require(isBallotActive(STOP)); if(_decision) voteFor(STOP, msg.sender); else voteAgainst(STOP, msg.sender); uint32 minVotes = getAcceptThreshold(STOP); uint32[2] memory votes = getVotes(STOP); if(votes[0] >= minVotes) { stopContract(); emit GlobalPause(getProposerAddress("stop")); clearBallot(STOP); return true; } if(votes[1] + minVotes > activeStakeHoldersCount) { startContract(); emit UnPauseGlobal(getProposerAddress("stop")); clearBallot(STOP); } return true; } /** * @dev Function to return list of all StakeHolders * @return returns the list */ function getAddress(string memory _contractName) public view returns(address _contractAddress) { return contractMapping[_contractName].currentAddress; } /** * @dev Function to return list of all StakeHolders * @return returns the status */ function pauseMethod(string memory _method) public isContractActive returns(bool) { require(exists[msg.sender]); return stopMethod(_method); } /** * @dev Function to return list of all StakeHolders * @return returns the status */ function unpauseMethod(string memory _method) public isContractActive returns(bool) { require(exists[msg.sender]); return startMethod(_method); } /** * @dev Function to get total StakeHolders * @return returns the number */ function getStakeHoldersCount() public view isStakeHolder returns(uint32) { return totalStakeHoldersCount; } /** * @dev Function to get total active stakeHolders * @return returns the number */ function getActiveStakeHoldersCount() public view isStakeHolder returns(uint32) { return activeStakeHoldersCount; } /** * @dev Function to return list of all StakeHolders * @return returns the list */ function getAllStakeHolders() public view returns(address[] memory) { return stakeHolders; } /** * @dev Function to return list of all active stakeHolders * @return returns the bool */ function isActiveStakeHolder(address _address) public view returns(bool) { return activeStakeHolders[_address].isActive; } /** * @dev Function to return list of all existing StakeHolders * @return returns the bool */ function isExistingStakeHolder(address _address) public view returns(bool) { return exists[_address]; } /** * @dev Function to get who all have voted for current proposal. It checks validity of msg.sender with isStakeHolder modifier * @return returns the array of no of votes FOR and AGAINST */ function getVoted(string memory _method) public view isStakeHolder returns(uint32[2] memory v) { return getVotes(_method); } /** * @dev Function to get who all have voted for current proposal. It checks validity of msg.sender with isAdmin modifier * @return returns the array of no of votes FOR and AGAINST */ // function getProposal(string memory votingString) public view returns(bool) { // return isBallotActive(votingString); // } /** * @dev Function to get original proposer for the current proposal. It checks validity of msg.sender with isAdmin modifier * @return returns the address */ function getProposer(string memory _method) public view isStakeHolder returns(address) { return getProposerAddress(_method); } /** * @dev Function to get whether ballot is active for the method * @return returns the bool */ function isVotingActive(string memory _method) public view returns(bool) { return isBallotActive(_method); } /** * @dev Function to get votes for a particular stakeholder, votesFor and votesAgainst * @return uint32[2] */ function checkStakeholderVotes(address _stakeHolder) public view returns(uint32[2] memory) { require(exists[msg.sender]); string memory _temp = append("updateStakeHolder-", toString(_stakeHolder)); uint32[2] memory votes = getVotes(_temp); return votes; } }
* @dev Function to return list of all StakeHolders @return returns the status/
function pauseMethod(string memory _method) public isContractActive returns(bool) { require(exists[msg.sender]); return stopMethod(_method); }
923,315
[ 1, 2083, 358, 327, 666, 434, 777, 934, 911, 27003, 327, 1135, 326, 1267, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 11722, 1305, 12, 1080, 3778, 389, 2039, 13, 1071, 353, 8924, 3896, 1135, 12, 6430, 13, 288, 203, 202, 202, 6528, 12, 1808, 63, 3576, 18, 15330, 19226, 203, 202, 202, 2463, 2132, 1305, 24899, 2039, 1769, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.19; // TODO: CHECK IF A TABLE ALREADY EXISTS BEFORE CREATING ONE contract SQLStorage { bytes1 comma = 44; bytes1 recordSeparator = 124; // architecture // columnsBundle a column is maximum 32 characters // metadata uint numberOfTables; // table index -> table name mapping(uint => string) tableNames; // table name -> count mapping(string => uint) columnCount; // table name -> count mapping(string => uint) rowCount; // table name -> column index -> column name mapping(string => mapping(uint => string)) columnNames; // table name -> bool mapping(string => bool) tableExists; // table name -> column name -> bool mapping(string => mapping(string => bool)) columnExists; // tablename -> column name -> index mapping(string => mapping(string => uint)) columnIndex; // tablename -> column name -> index -> value mapping(string => mapping(string => mapping(uint => string))) tables; function SQLStorage() public { } function createTable(string tableName, string columns) public { tableNames[numberOfTables] = tableName; numberOfTables += 1; bytes memory characters = bytes(columns); uint charactersLen = characters.length; uint j = 0; for (uint i = 0; i < charactersLen; i += 1) { if (characters[i] == comma) { string memory columnName = substring(columns, j, i); columnNames[tableName][columnCount[tableName]] = columnName; columnIndex[tableName][columnName] = columnCount[tableName]; columnCount[tableName] += 1; columnExists[tableName][columnName] = true; j = i + 1; } } rowCount[tableName] = 0; tableExists[tableName] = true; } // values will be of the form: v1,v2,...,vn,\30 function insert(string tableName, uint numberOfColumns, string columns, string values) public { bytes memory chars = bytes(columns); uint charsLen = chars.length; // get the columns that are getting updated uint j = 0; uint k = 0; uint[] memory indexes = new uint[](numberOfColumns); for (uint i = 0; i < charsLen; i += 1) { if (chars[i] == comma) { string memory columnName = substring(columns, j, i); indexes[k] = columnIndex[tableName][columnName]; k += 1; j = i + 1; } } // update table value and row count j = 0; k = 0; chars = bytes(values); charsLen = chars.length; for (i = 0; i < charsLen; i++) { if (chars[i] == comma) { string memory value = substring(values, j, i); uint insertColumnIndex = indexes[k]; columnName = columnNames[tableName][insertColumnIndex]; uint rowIndex = rowCount[tableName]; tables[tableName][columnName][rowIndex] = value; j = i + 1; k += 1; } if (chars[i] == recordSeparator){ rowCount[tableName] += 1; k = 0; j += 1; } } rowCount[tableName] += 1; } // returns one row at a time function getSelect(string tableName, uint numberOfColumns, uint startRow, uint endRow, string columns) public returns (string) { bytes memory chars = bytes(columns); uint charsLen = chars.length; // get the columns that are getting updated uint j = 0; uint k = 0; uint[] memory indexes = new uint[](numberOfColumns); for (uint i = 0; i < charsLen; i += 1) { if (chars[i] == comma) { string memory columnName = substring(columns, j, i); indexes[k] = columnIndex[tableName][columnName]; k += 1; j = i + 1; } } // first count how large our row will be k = 0; for (i = 0; i < numberOfColumns; i++) { j = indexes[i]; columnName = columnNames[tableName][j]; string memory value = tables[tableName][columnName][startRow]; k += bytes(value).length; } bytes memory row = new bytes(k + numberOfColumns); k = 0; for (i = 0; i < numberOfColumns; i++) { j = indexes[i]; columnName = columnNames[tableName][j]; value = tables[tableName][columnName][startRow]; chars = bytes(value); for (j = 0; j < chars.length; j++) { row[k] = chars[j]; k += 1; } row[k] = ','; k += 1; } return string(row); } function update(string tableName, uint numberOfColumns, uint rowIndex, string columns, string values) public { bytes memory chars = bytes(columns); uint charsLen = chars.length; // get the columns that are getting updated uint j = 0; uint k = 0; uint[] memory indexes = new uint[](numberOfColumns); for (uint i = 0; i < charsLen; i += 1) { if (chars[i] == comma) { string memory columnName = substring(columns, j, i); indexes[k] = columnIndex[tableName][columnName]; k += 1; j = i + 1; } } j = 0; k = 0; chars = bytes(values); charsLen = chars.length; for (i = 0; i < charsLen; i++) { if (chars[i] == comma) { string memory value = substring(values, j, i); uint insertColumnIndex = indexes[k]; columnName = columnNames[tableName][insertColumnIndex]; tables[tableName][columnName][rowIndex] = value; j = i + 1; k += 1; } } } function getTableNumberCounter() public returns (uint) { return numberOfTables; } function getTableName(uint tableIndex) public returns (string) { return tableNames[tableIndex]; } function getValue(string tableName, string column, uint rowNumber) public returns (string) { return tables[tableName][column][rowNumber]; } function getColumnName(string tableName, uint columnIndex) public returns (string) { return columnNames[tableName][columnIndex]; } function getTableExists() public returns (bool) { return true; } function getRowCount(string tableName) public returns (uint) { return rowCount[tableName]; } // function copied from https://ethereum.stackexchange.com/questions/31457/substring-in-solidity function substring(string str, uint startIndex, uint endIndex) internal constant returns (string) { bytes memory strBytes = bytes(str); bytes memory result = new bytes(endIndex - startIndex); for (uint i = startIndex; i < endIndex; i++) result[i - startIndex] = strBytes[i]; return string(result); } // function copied from http://cryptodir.blogspot.com/2016/03/solidity-concat-string.html 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, "", "", ""); } }
returns one row at a time get the columns that are getting updated
function getSelect(string tableName, uint numberOfColumns, uint startRow, uint endRow, string columns) public returns (string) { bytes memory chars = bytes(columns); uint charsLen = chars.length; uint j = 0; uint k = 0; uint[] memory indexes = new uint[](numberOfColumns); for (uint i = 0; i < charsLen; i += 1) { if (chars[i] == comma) { string memory columnName = substring(columns, j, i); indexes[k] = columnIndex[tableName][columnName]; k += 1; j = i + 1; } } for (i = 0; i < numberOfColumns; i++) { j = indexes[i]; columnName = columnNames[tableName][j]; string memory value = tables[tableName][columnName][startRow]; k += bytes(value).length; } bytes memory row = new bytes(k + numberOfColumns); k = 0; for (i = 0; i < numberOfColumns; i++) { j = indexes[i]; columnName = columnNames[tableName][j]; value = tables[tableName][columnName][startRow]; chars = bytes(value); for (j = 0; j < chars.length; j++) { row[k] = chars[j]; k += 1; } row[k] = ','; k += 1; } return string(row); }
12,680,231
[ 1, 6154, 1245, 1027, 622, 279, 813, 336, 326, 2168, 716, 854, 8742, 3526, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 20182, 12, 1080, 4775, 16, 2254, 7922, 3380, 16, 2254, 787, 1999, 16, 2254, 679, 1999, 16, 533, 2168, 13, 203, 565, 1071, 1135, 261, 1080, 13, 203, 565, 288, 203, 3639, 1731, 3778, 5230, 273, 1731, 12, 5112, 1769, 203, 3639, 2254, 5230, 2891, 273, 5230, 18, 2469, 31, 203, 203, 3639, 2254, 525, 273, 374, 31, 203, 3639, 2254, 417, 273, 374, 31, 203, 3639, 2254, 8526, 3778, 5596, 273, 394, 2254, 8526, 12, 2696, 951, 3380, 1769, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 5230, 2891, 31, 277, 1011, 404, 13, 288, 203, 5411, 309, 261, 7549, 63, 77, 65, 422, 8716, 13, 288, 203, 7734, 533, 3778, 7578, 273, 3019, 12, 5112, 16, 525, 16, 277, 1769, 203, 7734, 5596, 63, 79, 65, 273, 14882, 63, 18033, 6362, 2827, 461, 15533, 203, 7734, 417, 1011, 404, 31, 203, 7734, 525, 273, 277, 397, 404, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 364, 261, 77, 273, 374, 31, 277, 411, 7922, 3380, 31, 277, 27245, 288, 203, 5411, 525, 273, 5596, 63, 77, 15533, 203, 5411, 7578, 273, 19975, 63, 18033, 6362, 78, 15533, 203, 5411, 533, 3778, 460, 273, 4606, 63, 18033, 6362, 2827, 461, 6362, 1937, 1999, 15533, 203, 5411, 417, 1011, 1731, 12, 1132, 2934, 2469, 31, 203, 3639, 289, 203, 203, 3639, 1731, 3778, 1027, 273, 394, 1731, 12, 79, 397, 7922, 3380, 1769, 203, 3639, 417, 273, 374, 31, 203, 3639, 364, 261, 77, 273, 374, 31, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* Fully commented standard ERC721 Distilled from OpenZeppelin Docs Base for Building ERC721 by Martin McConnell All the utility without the fluff. */ interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } interface IERC721 is IERC165 { //@dev Emitted when `tokenId` token is transferred from `from` to `to`. event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); //@dev Emitted when `owner` enables `approved` to manage the `tokenId` token. event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); //@dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. event ApprovalForAll(address indexed owner, address indexed operator, bool approved); //@dev Returns the number of tokens in ``owner``'s account. function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from,address to,uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; //@dev Returns if the `operator` is allowed to manage all of the assets of `owner`. function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } interface 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); } 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); } library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _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); } } abstract contract Functionality { function toString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } bool private _reentryKey = false; modifier reentryLock { require(!_reentryKey, "attempt to reenter a locked function"); _reentryKey = true; _; _reentryKey = false; } } // ****************************************************************************************************************************** // ************************************************** Start of Main Contract *************************************************** // ****************************************************************************************************************************** contract dice is IERC721, Ownable, Functionality { using Address for address; // Token name string private _name; // Token symbol string private _symbol; // URI Root Location for Json Files string private _baseURI; // 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; //for setting purchase limits per collection mapping(uint256 => mapping(address => uint256)) public numPurchased; struct diceGroup { bool diceLock; uint256 numTokens; //tokens minted so far uint256 maxTokens; //max tokens of this type uint256 startId; //Start location for tokenID uint256 price; //Cost in wei uint256 payoutPercent; uint256 payoutBalance; uint256 giveawayBalance; uint256 purchaseThreshold; string tokenURI; address payoutAddress; } diceGroup[] collection; //TokenID to collection ID mapping (uint256 => uint256) diceType; //Holder's Dice Bag mapping (address => uint256[]) diceBag; //Global Variables uint256 totalTokensReserved; uint256 primaryBalance; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor() { _name = "DICE"; _symbol = "DICE"; _baseURI = "https://triple7dice.club/metadata/contract.json"; } // **************************************** Internal Functions ******************* function createDice(uint256 maxTokens, uint256 price, string memory uri_, uint256 maxPurchase) external onlyOwner reentryLock { //initialize the new token diceGroup memory newDice; newDice.numTokens = 0; newDice.maxTokens = maxTokens; newDice.startId = totalTokensReserved; newDice.payoutAddress = address(0); newDice.payoutPercent = 0; newDice.giveawayBalance = 0; newDice.price = price; newDice.tokenURI = uri_; newDice.diceLock = true; newDice.purchaseThreshold = maxPurchase; //Incriment the allocation variable totalTokensReserved += maxTokens; //Add the new token to the collection collection.push(newDice); } function mint(uint256 ID, uint256 amount) external payable { diceGroup memory tempId = collection[ID]; uint256 price = tempId.price; require(amount > 0, "You must mint a positive number"); require(numPurchased[ID][_msgSender()] + amount <= tempId.purchaseThreshold, "Can't mint that many"); require(amount + tempId.numTokens + tempId.giveawayBalance <= tempId.maxTokens, "Not enough dice remaining"); require(msg.value >= price * amount, "You can't afford that"); require(!tempId.diceLock, "Those dice are not for sale"); //handle payouts uint256 reserve = (amount * price * tempId.payoutPercent) / 100; uint256 leftoverBalance = (price * amount) - reserve; collection[ID].payoutBalance += reserve; primaryBalance += leftoverBalance; //mint tokens and update tallies uint256 tokenStart = collection[ID].startId + collection[ID].numTokens; for ( uint256 i; i < amount; i++) { _safeMint(_msgSender(), tokenStart + i); diceType[tokenStart + i] = ID; } collection[ID].numTokens +=amount; if ((price * amount) < msg.value) { uint256 change = (msg.value - (price*amount)); (bool success, ) = msg.sender.call{value: change}(""); require(success, "Mint: unable to send change to user"); } } function founderMint(uint256 ID, address[] memory to) external reentryLock{ uint256 arraySize = to.length; require(_msgSender() == collection[ID].payoutAddress || _msgSender() == owner()); diceGroup memory tempId = collection[ID]; require(tempId.numTokens + tempId.giveawayBalance + arraySize <= tempId.maxTokens, "Not enough dice remaining"); uint256 tokenStart = tempId.startId + tempId.numTokens; collection[ID].numTokens += arraySize; if (collection[ID].giveawayBalance >= arraySize) { collection[ID].giveawayBalance -= arraySize; } else { collection[ID].giveawayBalance = 0; } for (uint256 i; i < arraySize; i++) { diceType[tokenStart + i] = ID; _safeMint(to[i], tokenStart + i); } } function assignFounder(uint256 ID, uint256 founderPercentage, address receiver, uint256 freebies) external onlyOwner { //Approve a sponsored account to receive payment or ammend contract terms collection[ID].payoutPercent = founderPercentage; collection[ID].payoutAddress = receiver; collection[ID].giveawayBalance = freebies; } function ownerFunds() external view onlyOwner returns(uint256) { return primaryBalance; } function withdraw(uint256 sendAmount) external onlyOwner { require(sendAmount <= primaryBalance); primaryBalance -= sendAmount; (bool success, ) = msg.sender.call{value: sendAmount}(""); require(success, "Transaction Unsuccessful"); } function receiveFunds(uint256 ID) external reentryLock { //Verify ownership of the token class require(collection[ID].payoutAddress != address(0)); require(_msgSender() == collection[ID].payoutAddress, "Unauthorized Transaction!"); uint256 sendAmount = collection[ID].payoutBalance; collection[ID].payoutBalance = 0; (bool success, ) = msg.sender.call{value: sendAmount}(""); require(success, "Transaction Unsuccessful"); } //@dev See {IERC165-supportsInterface}. Interfaces Supported by this Standard function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC165).interfaceId || interfaceId == dice.onERC721Received.selector; } // **************************************** Metadata Standard Functions ********** //@dev Returns the token collection name. function name() external view returns (string memory){ return _name; } //@dev Returns the token collection symbol. function symbol() external view returns (string memory){ return _symbol; } // ******************************* Dice Interface ******************************** function setPurchaseMax(uint groupID, uint256 maxPerWallet) external { require(_msgSender() == owner() || _msgSender() == collection[groupID].payoutAddress, "unauthorized access"); collection[groupID].purchaseThreshold = maxPerWallet; } function getType(uint256 tokenId) external view returns (uint256) { return diceType[tokenId]; } function getPrice(uint256 groupID) external view returns (uint256) { return collection[groupID].price; } function getDiceMinted(uint256 groupID) external view returns (uint256) { return collection[groupID].numTokens; } function getURI(uint256 groupID) external view returns (string memory) { return collection[groupID].tokenURI; } function getAllDice(address holder) external view returns (uint256[] memory) { return diceBag[holder]; } function setURI(uint256 groupID, string memory uri_) external { require(_msgSender() == owner() || _msgSender() == collection[groupID].payoutAddress, "unauthorized access"); collection[groupID].tokenURI = uri_; } function verifyFunds(uint256 ID) external view returns(uint256) { require(_msgSender() == owner() || _msgSender() == collection[ID].payoutAddress, "unauthorized access"); return collection[ID].payoutBalance; } function lockMint(uint256 ID) external { require(_msgSender() == owner() || _msgSender() == collection[ID].payoutAddress, "unauthorized access"); collection[ID].diceLock = true; } function unlockMint(uint256 ID) external { require(_msgSender() == owner() || _msgSender() == collection[ID].payoutAddress, "unauthorized access"); collection[ID].diceLock = false; } function checkLock(uint256 ID) external view returns(bool) { return collection[ID].diceLock; } // ************************** Internal Functions *********************************** function addDiceToBag(address holder, uint256 tokenId) internal { diceBag[holder].push(tokenId); } function removeDiceFromBag(address holder, uint256 tokenId) internal { uint256[] memory diceCollection = diceBag[holder]; bool foundIt; uint256 index; uint256 length = diceCollection.length; for (uint256 i; i < length; i++) { if (!foundIt) { if (diceCollection[i] == tokenId) { foundIt = true;} } if (foundIt) { if (i+1 < length) { diceCollection[i] = diceCollection[i+1]; index = i; break; } } } //make changes to the actual user bag if (index < length - 1) { diceBag[holder][index] = diceCollection[length - 1]; } diceBag[holder].pop(); } /** * @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 {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, 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(msg.sender, 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(msg.sender, 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 = 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 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(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(ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } // *********************** ERC721 Token Receiver ********************** /** * @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) { //InterfaceID=0x150b7a02 return this.onERC721Received.selector; } /** * @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 { //transfer functions take care of checks so we don't have to if(from != address(0)){ removeDiceFromBag(from, tokenId); } if(to != address(0)){ addDiceToBag(to, tokenId); } } //******************************************************** //**************** Fallback and Generic ****************** //******************************************************** //contractURI function for OpenSea, This is for ALL dice collections function contractURI() external view returns (string memory) { return string(abi.encodePacked(_baseURI)); } // TokenURI for OS function tokenURI(uint256 tokenId) public view returns (string memory) { uint256 groupID = diceType[tokenId]; ///require that token exists require((tokenId - collection[groupID].startId) < collection[groupID].numTokens); return string(abi.encodePacked(collection[groupID].tokenURI, toString((tokenId - collection[groupID].startId)), ".json")); } //Fallback function receive () external payable { primaryBalance += msg.value; } }
Approve a sponsored account to receive payment or ammend contract terms
function assignFounder(uint256 ID, uint256 founderPercentage, address receiver, uint256 freebies) external onlyOwner { collection[ID].payoutPercent = founderPercentage; collection[ID].payoutAddress = receiver; collection[ID].giveawayBalance = freebies; }
1,472,007
[ 1, 12053, 537, 279, 272, 500, 87, 7653, 2236, 358, 6798, 5184, 578, 2125, 81, 409, 6835, 6548, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2683, 42, 465, 765, 12, 11890, 5034, 1599, 16, 2254, 5034, 284, 465, 765, 16397, 16, 1758, 5971, 16, 2254, 5034, 4843, 70, 606, 13, 3903, 1338, 5541, 288, 203, 3639, 1849, 63, 734, 8009, 84, 2012, 8410, 273, 284, 465, 765, 16397, 31, 203, 3639, 1849, 63, 734, 8009, 84, 2012, 1887, 273, 5971, 31, 203, 3639, 1849, 63, 734, 8009, 75, 688, 26718, 13937, 273, 4843, 70, 606, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.16; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20 { function totalSupply() constant returns (uint totalSupply); function balanceOf(address _owner) constant returns (uint balance); function transfer(address _to, uint _value) returns (bool success); function transferFrom(address _from, address _to, uint _value) returns (bool success); function approve(address _spender, uint _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint remaining); // This generates a public event on the blockchain that will notify clients event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } //Token with owner (admin) contract OwnedToken { address public owner; //contract owner (admin) address function OwnedToken () public { owner = msg.sender; } //Check if owner initiate call modifier onlyOwner() { require(msg.sender == owner); _; } /** * Transfer ownership * * @param newOwner The address of the new contract owner */ function transferOwnership(address newOwner) public onlyOwner { owner = newOwner; } } //Contract with name contract NamedOwnedToken is OwnedToken { string public name; //the name for display purposes string public symbol; //the symbol for display purposes function NamedOwnedToken(string tokenName, string tokenSymbol) public { name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes } /** * Change name and symbol * * @param newName The new contract name * @param newSymbol The new contract symbol */ function changeName(string newName, string newSymbol)public onlyOwner { name = newName; symbol = newSymbol; } } contract TSBToken is ERC20, NamedOwnedToken { using SafeMath for uint256; // Public variables of the token uint256 public _totalSupply = 0; //Total number of token issued (1 token = 10^decimals) uint8 public decimals = 18; //Decimals, each 1 token = 10^decimals mapping (address => uint256) public balances; // A map with all balances mapping (address => mapping (address => uint256)) public allowed; //Implement allowence to support ERC20 mapping (address => uint256) public paidETH; //The sum have already been paid to token owner uint256 public accrueDividendsPerXTokenETH = 0; uint256 public tokenPriceETH = 0; mapping (address => uint256) public paydCouponsETH; uint256 public accrueCouponsPerXTokenETH = 0; uint256 public totalCouponsUSD = 0; uint256 public MaxCouponsPaymentUSD = 150000; mapping (address => uint256) public rebuySum; mapping (address => uint256) public rebuyInformTime; uint256 public endSaleTime; uint256 public startRebuyTime; uint256 public reservedSum; bool public rebuyStarted = false; uint public tokenDecimals; uint public tokenDecimalsLeft; /** * Constructor function * * Initializes contract */ function TSBToken( string tokenName, string tokenSymbol ) NamedOwnedToken(tokenName, tokenSymbol) public { tokenDecimals = 10**uint256(decimals - 5); tokenDecimalsLeft = 10**5; startRebuyTime = now + 1 years; endSaleTime = now; } /** * Internal function, calc dividends to transfer when tokens are transfering to another wallet */ function transferDiv(uint startTokens, uint fromTokens, uint toTokens, uint sumPaydFrom, uint sumPaydTo, uint acrued) internal constant returns (uint, uint) { uint sumToPayDividendsFrom = fromTokens.mul(acrued); uint sumToPayDividendsTo = toTokens.mul(acrued); uint sumTransfer = sumPaydFrom.div(startTokens); sumTransfer = sumTransfer.mul(startTokens-fromTokens); if (sumPaydFrom > sumTransfer) { sumPaydFrom -= sumTransfer; if (sumPaydFrom > sumToPayDividendsFrom) { sumTransfer += sumPaydFrom - sumToPayDividendsFrom; sumPaydFrom = sumToPayDividendsFrom; } } else { sumTransfer = sumPaydFrom; sumPaydFrom = 0; } sumPaydTo = sumPaydTo.add(sumTransfer); if (sumPaydTo > sumToPayDividendsTo) { uint differ = sumPaydTo - sumToPayDividendsTo; sumPaydTo = sumToPayDividendsTo; sumPaydFrom = sumPaydFrom.add(differ); if (sumPaydFrom > sumToPayDividendsFrom) { sumPaydFrom = sumToPayDividendsFrom; } } return (sumPaydFrom, sumPaydTo); } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { require(_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require(balances[_from] >= _value); // Check if the sender has enough require(balances[_to] + _value > balances[_to]); // Check for overflows uint startTokens = balances[_from].div(tokenDecimals); balances[_from] -= _value; // Subtract from the sender balances[_to] += _value; // Add the same to the recipient if (balances[_from] == 0) { paidETH[_to] = paidETH[_to].add(paidETH[_from]); } else { uint fromTokens = balances[_from].div(tokenDecimals); uint toTokens = balances[_to].div(tokenDecimals); (paidETH[_from], paidETH[_to]) = transferDiv(startTokens, fromTokens, toTokens, paidETH[_from], paidETH[_to], accrueDividendsPerXTokenETH+accrueCouponsPerXTokenETH); } 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 returns (bool success) { _transfer(msg.sender, _to, _value); return true; } /** * Balance of tokens * * @param _owner The address of token wallet */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } /** * Returns total issued tokens number * */ function totalSupply() public constant returns (uint totalSupply) { return _totalSupply; } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` in behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowed[_from][msg.sender]); // Check allowance allowed[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; return true; } /** * Check allowance for address * * @param _owner The address who authorize to spend * @param _spender The address authorized to spend */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Internal function destroy tokens */ function burnTo(uint256 _value, address adr) internal returns (bool success) { require(balances[adr] >= _value); // Check if the sender has enough require(_value > 0); // Check if the sender has enough uint startTokens = balances[adr].div(tokenDecimals); balances[adr] -= _value; // Subtract from the sender uint endTokens = balances[adr].div(tokenDecimals); uint sumToPayFrom = endTokens.mul(accrueDividendsPerXTokenETH + accrueCouponsPerXTokenETH); uint divETH = paidETH[adr].div(startTokens); divETH = divETH.mul(endTokens); if (divETH > sumToPayFrom) { paidETH[adr] = sumToPayFrom; } else { paidETH[adr] = divETH; } _totalSupply -= _value; // Updates totalSupply Burn(adr, _value); return true; } /** * Delete tokens tokens during the end of croudfunding * (in case of errors made by crowdfnuding participants) * Only owner could call */ function deleteTokens(address adr, uint256 amount) public onlyOwner canMint { burnTo(amount, adr); } bool public mintingFinished = false; event Mint(address indexed to, uint256 amount); event MintFinished(); //Check if it is possible to mint new tokens (mint allowed only during croudfunding) modifier canMint() { require(!mintingFinished); _; } function () public payable { } //Withdraw unused ETH from contract to owner function WithdrawLeftToOwner(uint sum) public onlyOwner { owner.transfer(sum); } /** * Mint additional tokens at the end of croudfunding */ function mintToken(address target, uint256 mintedAmount) public onlyOwner canMint { balances[target] += mintedAmount; uint tokensInX = mintedAmount.div(tokenDecimals); paidETH[target] += tokensInX.mul(accrueDividendsPerXTokenETH + accrueCouponsPerXTokenETH); _totalSupply += mintedAmount; Mint(owner, mintedAmount); Transfer(0x0, target, mintedAmount); } /** * Finish minting */ function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; endSaleTime = now; startRebuyTime = endSaleTime + (180 * 1 days); MintFinished(); return true; } /** * Withdraw accrued dividends and coupons */ function WithdrawDividendsAndCoupons() public { withdrawTo(msg.sender,0); } /** * Owner could initiate a withdrawal of accrued dividends and coupons to some address (in purpose to help users) */ function WithdrawDividendsAndCouponsTo(address _sendadr) public onlyOwner { withdrawTo(_sendadr, tx.gasprice * block.gaslimit); } /** * Internal function to withdraw accrued dividends and coupons */ function withdrawTo(address _sendadr, uint comiss) internal { uint tokensPerX = balances[_sendadr].div(tokenDecimals); uint sumPayd = paidETH[_sendadr]; uint sumToPayRes = tokensPerX.mul(accrueCouponsPerXTokenETH+accrueDividendsPerXTokenETH); uint sumToPay = sumToPayRes.sub(comiss); require(sumToPay>sumPayd); sumToPay = sumToPay.sub(sumPayd); _sendadr.transfer(sumToPay); paidETH[_sendadr] = sumToPayRes; } /** * Owner accrue new sum of dividends and coupons (once per month) */ function accrueDividendandCoupons(uint sumDivFinney, uint sumFinneyCoup) public onlyOwner { sumDivFinney = sumDivFinney * 1 finney; sumFinneyCoup = sumFinneyCoup * 1 finney; uint tokens = _totalSupply.div(tokenDecimals); accrueDividendsPerXTokenETH = accrueDividendsPerXTokenETH.add(sumDivFinney.div(tokens)); accrueCouponsPerXTokenETH = accrueCouponsPerXTokenETH.add(sumFinneyCoup.div(tokens)); } /** * Set a price of token to rebuy */ function setTokenPrice(uint priceFinney) public onlyOwner { tokenPriceETH = priceFinney * 1 finney; } event RebuyInformEvent(address indexed adr, uint256 amount); /** * Inform owner that someone whant to sell tokens * The rebuy proccess allowed in 2 weeks after inform * Only after half a year after croudfunding */ function InformRebuy(uint sum) public { _informRebuyTo(sum, msg.sender); } function InformRebuyTo(uint sum, address adr) public onlyOwner{ _informRebuyTo(sum, adr); } function _informRebuyTo(uint sum, address adr) internal{ require (rebuyStarted || (now >= startRebuyTime)); require (sum <= balances[adr]); rebuyInformTime[adr] = now; rebuySum[adr] = sum; RebuyInformEvent(adr, sum); } /** * Owner could allow rebuy proccess early */ function StartRebuy() public onlyOwner{ rebuyStarted = true; } /** * Sell tokens after 2 weeks from information */ function doRebuy() public { _doRebuyTo(msg.sender, 0); } /** * Contract owner would perform tokens rebuy after 2 weeks from information */ function doRebuyTo(address adr) public onlyOwner { _doRebuyTo(adr, tx.gasprice * block.gaslimit); } function _doRebuyTo(address adr, uint comiss) internal { require (rebuyStarted || (now >= startRebuyTime)); require (now >= rebuyInformTime[adr].add(14 days)); uint sum = rebuySum[adr]; require (sum <= balances[adr]); withdrawTo(adr, 0); if (burnTo(sum, adr)) { sum = sum.div(tokenDecimals); sum = sum.mul(tokenPriceETH); sum = sum.div(tokenDecimalsLeft); sum = sum.sub(comiss); adr.transfer(sum); rebuySum[adr] = 0; } } } contract TSBCrowdFundingContract is NamedOwnedToken{ using SafeMath for uint256; enum CrowdSaleState {NotFinished, Success, Failure} CrowdSaleState public crowdSaleState = CrowdSaleState.NotFinished; uint public fundingGoalUSD = 200000; //Min cap uint public fundingMaxCapUSD = 500000; //Max cap uint public priceUSD = 1; //Price in USD per 1 token uint public USDDecimals = 1 ether; uint public startTime; //crowdfunding start time uint public endTime; //crowdfunding end time uint public bonusEndTime; //crowdfunding end of bonus time uint public selfDestroyTime = 2 weeks; TSBToken public tokenReward; //TSB Token to send uint public ETHPrice = 30000; //Current price of one ETH in USD cents uint public BTCPrice = 400000; //Current price of one BTC in USD cents uint public PriceDecimals = 100; uint public ETHCollected = 0; //Collected sum of ETH uint public BTCCollected = 0; //Collected sum of BTC uint public amountRaisedUSD = 0; //Collected sum in USD uint public TokenAmountToPay = 0; //Number of tokens to distribute (excluding bonus tokens) mapping(address => uint256) public balanceMapPos; struct mapStruct { address mapAddress; uint mapBalanceETH; uint mapBalanceBTC; uint bonusTokens; } mapStruct[] public balanceList; //Array of struct with information about invested sums uint public bonusCapUSD = 100000; //Bonus cap mapping(bytes32 => uint256) public bonusesMapPos; struct bonusStruct { uint balancePos; bool notempty; uint maxBonusETH; uint maxBonusBTC; uint bonusETH; uint bonusBTC; uint8 bonusPercent; } bonusStruct[] public bonusesList; //Array of struct with information about bonuses bool public fundingGoalReached = false; bool public crowdsaleClosed = false; event GoalReached(address beneficiary, uint amountRaised); event FundTransfer(address backer, uint amount, bool isContribution); function TSBCrowdFundingContract( uint _startTime, uint durationInHours, string tokenName, string tokenSymbol ) NamedOwnedToken(tokenName, tokenSymbol) public { // require(_startTime >= now); SetStartTime(_startTime, durationInHours); bonusCapUSD = bonusCapUSD * USDDecimals; } function SetStartTime(uint startT, uint durationInHours) public onlyOwner { startTime = startT; bonusEndTime = startT+ 24 hours; endTime = startT + (durationInHours * 1 hours); } function assignTokenContract(address tok) public onlyOwner { tokenReward = TSBToken(tok); tokenReward.transferOwnership(address(this)); } function () public payable { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; require( withinPeriod && nonZeroPurchase && (crowdSaleState == CrowdSaleState.NotFinished)); uint bonuspos = 0; if (now <= bonusEndTime) { // lastdata = msg.data; bytes32 code = sha3(msg.data); bonuspos = bonusesMapPos[code]; } ReceiveAmount(msg.sender, msg.value, 0, now, bonuspos); } function CheckBTCtransaction() internal constant returns (bool) { return true; } function AddBTCTransactionFromArray (address[] ETHadress, uint[] BTCnum, uint[] TransTime, bytes4[] bonusdata) public onlyOwner { require(ETHadress.length == BTCnum.length); require(TransTime.length == bonusdata.length); require(ETHadress.length == bonusdata.length); for (uint i = 0; i < ETHadress.length; i++) { AddBTCTransaction(ETHadress[i], BTCnum[i], TransTime[i], bonusdata[i]); } } /** * Add transfered BTC, only owner could call * * @param ETHadress The address of ethereum wallet of sender * @param BTCnum the received amount in BTC * 10^18 * @param TransTime the original (BTC) transaction time */ function AddBTCTransaction (address ETHadress, uint BTCnum, uint TransTime, bytes4 bonusdata) public onlyOwner { require(CheckBTCtransaction()); require((TransTime >= startTime) && (TransTime <= endTime)); require(BTCnum != 0); uint bonuspos = 0; if (TransTime <= bonusEndTime) { // lastdata = bonusdata; bytes32 code = sha3(bonusdata); bonuspos = bonusesMapPos[code]; } ReceiveAmount(ETHadress, 0, BTCnum, TransTime, bonuspos); } modifier afterDeadline() { if (now >= endTime) _; } /** * Set price for ETH and BTC, only owner could call * * @param _ETHPrice ETH price in USD cents * @param _BTCPrice BTC price in USD cents */ function SetCryptoPrice(uint _ETHPrice, uint _BTCPrice) public onlyOwner { ETHPrice = _ETHPrice; BTCPrice = _BTCPrice; } /** * Convert sum in ETH plus BTC to USD * * @param ETH ETH sum in wei * @param BTC BTC sum in 10^18 */ function convertToUSD(uint ETH, uint BTC) public constant returns (uint) { uint _ETH = ETH.mul(ETHPrice); uint _BTC = BTC.mul(BTCPrice); return (_ETH+_BTC).div(PriceDecimals); } /** * Calc collected sum in USD */ function collectedSum() public constant returns (uint) { return convertToUSD(ETHCollected,BTCCollected); } /** * Check if min cap was reached (only after finish of crowdfunding) */ function checkGoalReached() public afterDeadline { amountRaisedUSD = collectedSum(); if (amountRaisedUSD >= (fundingGoalUSD * USDDecimals) ){ crowdSaleState = CrowdSaleState.Success; TokenAmountToPay = amountRaisedUSD; GoalReached(owner, amountRaisedUSD); } else { crowdSaleState = CrowdSaleState.Failure; } } /** * Check if max cap was reached */ function checkMaxCapReached() public { amountRaisedUSD = collectedSum(); if (amountRaisedUSD >= (fundingMaxCapUSD * USDDecimals) ){ crowdSaleState = CrowdSaleState.Success; TokenAmountToPay = amountRaisedUSD; GoalReached(owner, amountRaisedUSD); } } function ReceiveAmount(address investor, uint sumETH, uint sumBTC, uint TransTime, uint bonuspos) internal { require(investor != 0x0); uint pos = balanceMapPos[investor]; if (pos>0) { pos--; assert(pos < balanceList.length); assert(balanceList[pos].mapAddress == investor); balanceList[pos].mapBalanceETH = balanceList[pos].mapBalanceETH.add(sumETH); balanceList[pos].mapBalanceBTC = balanceList[pos].mapBalanceBTC.add(sumBTC); } else { mapStruct memory newStruct; newStruct.mapAddress = investor; newStruct.mapBalanceETH = sumETH; newStruct.mapBalanceBTC = sumBTC; newStruct.bonusTokens = 0; pos = balanceList.push(newStruct); balanceMapPos[investor] = pos; pos--; } // update state ETHCollected = ETHCollected.add(sumETH); BTCCollected = BTCCollected.add(sumBTC); checkBonus(pos, sumETH, sumBTC, TransTime, bonuspos); checkMaxCapReached(); } uint public DistributionNextPos = 0; /** * Distribute tokens to next N participants, only owner could call */ function DistributeNextNTokens(uint n) public payable onlyOwner { require(BonusesDistributed); require(DistributionNextPos<balanceList.length); uint nextpos; if (n == 0) { nextpos = balanceList.length; } else { nextpos = DistributionNextPos.add(n); if (nextpos > balanceList.length) { nextpos = balanceList.length; } } uint TokenAmountToPay_local = TokenAmountToPay; for (uint i = DistributionNextPos; i < nextpos; i++) { uint USDbalance = convertToUSD(balanceList[i].mapBalanceETH, balanceList[i].mapBalanceBTC); uint tokensCount = USDbalance.mul(priceUSD); tokenReward.mintToken(balanceList[i].mapAddress, tokensCount + balanceList[i].bonusTokens); TokenAmountToPay_local = TokenAmountToPay_local.sub(tokensCount); balanceList[i].mapBalanceETH = 0; balanceList[i].mapBalanceBTC = 0; } TokenAmountToPay = TokenAmountToPay_local; DistributionNextPos = nextpos; } function finishDistribution() onlyOwner { require ((TokenAmountToPay == 0)||(DistributionNextPos >= balanceList.length)); // tokenReward.finishMinting(); tokenReward.transferOwnership(owner); selfdestruct(owner); } /** * Withdraw the funds * * Checks to see if goal was not reached, each contributor can withdraw * the amount they contributed. */ function safeWithdrawal() public afterDeadline { require(crowdSaleState == CrowdSaleState.Failure); uint pos = balanceMapPos[msg.sender]; require((pos>0)&&(pos<=balanceList.length)); pos--; uint amount = balanceList[pos].mapBalanceETH; balanceList[pos].mapBalanceETH = 0; if (amount > 0) { msg.sender.transfer(amount); FundTransfer(msg.sender, amount, false); } } /** * If something goes wrong owner could destroy the contract after 2 weeks from the crowdfunding end * In this case the token distribution or sum refund will be performed in mannual */ function killContract() public onlyOwner { require(now >= endTime + selfDestroyTime); tokenReward.transferOwnership(owner); selfdestruct(owner); } /** * Add a new bonus code, only owner could call */ function AddBonusToListFromArray(bytes32[] bonusCode, uint[] ETHsumInFinney, uint[] BTCsumInFinney) public onlyOwner { require(bonusCode.length == ETHsumInFinney.length); require(bonusCode.length == BTCsumInFinney.length); for (uint i = 0; i < bonusCode.length; i++) { AddBonusToList(bonusCode[i], ETHsumInFinney[i], BTCsumInFinney[i] ); } } /** * Add a new bonus code, only owner could call */ function AddBonusToList(bytes32 bonusCode, uint ETHsumInFinney, uint BTCsumInFinney) public onlyOwner { uint pos = bonusesMapPos[bonusCode]; if (pos > 0) { pos -= 1; bonusesList[pos].maxBonusETH = ETHsumInFinney * 1 finney; bonusesList[pos].maxBonusBTC = BTCsumInFinney * 1 finney; } else { bonusStruct memory newStruct; newStruct.balancePos = 0; newStruct.notempty = false; newStruct.maxBonusETH = ETHsumInFinney * 1 finney; newStruct.maxBonusBTC = BTCsumInFinney * 1 finney; newStruct.bonusETH = 0; newStruct.bonusBTC = 0; newStruct.bonusPercent = 20; pos = bonusesList.push(newStruct); bonusesMapPos[bonusCode] = pos; } } bool public BonusesDistributed = false; uint public BonusCalcPos = 0; // bytes public lastdata; function checkBonus(uint newBalancePos, uint sumETH, uint sumBTC, uint TransTime, uint pos) internal { if (pos > 0) { pos--; if (!bonusesList[pos].notempty) { bonusesList[pos].balancePos = newBalancePos; bonusesList[pos].notempty = true; } else { if (bonusesList[pos].balancePos != newBalancePos) return; } bonusesList[pos].bonusETH = bonusesList[pos].bonusETH.add(sumETH); // if (bonusesList[pos].bonusETH > bonusesList[pos].maxBonusETH) // bonusesList[pos].bonusETH = bonusesList[pos].maxBonusETH; bonusesList[pos].bonusBTC = bonusesList[pos].bonusBTC.add(sumBTC); // if (bonusesList[pos].bonusBTC > bonusesList[pos].maxBonusBTC) // bonusesList[pos].bonusBTC = bonusesList[pos].maxBonusBTC; } } /** * Calc the number of bonus tokens for N next bonus participants, only owner could call */ function calcNextNBonuses(uint N) public onlyOwner { require(crowdSaleState == CrowdSaleState.Success); require(!BonusesDistributed); uint nextPos = BonusCalcPos + N; if (nextPos > bonusesList.length) nextPos = bonusesList.length; uint bonusCapUSD_local = bonusCapUSD; for (uint i = BonusCalcPos; i < nextPos; i++) { if ((bonusesList[i].notempty) && (bonusesList[i].balancePos < balanceList.length)) { uint maxbonus = convertToUSD(bonusesList[i].maxBonusETH, bonusesList[i].maxBonusBTC); uint bonus = convertToUSD(bonusesList[i].bonusETH, bonusesList[i].bonusBTC); if (maxbonus < bonus) bonus = maxbonus; bonus = bonus.mul(priceUSD); if (bonusCapUSD_local >= bonus) { bonusCapUSD_local = bonusCapUSD_local - bonus; } else { bonus = bonusCapUSD_local; bonusCapUSD_local = 0; } bonus = bonus.mul(bonusesList[i].bonusPercent) / 100; balanceList[bonusesList[i].balancePos].bonusTokens = bonus; if (bonusCapUSD_local == 0) { BonusesDistributed = true; break; } } } bonusCapUSD = bonusCapUSD_local; BonusCalcPos = nextPos; if (nextPos >= bonusesList.length) { BonusesDistributed = true; } } }
* Calc the number of bonus tokens for N next bonus participants, only owner could call/
function calcNextNBonuses(uint N) public onlyOwner { require(crowdSaleState == CrowdSaleState.Success); require(!BonusesDistributed); uint nextPos = BonusCalcPos + N; if (nextPos > bonusesList.length) nextPos = bonusesList.length; uint bonusCapUSD_local = bonusCapUSD; for (uint i = BonusCalcPos; i < nextPos; i++) { if ((bonusesList[i].notempty) && (bonusesList[i].balancePos < balanceList.length)) { uint maxbonus = convertToUSD(bonusesList[i].maxBonusETH, bonusesList[i].maxBonusBTC); uint bonus = convertToUSD(bonusesList[i].bonusETH, bonusesList[i].bonusBTC); if (maxbonus < bonus) bonus = maxbonus; bonus = bonus.mul(priceUSD); if (bonusCapUSD_local >= bonus) { bonusCapUSD_local = bonusCapUSD_local - bonus; bonus = bonusCapUSD_local; bonusCapUSD_local = 0; } bonus = bonus.mul(bonusesList[i].bonusPercent) / 100; balanceList[bonusesList[i].balancePos].bonusTokens = bonus; if (bonusCapUSD_local == 0) { BonusesDistributed = true; break; } } } bonusCapUSD = bonusCapUSD_local; BonusCalcPos = nextPos; if (nextPos >= bonusesList.length) { BonusesDistributed = true; } }
12,838,220
[ 1, 25779, 326, 1300, 434, 324, 22889, 2430, 364, 423, 1024, 324, 22889, 22346, 16, 1338, 3410, 3377, 745, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 7029, 2134, 20626, 265, 6117, 12, 11890, 423, 13, 1071, 1338, 5541, 288, 203, 202, 202, 6528, 12, 71, 492, 72, 30746, 1119, 422, 385, 492, 72, 30746, 1119, 18, 4510, 1769, 203, 202, 202, 6528, 12, 5, 38, 265, 6117, 1669, 11050, 1769, 203, 202, 202, 11890, 1024, 1616, 273, 605, 22889, 25779, 1616, 397, 423, 31, 203, 202, 202, 430, 261, 4285, 1616, 405, 324, 265, 6117, 682, 18, 2469, 13, 7010, 1082, 202, 4285, 1616, 273, 324, 265, 6117, 682, 18, 2469, 31, 203, 3639, 2254, 324, 22889, 4664, 3378, 40, 67, 3729, 273, 324, 22889, 4664, 3378, 40, 31, 377, 203, 202, 202, 1884, 261, 11890, 277, 273, 605, 22889, 25779, 1616, 31, 277, 411, 1024, 1616, 31, 277, 27245, 288, 203, 1082, 202, 430, 225, 14015, 18688, 6117, 682, 63, 77, 8009, 902, 5531, 13, 597, 261, 18688, 6117, 682, 63, 77, 8009, 12296, 1616, 411, 11013, 682, 18, 2469, 3719, 288, 203, 9506, 202, 11890, 943, 18688, 407, 273, 8137, 3378, 40, 12, 18688, 6117, 682, 63, 77, 8009, 1896, 38, 22889, 1584, 44, 16, 324, 265, 6117, 682, 63, 77, 8009, 1896, 38, 22889, 38, 15988, 1769, 203, 9506, 202, 11890, 324, 22889, 273, 8137, 3378, 40, 12, 18688, 6117, 682, 63, 77, 8009, 18688, 407, 1584, 44, 16, 324, 265, 6117, 682, 63, 77, 8009, 18688, 407, 38, 15988, 1769, 203, 9506, 202, 430, 261, 1896, 18688, 407, 411, 324, 22889, 13, 203, 6862, 565, 324, 22889, 273, 943, 18688, 407, 31, 203, 9506, 2 ]
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; // Referencing Uniswap Example Simple Oracle // https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/examples/ExampleOracleSimple.sol import "./IUniswapOracle.sol"; import "../refs/CoreRef.sol"; import "../external/SafeMathCopy.sol"; import "../external/UniswapV2OracleLibrary.sol"; /// @title Uniswap Oracle for ETH/FEI /// @author Fei Protocol /// @notice maintains the TWAP of a uniswap pair contract over a specified duration contract UniswapOracle is IUniswapOracle, CoreRef { using Decimal for Decimal.D256; using SafeMathCopy for uint256; /// @notice the referenced uniswap pair contract IUniswapV2Pair public override pair; bool private isPrice0; /// @notice the previous cumulative price of the oracle snapshot uint256 public override priorCumulative; /// @notice the previous timestamp of the oracle snapshot uint32 public override priorTimestamp; Decimal.D256 private twap = Decimal.zero(); /// @notice the window over which the initial price will "thaw" to the true peg price uint256 public override duration; uint256 private constant FIXED_POINT_GRANULARITY = 2**112; /// @notice UniswapOracle constructor /// @param _core Fei Core for reference /// @param _pair Uniswap Pair to provide TWAP /// @param _duration TWAP duration /// @param _isPrice0 flag for using token0 or token1 for cumulative on Uniswap constructor( address _core, address _pair, uint256 _duration, bool _isPrice0 ) public CoreRef(_core) { pair = IUniswapV2Pair(_pair); // Relative to USD per ETH price isPrice0 = _isPrice0; duration = _duration; _init(); } /// @notice updates the oracle price /// @return true if oracle is updated and false if unchanged function update() external override whenNotPaused returns (bool) { ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 currentTimestamp ) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); uint32 deltaTimestamp = currentTimestamp - priorTimestamp; // allowing underflow per Uniswap Oracle spec if (deltaTimestamp < duration) { return false; } uint256 currentCumulative = _getCumulative(price0Cumulative, price1Cumulative); uint256 deltaCumulative = (currentCumulative - priorCumulative); // allowing underflow per Uniswap Oracle spec // Uniswap stores cumulative price variables as a fixed point 112x112 so we need to divide out the granularity Decimal.D256 memory _twap = Decimal.ratio( deltaCumulative / deltaTimestamp, FIXED_POINT_GRANULARITY ); twap = _twap; priorTimestamp = currentTimestamp; priorCumulative = currentCumulative; emit Update(_twap.asUint256()); return true; } /// @notice determine if read value is stale /// @return true if read value is stale function isOutdated() external view override returns (bool) { (, , uint32 currentTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); uint32 deltaTimestamp = currentTimestamp - priorTimestamp; // allowing underflow per Uniswap Oracle spec return deltaTimestamp >= duration; } /// @notice read the oracle price /// @return oracle price /// @return true if price is valid /// @dev price is to be denominated in USD per X where X can be ETH, etc. /// @dev Can be innacurate if outdated, need to call `isOutdated()` to check function read() external view override returns (Decimal.D256 memory, bool) { bool valid = !(paused() || twap.isZero()); return (twap, valid); } /// @notice set a new duration for the TWAP window function setDuration(uint256 _duration) external override onlyGovernor { duration = _duration; emit DurationUpdate(_duration); } function _init() internal { ( uint256 price0Cumulative, uint256 price1Cumulative, uint32 currentTimestamp ) = UniswapV2OracleLibrary.currentCumulativePrices(address(pair)); priorTimestamp = currentTimestamp; priorCumulative = _getCumulative(price0Cumulative, price1Cumulative); } function _getCumulative(uint256 price0Cumulative, uint256 price1Cumulative) internal view returns (uint256) { return isPrice0 ? price0Cumulative : price1Cumulative; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import "./IOracle.sol"; /// @title Uniswap oracle interface /// @author Fei Protocol interface IUniswapOracle is IOracle { // ----------- Events ----------- event DurationUpdate(uint256 _duration); // ----------- Governor only state changing API ----------- function setDuration(uint256 _duration) external; // ----------- Getters ----------- function priorTimestamp() external returns (uint32); function priorCumulative() external returns (uint256); function duration() external returns (uint256); function pair() external returns (IUniswapV2Pair); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../external/Decimal.sol"; /// @title generic oracle interface for Fei Protocol /// @author Fei Protocol interface IOracle { // ----------- Events ----------- event Update(uint256 _peg); // ----------- State changing API ----------- function update() external returns (bool); // ----------- Getters ----------- function read() external view returns (Decimal.D256 memory, bool); function isOutdated() external view returns (bool); } /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Empty Set Squad <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./SafeMathCopy.sol"; /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMathCopy for uint256; // ============ Constants ============ uint256 private constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({ value: 0 }); } function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function from( uint256 a ) internal pure returns (D256 memory) { return D256({ value: a.mul(BASE) }); } function ratio( uint256 a, uint256 b ) internal pure returns (D256 memory) { return D256({ value: getPartial(a, BASE, b) }); } // ============ Self Functions ============ function add( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE), reason) }); } function mul( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.mul(b) }); } function div( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.div(b) }); } function pow( D256 memory self, uint256 b ) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({ value: self.value }); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.value) }); } function sub( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value) }); } function sub( D256 memory self, D256 memory b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value, reason) }); } function mul( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, b.value, BASE) }); } function div( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, BASE, b.value) }); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo( D256 memory a, D256 memory b ) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathCopy { // To avoid namespace collision between openzeppelin safemath and uniswap safemath /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./ICoreRef.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/utils/Address.sol"; /// @title A Reference to Core /// @author Fei Protocol /// @notice defines some modifiers and utilities around interacting with Core abstract contract CoreRef is ICoreRef, Pausable { ICore private _core; /// @notice CoreRef constructor /// @param core Fei Core to reference constructor(address core) public { _core = ICore(core); } modifier ifMinterSelf() { if (_core.isMinter(address(this))) { _; } } modifier ifBurnerSelf() { if (_core.isBurner(address(this))) { _; } } modifier onlyMinter() { require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter"); _; } modifier onlyBurner() { require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner"); _; } modifier onlyPCVController() { require( _core.isPCVController(msg.sender), "CoreRef: Caller is not a PCV controller" ); _; } modifier onlyGovernor() { require( _core.isGovernor(msg.sender), "CoreRef: Caller is not a governor" ); _; } modifier onlyGuardianOrGovernor() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender), "CoreRef: Caller is not a guardian or governor" ); _; } modifier onlyFei() { require(msg.sender == address(fei()), "CoreRef: Caller is not FEI"); _; } modifier onlyGenesisGroup() { require( msg.sender == _core.genesisGroup(), "CoreRef: Caller is not GenesisGroup" ); _; } modifier postGenesis() { require( _core.hasGenesisGroupCompleted(), "CoreRef: Still in Genesis Period" ); _; } modifier nonContract() { require(!Address.isContract(msg.sender), "CoreRef: Caller is a contract"); _; } /// @notice set new Core reference address /// @param core the new core address function setCore(address core) external override onlyGovernor { _core = ICore(core); emit CoreUpdate(core); } /// @notice set pausable methods to paused function pause() public override onlyGuardianOrGovernor { _pause(); } /// @notice set pausable methods to unpaused function unpause() public override onlyGuardianOrGovernor { _unpause(); } /// @notice address of the Core contract referenced /// @return ICore implementation address function core() public view override returns (ICore) { return _core; } /// @notice address of the Fei contract referenced by Core /// @return IFei implementation address function fei() public view override returns (IFei) { return _core.fei(); } /// @notice address of the Tribe contract referenced by Core /// @return IERC20 implementation address function tribe() public view override returns (IERC20) { return _core.tribe(); } /// @notice fei balance of contract /// @return fei amount held function feiBalance() public view override returns (uint256) { return fei().balanceOf(address(this)); } /// @notice tribe balance of contract /// @return tribe amount held function tribeBalance() public view override returns (uint256) { return tribe().balanceOf(address(this)); } function _burnFeiHeld() internal { fei().burn(feiBalance()); } function _mintFei(uint256 amount) internal { fei().mint(address(this), amount); } } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "../core/ICore.sol"; /// @title CoreRef interface /// @author Fei Protocol interface ICoreRef { // ----------- Events ----------- event CoreUpdate(address indexed _core); // ----------- Governor only state changing api ----------- function setCore(address core) external; function pause() external; function unpause() external; // ----------- Getters ----------- function core() external view returns (ICore); function fei() external view returns (IFei); function tribe() external view returns (IERC20); function feiBalance() external view returns (uint256); function tribeBalance() external view returns (uint256); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./IPermissions.sol"; import "../token/IFei.sol"; /// @title Core Interface /// @author Fei Protocol interface ICore is IPermissions { // ----------- Events ----------- event FeiUpdate(address indexed _fei); event TribeUpdate(address indexed _tribe); event GenesisGroupUpdate(address indexed _genesisGroup); event TribeAllocation(address indexed _to, uint256 _amount); event GenesisPeriodComplete(uint256 _timestamp); // ----------- Governor only state changing api ----------- function init() external; // ----------- Governor only state changing api ----------- function setFei(address token) external; function setTribe(address token) external; function setGenesisGroup(address _genesisGroup) external; function allocateTribe(address to, uint256 amount) external; // ----------- Genesis Group only state changing api ----------- function completeGenesisGroup() external; // ----------- Getters ----------- function fei() external view returns (IFei); function tribe() external view returns (IERC20); function genesisGroup() external view returns (address); function hasGenesisGroupCompleted() external view returns (bool); } pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; /// @title Permissions interface /// @author Fei Protocol interface IPermissions { // ----------- Governor only state changing api ----------- function createRole(bytes32 role, bytes32 adminRole) external; function grantMinter(address minter) external; function grantBurner(address burner) external; function grantPCVController(address pcvController) external; function grantGovernor(address governor) external; function grantGuardian(address guardian) external; function revokeMinter(address minter) external; function revokeBurner(address burner) external; function revokePCVController(address pcvController) external; function revokeGovernor(address governor) external; function revokeGuardian(address guardian) external; // ----------- Revoker only state changing api ----------- function revokeOverride(bytes32 role, address account) external; // ----------- Getters ----------- function isBurner(address _address) external view returns (bool); function isMinter(address _address) external view returns (bool); function isGovernor(address _address) external view returns (bool); function isGuardian(address _address) external view returns (bool); function isPCVController(address _address) external view returns (bool); } pragma solidity ^0.6.2; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title FEI stablecoin interface /// @author Fei Protocol interface IFei is IERC20 { // ----------- Events ----------- event Minting( address indexed _to, address indexed _minter, uint256 _amount ); event Burning( address indexed _to, address indexed _burner, uint256 _amount ); event IncentiveContractUpdate( address indexed _incentivized, address indexed _incentiveContract ); // ----------- State changing api ----------- function burn(uint256 amount) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; // ----------- Burner only state changing api ----------- function burnFrom(address account, uint256 amount) external; // ----------- Minter only state changing api ----------- function mint(address account, uint256 amount) external; // ----------- Governor only state changing api ----------- function setIncentiveContract(address account, address incentive) external; // ----------- Getters ----------- function incentiveContract(address account) external view returns (address); } pragma solidity >=0.6.0; import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; import '@uniswap/lib/contracts/libraries/FixedPoint.sol'; // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices( address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; import './Babylonian.sol'; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; uint private constant Q112 = uint(1) << RESOLUTION; uint private constant Q224 = Q112 << RESOLUTION; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // take the reciprocal of a UQ112x112 function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56)); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.4.0; // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } }
allowing underflow per Uniswap Oracle spec
uint32 deltaTimestamp = currentTimestamp - priorTimestamp;
464,883
[ 1, 5965, 310, 3613, 2426, 1534, 1351, 291, 91, 438, 28544, 857, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 1578, 3622, 4921, 273, 783, 4921, 300, 6432, 4921, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.8.10; /// @title On Chain Payroll /// @author 0xMarty /// @notice Owner pays payee contract OnChainPayroll { /// STATE VARIABLES /// /// @notice Payer of contact address immutable public owner; /// @notice Total amount of eth owner paid uint public ethPayed; /// @notice Amount of eth address has recieved mapping(address => uint) public addressToPaid; /// CONSTRUCTOR /// /// @param _owner Address that pays eth constructor (address _owner) { owner = _owner; } /// PAY FUNCTION /// /// @notice Owner pays specified address /// @param _payee Address of who is being paid function pay(address payable _payee) external payable { require(msg.sender == owner, "not owner"); ethPayed += msg.value; addressToPaid[_payee] += msg.value; _payee.transfer(msg.value); } }
@title On Chain Payroll @author 0xMarty @notice Owner pays payee
contract OnChainPayroll { address immutable public owner; uint public ethPayed; mapping(address => uint) public addressToPaid; constructor (address _owner) { owner = _owner; } function pay(address payable _payee) external payable { require(msg.sender == owner, "not owner"); ethPayed += msg.value; addressToPaid[_payee] += msg.value; _payee.transfer(msg.value); } }
12,245,576
[ 1, 1398, 7824, 13838, 2693, 282, 374, 92, 49, 7325, 282, 16837, 293, 8271, 8843, 1340, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2755, 3893, 9148, 2693, 288, 203, 203, 203, 565, 1758, 11732, 1071, 3410, 31, 203, 565, 2254, 1071, 13750, 9148, 329, 31, 203, 565, 2874, 12, 2867, 516, 2254, 13, 1071, 1758, 774, 16507, 350, 31, 203, 203, 203, 565, 3885, 261, 2867, 389, 8443, 13, 288, 203, 3639, 3410, 273, 389, 8443, 31, 203, 565, 289, 203, 203, 203, 565, 445, 8843, 12, 2867, 8843, 429, 389, 10239, 1340, 13, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 16, 315, 902, 3410, 8863, 203, 540, 203, 3639, 13750, 9148, 329, 1011, 1234, 18, 1132, 31, 203, 3639, 1758, 774, 16507, 350, 63, 67, 10239, 1340, 65, 1011, 1234, 18, 1132, 31, 203, 3639, 389, 10239, 1340, 18, 13866, 12, 3576, 18, 1132, 1769, 7010, 565, 289, 203, 97, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; contract _8thereum { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyTokenHolders() { require(myTokens() > 0); _; } // only people with profits modifier onlyDividendPositive() { require(myDividends(true) > 0); _; } // only owner modifier onlyOwner() { require (address(msg.sender) == owner); _; } // only non-whales modifier onlyNonOwner() { require (address(msg.sender) != owner); _; } modifier onlyFoundersIfNotPublic() { if(!openToThePublic) { require (founders[address(msg.sender)] == true); } _; } modifier onlyApprovedContracts() { if(!gameList[msg.sender]) { require (msg.sender == tx.origin); } _; } /*============================== = 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 ); event lotteryPayout( address customerAddress, uint256 lotterySupply ); event whaleDump( uint256 amount ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "8thereum"; string public symbol = "BIT"; bool public openToThePublic = false; address public owner; uint8 constant public decimals = 18; uint8 constant internal dividendFee = 15; uint256 constant internal tokenPrice = 500000000000000;//0.0005 ether uint256 constant internal magnitude = 2**64; uint256 constant public referralLinkRequirement = 5e18;// 5 token minimum for referral link /*================================ = DATASETS = ================================*/ mapping(address => bool) internal gameList; mapping(address => uint256) internal publicTokenLedger; mapping(address => uint256) public whaleLedger; mapping(address => uint256) public gameLedger; mapping(address => uint256) internal referralBalances; mapping(address => int256) internal payoutsTo_; mapping(address => mapping(address => uint256)) public gamePlayers; mapping(address => bool) internal founders; address[] lotteryPlayers; uint256 internal lotterySupply = 0; uint256 internal tokenSupply = 0; uint256 internal gameSuppply = 0; uint256 internal profitPerShare_; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor() public { // no admin, but the owner of the contract is the address used for whale owner = address(msg.sender); // add founders here... Founders don&#39;t get any special priveledges except being first in line at launch day founders[owner] = true; //owner&#39;s address founders[0x7e474fe5Cfb720804860215f407111183cbc2f85] = true; //KENNY founders[0x5138240E96360ad64010C27eB0c685A8b2eDE4F2] = true; //crypt0b!t founders[0xAA7A7C2DECB180f68F11E975e6D92B5Dc06083A6] = true; //NumberOfThings founders[0x6DC622a04Fd13B6a1C3C5B229CA642b8e50e1e74] = true; //supermanlxvi founders[0x41a21b264F9ebF6cF571D4543a5b3AB1c6bEd98C] = true; //Ravi } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral address */ function buy(address referredyBy) onlyFoundersIfNotPublic() public payable returns(uint256) { require (msg.sender == tx.origin); excludeWhale(referredyBy); } /** * Fallback function to handle ethereum that was send straight to the contract */ function() onlyFoundersIfNotPublic() payable public { require (msg.sender == tx.origin); excludeWhale(0x0); } /** * Converts all of caller&#39;s dividends to tokens. */ function reinvest() onlyDividendPositive() onlyNonOwner() public { require (msg.sender == tx.origin); // 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(SafeMath.mul(dividends, magnitude)); // retrieve ref. bonus dividends += referralBalances[customerAddress]; referralBalances[customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(dividends, 0x0); // fire event for logging emit onReinvestment(customerAddress, dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() onlyNonOwner() onlyTokenHolders() public { require (msg.sender == tx.origin); // get token count for caller & sell them all address customerAddress = address(msg.sender); uint256 _tokens = publicTokenLedger[customerAddress]; if(_tokens > 0) { sell(_tokens); } withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyNonOwner() onlyDividendPositive() public { require (msg.sender == tx.origin); // setup data address customerAddress = msg.sender; uint256 dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[customerAddress] += int256(SafeMath.mul(dividends, magnitude)); // add ref. bonus dividends += referralBalances[customerAddress]; referralBalances[customerAddress] = 0; customerAddress.transfer(dividends); // fire event for logging emit onWithdraw(customerAddress, dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyNonOwner() onlyTokenHolders() public { require (msg.sender == tx.origin); require((_amountOfTokens <= publicTokenLedger[msg.sender]) && (_amountOfTokens > 0)); uint256 _tokens = _amountOfTokens; uint256 ethereum = tokensToEthereum_(_tokens); uint256 dividends = (ethereum * dividendFee) / 100; uint256 taxedEthereum = SafeMath.sub(ethereum, dividends); //Take some divs for the lottery and whale uint256 lotteryAndWhaleFee = dividends / 3; dividends -= lotteryAndWhaleFee; //figure out the lotteryFee uint256 lotteryFee = lotteryAndWhaleFee / 2; //add tokens to the whale uint256 whaleFee = lotteryAndWhaleFee - lotteryFee; whaleLedger[owner] += whaleFee; //add tokens to the lotterySupply lotterySupply += ethereumToTokens_(lotteryFee); // burn the sold tokens tokenSupply -= _tokens; publicTokenLedger[msg.sender] -= _tokens; // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (taxedEthereum * magnitude)); payoutsTo_[msg.sender] -= _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 for logging emit onTokenSell(msg.sender, _tokens, taxedEthereum); } /** * Transfer tokens from the caller to a new holder. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyNonOwner() onlyTokenHolders() onlyApprovedContracts() public returns(bool) { assert(_toAddress != owner); // setup if(gameList[msg.sender] == true) //If game is transferring tokens { require((_amountOfTokens <= gameLedger[msg.sender]) && (_amountOfTokens > 0 )); // exchange tokens gameLedger[msg.sender] -= _amountOfTokens; gameSuppply -= _amountOfTokens; publicTokenLedger[_toAddress] += _amountOfTokens; // update dividend trackers payoutsTo_[_toAddress] += int256(profitPerShare_ * _amountOfTokens); } else if (gameList[_toAddress] == true) //If customer transferring tokens to game { // make sure we have the requested tokens //each game should only cost one token to play require((_amountOfTokens <= publicTokenLedger[msg.sender]) && (_amountOfTokens > 0 && (_amountOfTokens == 1e18))); // exchange tokens publicTokenLedger[msg.sender] -= _amountOfTokens; gameLedger[_toAddress] += _amountOfTokens; gameSuppply += _amountOfTokens; gamePlayers[_toAddress][msg.sender] += _amountOfTokens; // update dividend trackers payoutsTo_[msg.sender] -= int256(profitPerShare_ * _amountOfTokens); } else{ // make sure we have the requested tokens require((_amountOfTokens <= publicTokenLedger[msg.sender]) && (_amountOfTokens > 0 )); // exchange tokens publicTokenLedger[msg.sender] -= _amountOfTokens; publicTokenLedger[_toAddress] += _amountOfTokens; // update dividend trackers payoutsTo_[msg.sender] -= int256(profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += int256(profitPerShare_ * _amountOfTokens); } // fire event for logging emit Transfer(msg.sender, _toAddress, _amountOfTokens); // ERC20 return true; } /*---------- OWNER ONLY FUNCTIONS ----------*/ /** * future games can be added so they can&#39;t earn divs on their token balances */ function setGames(address newGameAddress) onlyOwner() public { gameList[newGameAddress] = true; } /** * Want to prevent snipers from buying prior to launch */ function goPublic() onlyOwner() public returns(bool) { openToThePublic = true; return openToThePublic; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract */ function totalEthereumBalance() public view returns(uint) { return address(this).balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return (tokenSupply + lotterySupply + gameSuppply); //adds the tokens from ambassadors to the supply (but not to the dividends calculation which is based on the supply) } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { return balanceOf(msg.sender); } /** * 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) { return _includeReferralBonus ? dividendsOf(msg.sender) + referralBalances[msg.sender] : dividendsOf(msg.sender) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address customerAddress) view public returns(uint256) { uint256 balance; if (customerAddress == owner) { // to show div balance of owner balance = whaleLedger[customerAddress]; } else if(gameList[customerAddress] == true) { // games can still see their token balance balance = gameLedger[customerAddress]; } else { // to see token balance for anyone else balance = publicTokenLedger[customerAddress]; } return balance; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * publicTokenLedger[customerAddress]) - payoutsTo_[customerAddress]) / magnitude; } /** * Return the buy and sell price of 1 individual token. */ function buyAndSellPrice() public pure returns(uint256) { uint256 ethereum = tokenPrice; uint256 dividends = SafeMath.div(SafeMath.mul(ethereum, dividendFee ), 100); uint256 taxedEthereum = SafeMath.sub(ethereum, dividends); return taxedEthereum; } /** * Function for the frontend to dynamically retrieve the price of buy orders. */ function calculateTokensReceived(uint256 ethereumToSpend) public pure returns(uint256) { require(ethereumToSpend >= tokenPrice); uint256 dividends = SafeMath.div(SafeMath.mul(ethereumToSpend, dividendFee ), 100); uint256 taxedEthereum = SafeMath.sub(ethereumToSpend, dividends); uint256 amountOfTokens = ethereumToTokens_(taxedEthereum); return amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price of sell orders. */ function calculateEthereumReceived(uint256 tokensToSell) public view returns(uint256) { require(tokensToSell <= tokenSupply); uint256 ethereum = tokensToEthereum_(tokensToSell); uint256 dividends = SafeMath.div(SafeMath.mul(ethereum, dividendFee ), 100); uint256 taxedEthereum = SafeMath.sub(ethereum, dividends); return taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function excludeWhale(address referredyBy) onlyNonOwner() internal returns(uint256) { require (msg.sender == tx.origin); uint256 tokenAmount; tokenAmount = purchaseTokens(msg.value, referredyBy); //redirects to purchaseTokens so same functionality if(gameList[msg.sender] == true) { tokenSupply = SafeMath.sub(tokenSupply, tokenAmount); // takes out game&#39;s tokens from the tokenSupply (important for redistribution) publicTokenLedger[msg.sender] = SafeMath.sub(publicTokenLedger[msg.sender], tokenAmount); // takes out game&#39;s tokens from its ledger so it is "officially" holding 0 tokens. (=> doesn&#39;t receive dividends anymore) gameLedger[msg.sender] += tokenAmount; //it gets a special ledger so it can&#39;t sell its tokens gameSuppply += tokenAmount; // we need this for a correct totalSupply() number later } return tokenAmount; } function purchaseTokens(uint256 incomingEthereum, address referredyBy) internal returns(uint256) { require (msg.sender == tx.origin); // data setup uint256 undividedDivs = SafeMath.div(SafeMath.mul(incomingEthereum, dividendFee ), 100); //divide the divs uint256 lotteryAndWhaleFee = undividedDivs / 3; uint256 referralBonus = lotteryAndWhaleFee; uint256 dividends = SafeMath.sub(undividedDivs, (referralBonus + lotteryAndWhaleFee)); uint256 taxedEthereum = incomingEthereum - undividedDivs; uint256 amountOfTokens = ethereumToTokens_(taxedEthereum); uint256 whaleFee = lotteryAndWhaleFee / 2; //add divs to whale whaleLedger[owner] += whaleFee; //add tokens to the lotterySupply lotterySupply += ethereumToTokens_(lotteryAndWhaleFee - whaleFee); //add entry to lottery lotteryPlayers.push(msg.sender); uint256 fee = dividends * magnitude; require(amountOfTokens > 0 && (amountOfTokens + tokenSupply) > tokenSupply); // is the user referred by a masternode? if( // is this a referred purchase? referredyBy != 0x0000000000000000000000000000000000000000 && // no cheating! referredyBy != msg.sender && //can&#39;t use games for referralBonus gameList[referredyBy] == false && // does the referrer have at least 5 tokens? publicTokenLedger[referredyBy] >= referralLinkRequirement ) { // wealth redistribution referralBalances[referredyBy] += referralBonus; } else { // no ref purchase // add the referral bonus back dividends += referralBonus; fee = dividends * magnitude; } uint256 payoutDividends = isWhalePaying(); // we can&#39;t give people infinite ethereum if(tokenSupply > 0) { // add tokens to the pool tokenSupply += amountOfTokens; // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += ((payoutDividends + dividends) * magnitude / (tokenSupply)); // calculate the amount of tokens the customer receives over his purchase fee -= fee-(amountOfTokens * (dividends * magnitude / (tokenSupply))); } else { // add tokens to the pool tokenSupply = amountOfTokens; //if there are zero tokens prior to this buy, and the whale is triggered, send dividends back to whale if(whaleLedger[owner] == 0) { whaleLedger[owner] = payoutDividends; } } // update circulating supply & the ledger address for the customer publicTokenLedger[msg.sender] += amountOfTokens; // Tells the contract that the buyer doesn&#39;t deserve dividends for the tokens before they owned them; // BUT, you still get the whale&#39;s divs from your purchase.... so, you still get SOMETHING. int256 _updatedPayouts = int256((profitPerShare_ * amountOfTokens) - fee); payoutsTo_[msg.sender] += _updatedPayouts; // fire event for logging emit onTokenPurchase(msg.sender, incomingEthereum, amountOfTokens, referredyBy); return amountOfTokens; } /** * Calculate token sell value. * It&#39;s a simple algorithm. Hopefully, you don&#39;t need a whitepaper with it in scientific notation. */ function isWhalePaying() private returns(uint256) { uint256 payoutDividends = 0; // this is where we check for lottery winner if(whaleLedger[owner] >= 1 ether) { if(lotteryPlayers.length > 0) { uint256 winner = uint256(blockhash(block.number-1))%lotteryPlayers.length; publicTokenLedger[lotteryPlayers[winner]] += lotterySupply; emit lotteryPayout(lotteryPlayers[winner], lotterySupply); tokenSupply += lotterySupply; lotterySupply = 0; delete lotteryPlayers; } //whale pays out everyone its divs payoutDividends = whaleLedger[owner]; whaleLedger[owner] = 0; emit whaleDump(payoutDividends); } return payoutDividends; } /** * Calculate Token price based on an amount of incoming ethereum *It&#39;s a simple algorithm. Hopefully, you don&#39;t need a whitepaper with it in scientific notation. */ function ethereumToTokens_(uint256 ethereum) internal pure returns(uint256) { uint256 tokensReceived = ((ethereum / tokenPrice) * 1e18); return tokensReceived; } /** * Calculate token sell value. * It&#39;s a simple algorithm. Hopefully, you don&#39;t need a whitepaper with it in scientific notation. */ function tokensToEthereum_(uint256 coin) internal pure returns(uint256) { uint256 ethReceived = tokenPrice * (SafeMath.div(coin, 1e18)); return ethReceived; } } /** * @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&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
* Withdraws all of the callers earnings./ setup data update dividend tracker add ref. bonus fire event for logging
function withdraw() onlyNonOwner() onlyDividendPositive() public { require (msg.sender == tx.origin); address customerAddress = msg.sender; payoutsTo_[customerAddress] += int256(SafeMath.mul(dividends, magnitude)); dividends += referralBalances[customerAddress]; referralBalances[customerAddress] = 0; customerAddress.transfer(dividends); emit onWithdraw(customerAddress, dividends); }
2,284,225
[ 1, 1190, 9446, 87, 777, 434, 326, 19932, 425, 1303, 899, 18, 19, 3875, 501, 1089, 31945, 9745, 527, 1278, 18, 324, 22889, 4452, 871, 364, 2907, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 1435, 203, 3639, 1338, 3989, 5541, 1435, 203, 3639, 1338, 7244, 26746, 14900, 1435, 203, 3639, 1071, 203, 565, 288, 203, 3639, 2583, 261, 3576, 18, 15330, 422, 2229, 18, 10012, 1769, 203, 540, 203, 3639, 1758, 6666, 1887, 273, 1234, 18, 15330, 31, 203, 540, 203, 3639, 293, 2012, 11634, 67, 63, 10061, 1887, 65, 1011, 225, 509, 5034, 12, 9890, 10477, 18, 16411, 12, 2892, 350, 5839, 16, 13463, 10019, 203, 540, 203, 3639, 3739, 350, 5839, 1011, 1278, 29084, 38, 26488, 63, 10061, 1887, 15533, 203, 3639, 1278, 29084, 38, 26488, 63, 10061, 1887, 65, 273, 374, 31, 203, 540, 203, 3639, 6666, 1887, 18, 13866, 12, 2892, 350, 5839, 1769, 203, 540, 203, 3639, 3626, 603, 1190, 9446, 12, 10061, 1887, 16, 3739, 350, 5839, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/83/0x7473a3E6f3d7A4F33F59345E971D2d04d1fe299F/sources/Bridge.sol
@dev Returns the hash of internal node, calculated from child nodes.
function merkleInnerHash(bytes32 left, bytes32 right) internal pure returns (bytes32) { return sha256(abi.encodePacked(uint8(1), left, right)); }
8,828,753
[ 1, 1356, 326, 1651, 434, 2713, 756, 16, 8894, 628, 1151, 2199, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 30235, 2857, 2310, 12, 3890, 1578, 2002, 16, 1731, 1578, 2145, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 3890, 1578, 13, 203, 565, 288, 203, 3639, 327, 6056, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 11890, 28, 12, 21, 3631, 2002, 16, 2145, 10019, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: Unlicense pragma solidity ^0.8.0; import "@openzeppelin/contracts/interfaces/IERC165.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "./Controllable.sol"; import "./ITokenSale.sol"; /// tokensale implementation contract TokenSale is ITokenSale, Controllable, Initializable { address private payee; address private soldToken; uint256 private salePrice_; uint256 private issueCount; uint256 private maxCount; uint256 private vipReserve; uint256 private vipIssued; TokenMinting[] private _purchasers; TokenMinting[] private _mintees; address private _partner; uint256 private _permill; bool private _openState; /// @notice Called to purchase some quantity of a token /// @param _soldToken - the erc721 address /// @param _salePrice - the sale price /// @param _maxCount - the max quantity /// @param _vipReserve - the vip reserve to set aside for minting directly constructor(address _soldToken, uint256 _salePrice, uint256 _maxCount, uint256 _vipReserve) { _addController(msg.sender); payee = msg.sender; soldToken = _soldToken; salePrice_ = _salePrice; issueCount = 0; maxCount = _maxCount; vipReserve = _vipReserve; vipIssued = 0; } /// @dev called after constructor once to init stuff function initialize(address partner, uint256 permill) public initializer { require(IMintable(soldToken).getMinter() == address(this), "soldToken must be controllable by this contract"); _partner = partner; _permill = permill; } /// @dev create a token hash using the address of this objcet, sender address and the current issue count function _createTokenHash() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(address(this), msg.sender, issueCount))); } /// @notice Called to purchase some quantity of a token /// @param receiver - the address of the account receiving the item /// @param quantity - the quantity to purchase. max 5. function purchase(address receiver, uint256 quantity) external payable override returns (TokenMinting[] memory mintings) { require(issueCount + quantity + vipReserve <= maxCount, "cannot purchase more than maxCount"); require(salePrice_ * quantity <= msg.value, "must attach funds to purchase items"); require(quantity > 0 && quantity <= 5, "cannot purchase more than 5 items"); require(_openState, "cannot mint when tokensale is closed"); // mint the desired tokens to the receiver mintings = new TokenMinting[](quantity); for(uint256 i = 0; i < quantity; i++) { TokenMinting memory _minting = TokenMinting(receiver, _createTokenHash()); // create a record of this new minting _purchasers.push(_minting); // and get a refence to it mintings[i] = _minting; issueCount = issueCount + 1; // mint the token IMintable(soldToken).mint(receiver, _minting.tokenHash); // emit an event to that respect emit TokenMinted(receiver, _minting.tokenHash, 0); } uint256 partnerShare = 0; // transfer to partner share if(_partner != address(0) && _permill > 0) { partnerShare = msg.value * _permill / 1000000; payable(_partner).transfer(partnerShare); } uint256 ourShare = msg.value - partnerShare; payable(payee).transfer(ourShare); } /// @notice returns the sale price in ETH for the given quantity. /// @param quantity - the quantity to purchase. max 5. /// @return price - the sale price for the given quantity function salePrice(uint256 quantity) external view override returns (uint256 price) { price = salePrice_ * quantity; } /// @notice Mint a specific tokenhash to a specific address ( up to har-cap limit) /// only for controller of token /// @param receiver - the address of the account receiving the item /// @param tokenHash - token hash to mint to the receiver function mint(address receiver, uint256 tokenHash) external override onlyController { require(vipIssued < vipReserve, "cannot mint more than the reserve"); require(issueCount < maxCount, "cannot mint more than maxCount"); vipIssued = vipIssued + 1; issueCount = issueCount + 1; _mintees.push(TokenMinting(receiver, _createTokenHash())); IMintable(soldToken).mint(receiver, tokenHash); // emit an event to that respect emit TokenMinted(receiver, tokenHash, 1); } /// @notice set the revenue partner on this tokensale. we split revenue with the partner /// only for controller of token /// @param partner - the address of the partner. will receive x%% of the revenue /// @param permill - permilliage of the revenue to be split. min 0 max 1000000 function setRevenuePartner(address partner, uint256 permill) external override onlyController { require(permill >= 0 && permill <= 1000000, "permill must be between 0 and 1000000"); _partner = partner; _permill = permill; emit RevenuePartnerChanged(partner, permill); } /// @notice get the revenue partner on this tokensale. we split revenue with the partner /// @return partner - the address of the partner. will receive x%% of the revenue /// @return permill - permilliage of the revenue to be split. permill = 1 / 1000000 function getRevenuePartner() external view override returns (address partner, uint256 permill) { return (_partner, _permill); } /// @notice open / close the tokensale /// only for controller of token /// @param openState - the open state of the tokensale function setOpenState(bool openState) external override onlyController { _openState = openState; } /// @notice get the token sale open state /// @return openState - the open state of the tokensale function getOpenState() external view override returns (bool openState) { openState = _openState; } /// @notice set the psale price /// only for controller of token /// @param _salePrice - the open state of the tokensale function setSalePrice(uint256 _salePrice) external override onlyController { require(salePrice_ > 0, "salePrice must be greater than 0"); salePrice_ = _salePrice; } /// @notice get the token sale price /// @return salePrice - the open state of the tokensale function getSalePrice() external view override returns (uint256) { return salePrice_; } /// @notice set the psale price /// only for controller of token /// @param _payee - the open state of the tokensale function setPayee(address _payee) external override onlyController { require(_payee != address(0), "payee cannoot be zero address"); payee = _payee; emit PayeeChanged(payee); } /// @notice get the token sale price /// @return salePrice - the open state of the tokensale function getPayee() external view override returns (address) { return payee; } /// @notice get the address of the sole token /// @return token - the address of the sole token function getSaleToken() external view override returns (address token) { return soldToken; } /// @notice get the total list of purchasers /// @return _list - total list of purchasers function purchaserList() external view override returns (TokenMinting[] memory _list) { _list = _purchasers; } /// @notice get the total list of minters /// @return _list - total list of purchasers function minterList() external view override returns (TokenMinting[] memory _list) { _list = _mintees; } }
@dev create a token hash using the address of this objcet, sender address and the current issue count
function _createTokenHash() internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(address(this), msg.sender, issueCount))); }
15,835,799
[ 1, 2640, 279, 1147, 1651, 1450, 326, 1758, 434, 333, 1081, 71, 278, 16, 5793, 1758, 471, 326, 783, 5672, 1056, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 2640, 1345, 2310, 1435, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 2254, 5034, 12, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 2867, 12, 2211, 3631, 1234, 18, 15330, 16, 5672, 1380, 3719, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; import './BaseCDPManager.sol'; import '../interfaces/IOracleRegistry.sol'; import '../interfaces/IOracleUsd.sol'; import '../interfaces/IWETH.sol'; import '../interfaces/IVault.sol'; import '../interfaces/ICDPRegistry.sol'; import '../interfaces/vault-managers/parameters/IVaultManagerParameters.sol'; import '../interfaces/IVaultParameters.sol'; import '../interfaces/IToken.sol'; import '../helpers/ReentrancyGuard.sol'; import '../helpers/SafeMath.sol'; /** * @title CDPManager01 **/ contract CDPManager01 is BaseCDPManager { using SafeMath for uint; address payable public immutable WETH; /** * @param _vaultManagerParameters The address of the contract with Vault manager parameters * @param _oracleRegistry The address of the oracle registry * @param _cdpRegistry The address of the CDP registry * @param _vaultManagerBorrowFeeParameters The address of the vault manager borrow fee parameters **/ constructor(address _vaultManagerParameters, address _oracleRegistry, address _cdpRegistry, address _vaultManagerBorrowFeeParameters) BaseCDPManager(_vaultManagerParameters, _oracleRegistry, _cdpRegistry, _vaultManagerBorrowFeeParameters) { WETH = IVault(IVaultParameters(IVaultManagerParameters(_vaultManagerParameters).vaultParameters()).vault()).weth(); } // only accept ETH via fallback from the WETH contract receive() external payable { require(msg.sender == WETH, "Unit Protocol: RESTRICTED"); } /** * @notice Depositing tokens must be pre-approved to Vault address * @notice Borrow fee in USDP tokens must be pre-approved to CDP manager address * @notice position actually considered as spawned only when debt > 0 * @dev Deposits collateral and/or borrows USDP * @param asset The address of the collateral * @param assetAmount The amount of the collateral to deposit * @param usdpAmount The amount of USDP token to borrow **/ function join(address asset, uint assetAmount, uint usdpAmount) public nonReentrant checkpoint(asset, msg.sender) { require(usdpAmount != 0 || assetAmount != 0, "Unit Protocol: USELESS_TX"); require(IToken(asset).decimals() <= 18, "Unit Protocol: NOT_SUPPORTED_DECIMALS"); if (usdpAmount == 0) { vault.depositMain(asset, msg.sender, assetAmount); } else { _ensureOracle(asset); bool spawned = vault.debts(asset, msg.sender) != 0; if (!spawned) { // spawn a position vault.spawn(asset, msg.sender, oracleRegistry.oracleTypeByAsset(asset)); } if (assetAmount != 0) { vault.depositMain(asset, msg.sender, assetAmount); } // mint USDP to owner vault.borrow(asset, msg.sender, usdpAmount); _chargeBorrowFee(asset, msg.sender, usdpAmount); // check collateralization _ensurePositionCollateralization(asset, msg.sender); } // fire an event emit Join(asset, msg.sender, assetAmount, usdpAmount); } /** * @dev Deposits ETH and/or borrows USDP * @param usdpAmount The amount of USDP token to borrow **/ function join_Eth(uint usdpAmount) external payable { if (msg.value != 0) { IWETH(WETH).deposit{value: msg.value}(); require(IWETH(WETH).transfer(msg.sender, msg.value), "Unit Protocol: WETH_TRANSFER_FAILED"); } join(WETH, msg.value, usdpAmount); } /** * @notice Tx sender must have a sufficient USDP balance to pay the debt * @dev Withdraws collateral and repays specified amount of debt * @param asset The address of the collateral * @param assetAmount The amount of the collateral to withdraw * @param usdpAmount The amount of USDP to repay **/ function exit(address asset, uint assetAmount, uint usdpAmount) public nonReentrant checkpoint(asset, msg.sender) returns (uint) { // check usefulness of tx require(assetAmount != 0 || usdpAmount != 0, "Unit Protocol: USELESS_TX"); uint debt = vault.debts(asset, msg.sender); // catch full repayment if (usdpAmount > debt) { usdpAmount = debt; } if (assetAmount == 0) { _repay(asset, msg.sender, usdpAmount); } else { if (debt == usdpAmount) { vault.withdrawMain(asset, msg.sender, assetAmount); if (usdpAmount != 0) { _repay(asset, msg.sender, usdpAmount); } } else { _ensureOracle(asset); // withdraw collateral to the owner address vault.withdrawMain(asset, msg.sender, assetAmount); if (usdpAmount != 0) { _repay(asset, msg.sender, usdpAmount); } vault.update(asset, msg.sender); _ensurePositionCollateralization(asset, msg.sender); } } // fire an event emit Exit(asset, msg.sender, assetAmount, usdpAmount); return usdpAmount; } /** * @notice Repayment is the sum of the principal and interest * @dev Withdraws collateral and repays specified amount of debt * @param asset The address of the collateral * @param assetAmount The amount of the collateral to withdraw * @param repayment The target repayment amount **/ function exit_targetRepayment(address asset, uint assetAmount, uint repayment) external returns (uint) { uint usdpAmount = _calcPrincipal(asset, msg.sender, repayment); return exit(asset, assetAmount, usdpAmount); } /** * @notice Withdraws WETH and converts to ETH * @param ethAmount ETH amount to withdraw * @param usdpAmount The amount of USDP token to repay **/ function exit_Eth(uint ethAmount, uint usdpAmount) public returns (uint) { usdpAmount = exit(WETH, ethAmount, usdpAmount); require(IWETH(WETH).transferFrom(msg.sender, address(this), ethAmount), "Unit Protocol: WETH_TRANSFER_FROM_FAILED"); IWETH(WETH).withdraw(ethAmount); (bool success, ) = msg.sender.call{value:ethAmount}(""); require(success, "Unit Protocol: ETH_TRANSFER_FAILED"); return usdpAmount; } /** * @notice Repayment is the sum of the principal and interest * @notice Withdraws WETH and converts to ETH * @param ethAmount ETH amount to withdraw * @param repayment The target repayment amount **/ function exit_Eth_targetRepayment(uint ethAmount, uint repayment) external returns (uint) { uint usdpAmount = _calcPrincipal(WETH, msg.sender, repayment); return exit_Eth(ethAmount, usdpAmount); } function _ensurePositionCollateralization(address asset, address owner) internal view { // collateral value of the position in USD uint usdValue_q112 = getCollateralUsdValue_q112(asset, owner); // USD limit of the position uint usdLimit = usdValue_q112 * vaultManagerParameters.initialCollateralRatio(asset) / Q112 / 100; // revert if collateralization is not enough require(vault.getTotalDebt(asset, owner) <= usdLimit, "Unit Protocol: UNDERCOLLATERALIZED"); } // Liquidation Trigger /** * @dev Triggers liquidation of a position * @param asset The address of the collateral token of a position * @param owner The owner of the position **/ function triggerLiquidation(address asset, address owner) external nonReentrant { _ensureOracle(asset); // USD value of the collateral uint usdValue_q112 = getCollateralUsdValue_q112(asset, owner); // reverts if a position is not liquidatable require(_isLiquidatablePosition(asset, owner, usdValue_q112), "Unit Protocol: SAFE_POSITION"); uint liquidationDiscount_q112 = usdValue_q112.mul( vaultManagerParameters.liquidationDiscount(asset) ).div(DENOMINATOR_1E5); uint initialLiquidationPrice = usdValue_q112.sub(liquidationDiscount_q112).div(Q112); // sends liquidation command to the Vault vault.triggerLiquidation(asset, owner, initialLiquidationPrice); // fire an liquidation event emit LiquidationTriggered(asset, owner); } function getCollateralUsdValue_q112(address asset, address owner) public view returns (uint) { return IOracleUsd(oracleRegistry.oracleByAsset(asset)).assetToUsd(asset, vault.collaterals(asset, owner)); } function _ensureOracle(address asset) internal view { uint oracleType = oracleRegistry.oracleTypeByAsset(asset); require(oracleType != 0, "Unit Protocol: INVALID_ORACLE_TYPE"); address oracle = oracleRegistry.oracleByType(oracleType); require(oracle != address(0), "Unit Protocol: DISABLED_ORACLE"); } /** * @dev Determines whether a position is liquidatable * @param asset The address of the collateral * @param owner The owner of the position * @return boolean value, whether a position is liquidatable **/ function isLiquidatablePosition( address asset, address owner ) public view returns (bool) { uint usdValue_q112 = getCollateralUsdValue_q112(asset, owner); return _isLiquidatablePosition(asset, owner, usdValue_q112); } /** * @dev Calculates current utilization ratio * @param asset The address of the collateral * @param owner The owner of the position * @return utilization ratio **/ function utilizationRatio( address asset, address owner ) public view returns (uint) { uint debt = vault.getTotalDebt(asset, owner); if (debt == 0) return 0; uint usdValue_q112 = getCollateralUsdValue_q112(asset, owner); return debt.mul(100).mul(Q112).div(usdValue_q112); } } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2021 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; import "../interfaces/IVault.sol"; import '../interfaces/IVaultParameters.sol'; import "../interfaces/IOracleRegistry.sol"; import "../interfaces/ICDPRegistry.sol"; import '../interfaces/IToken.sol'; import "../interfaces/vault-managers/parameters/IVaultManagerParameters.sol"; import "../interfaces/vault-managers/parameters/IVaultManagerBorrowFeeParameters.sol"; import "../helpers/ReentrancyGuard.sol"; import '../helpers/TransferHelper.sol'; import "../helpers/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title BaseCDPManager * @dev all common logic should be moved here in future **/ abstract contract BaseCDPManager is ReentrancyGuard { using SafeMath for uint; IVault public immutable vault; IVaultManagerParameters public immutable vaultManagerParameters; IOracleRegistry public immutable oracleRegistry; ICDPRegistry public immutable cdpRegistry; IVaultManagerBorrowFeeParameters public immutable vaultManagerBorrowFeeParameters; IERC20 public immutable usdp; uint public constant Q112 = 2 ** 112; uint public constant DENOMINATOR_1E5 = 1e5; /** * @dev Trigger when joins are happened **/ event Join(address indexed asset, address indexed owner, uint main, uint usdp); /** * @dev Trigger when exits are happened **/ event Exit(address indexed asset, address indexed owner, uint main, uint usdp); /** * @dev Trigger when liquidations are initiated **/ event LiquidationTriggered(address indexed asset, address indexed owner); modifier checkpoint(address asset, address owner) { _; cdpRegistry.checkpoint(asset, owner); } /** * @param _vaultManagerParameters The address of the contract with Vault manager parameters * @param _oracleRegistry The address of the oracle registry * @param _cdpRegistry The address of the CDP registry * @param _vaultManagerBorrowFeeParameters The address of the vault manager borrow fee parameters **/ constructor(address _vaultManagerParameters, address _oracleRegistry, address _cdpRegistry, address _vaultManagerBorrowFeeParameters) { require( _vaultManagerParameters != address(0) && _oracleRegistry != address(0) && _cdpRegistry != address(0) && _vaultManagerBorrowFeeParameters != address(0), "Unit Protocol: INVALID_ARGS" ); vaultManagerParameters = IVaultManagerParameters(_vaultManagerParameters); IVault vaultLocal = IVault(IVaultParameters(IVaultManagerParameters(_vaultManagerParameters).vaultParameters()).vault()); vault = vaultLocal; oracleRegistry = IOracleRegistry(_oracleRegistry); cdpRegistry = ICDPRegistry(_cdpRegistry); vaultManagerBorrowFeeParameters = IVaultManagerBorrowFeeParameters(_vaultManagerBorrowFeeParameters); usdp = IERC20(vaultLocal.usdp()); } /** * @notice Charge borrow fee if needed */ function _chargeBorrowFee(address asset, address user, uint usdpAmount) internal { uint borrowFee = vaultManagerBorrowFeeParameters.calcBorrowFeeAmount(asset, usdpAmount); if (borrowFee == 0) { // very small amount case return; } // to fail with concrete reason, not with TRANSFER_FROM_FAILED from safeTransferFrom require(usdp.allowance(user, address(this)) >= borrowFee, "Unit Protocol: BORROW_FEE_NOT_APPROVED"); TransferHelper.safeTransferFrom( address(usdp), user, vaultManagerBorrowFeeParameters.feeReceiver(), borrowFee ); } // decreases debt function _repay(address asset, address owner, uint usdpAmount) internal { uint fee = vault.calculateFee(asset, owner, usdpAmount); vault.chargeFee(vault.usdp(), owner, fee); // burn USDP from the owner's balance uint debtAfter = vault.repay(asset, owner, usdpAmount); if (debtAfter == 0) { // clear unused storage vault.destroy(asset, owner); } } /** * @dev Calculates liquidation price * @param asset The address of the collateral * @param owner The owner of the position * @return Q112-encoded liquidation price **/ function liquidationPrice_q112( address asset, address owner ) external view returns (uint) { uint debt = vault.getTotalDebt(asset, owner); if (debt == 0) return uint(-1); uint collateralLiqPrice = debt.mul(100).mul(Q112).div(vaultManagerParameters.liquidationRatio(asset)); require(IToken(asset).decimals() <= 18, "Unit Protocol: NOT_SUPPORTED_DECIMALS"); return collateralLiqPrice / vault.collaterals(asset, owner) / 10 ** (18 - IToken(asset).decimals()); } function _calcPrincipal(address asset, address owner, uint repayment) internal view returns (uint) { uint fee = vault.stabilityFee(asset, owner) * (block.timestamp - vault.lastUpdate(asset, owner)) / 365 days; return repayment * DENOMINATOR_1E5 / (DENOMINATOR_1E5 + fee); } /** * @dev Determines whether a position is liquidatable * @param asset The address of the collateral * @param owner The owner of the position * @param usdValue_q112 Q112-encoded USD value of the collateral * @return boolean value, whether a position is liquidatable **/ function _isLiquidatablePosition( address asset, address owner, uint usdValue_q112 ) internal view returns (bool) { uint debt = vault.getTotalDebt(asset, owner); // position is collateralized if there is no debt if (debt == 0) return false; return debt.mul(100).mul(Q112).div(usdValue_q112) >= vaultManagerParameters.liquidationRatio(asset); } } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; pragma abicoder v2; interface IOracleRegistry { struct Oracle { uint oracleType; address oracleAddress; } function WETH ( ) external view returns ( address ); function getKeydonixOracleTypes ( ) external view returns ( uint256[] memory ); function getOracles ( ) external view returns ( Oracle[] memory foundOracles ); function keydonixOracleTypes ( uint256 ) external view returns ( uint256 ); function maxOracleType ( ) external view returns ( uint256 ); function oracleByAsset ( address asset ) external view returns ( address ); function oracleByType ( uint256 ) external view returns ( address ); function oracleTypeByAsset ( address ) external view returns ( uint256 ); function oracleTypeByOracle ( address ) external view returns ( uint256 ); function setKeydonixOracleTypes ( uint256[] memory _keydonixOracleTypes ) external; function setOracle ( uint256 oracleType, address oracle ) external; function setOracleTypeForAsset ( address asset, uint256 oracleType ) external; function setOracleTypeForAssets ( address[] memory assets, uint256 oracleType ) external; function unsetOracle ( uint256 oracleType ) external; function unsetOracleForAsset ( address asset ) external; function unsetOracleForAssets ( address[] memory assets ) external; function vaultParameters ( ) external view returns ( address ); } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; interface IOracleUsd { // returns Q112-encoded value // returned value 10**18 * 2**112 is $1 function assetToUsd(address asset, uint amount) external view returns (uint); } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function withdraw(uint) external; } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; interface IVault { function DENOMINATOR_1E2 ( ) external view returns ( uint256 ); function DENOMINATOR_1E5 ( ) external view returns ( uint256 ); function borrow ( address asset, address user, uint256 amount ) external returns ( uint256 ); function calculateFee ( address asset, address user, uint256 amount ) external view returns ( uint256 ); function changeOracleType ( address asset, address user, uint256 newOracleType ) external; function chargeFee ( address asset, address user, uint256 amount ) external; function col ( ) external view returns ( address ); function colToken ( address, address ) external view returns ( uint256 ); function collaterals ( address, address ) external view returns ( uint256 ); function debts ( address, address ) external view returns ( uint256 ); function depositCol ( address asset, address user, uint256 amount ) external; function depositEth ( address user ) external payable; function depositMain ( address asset, address user, uint256 amount ) external; function destroy ( address asset, address user ) external; function getTotalDebt ( address asset, address user ) external view returns ( uint256 ); function lastUpdate ( address, address ) external view returns ( uint256 ); function liquidate ( address asset, address positionOwner, uint256 mainAssetToLiquidator, uint256 colToLiquidator, uint256 mainAssetToPositionOwner, uint256 colToPositionOwner, uint256 repayment, uint256 penalty, address liquidator ) external; function liquidationBlock ( address, address ) external view returns ( uint256 ); function liquidationFee ( address, address ) external view returns ( uint256 ); function liquidationPrice ( address, address ) external view returns ( uint256 ); function oracleType ( address, address ) external view returns ( uint256 ); function repay ( address asset, address user, uint256 amount ) external returns ( uint256 ); function spawn ( address asset, address user, uint256 _oracleType ) external; function stabilityFee ( address, address ) external view returns ( uint256 ); function tokenDebts ( address ) external view returns ( uint256 ); function triggerLiquidation ( address asset, address positionOwner, uint256 initialPrice ) external; function update ( address asset, address user ) external; function usdp ( ) external view returns ( address ); function vaultParameters ( ) external view returns ( address ); function weth ( ) external view returns ( address payable ); function withdrawCol ( address asset, address user, uint256 amount ) external; function withdrawEth ( address user, uint256 amount ) external; function withdrawMain ( address asset, address user, uint256 amount ) external; } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; interface ICDPRegistry { struct CDP { address asset; address owner; } function batchCheckpoint ( address[] calldata assets, address[] calldata owners ) external; function batchCheckpointForAsset ( address asset, address[] calldata owners ) external; function checkpoint ( address asset, address owner ) external; function cr ( ) external view returns ( address ); function getAllCdps ( ) external view returns ( CDP[] memory r ); function getCdpsByCollateral ( address asset ) external view returns ( CDP[] memory cdps ); function getCdpsByOwner ( address owner ) external view returns ( CDP[] memory r ); function getCdpsCount ( ) external view returns ( uint256 totalCdpCount ); function getCdpsCountForCollateral ( address asset ) external view returns ( uint256 ); function isAlive ( address asset, address owner ) external view returns ( bool ); function isListed ( address asset, address owner ) external view returns ( bool ); function vault ( ) external view returns ( address ); } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; interface IVaultManagerParameters { function devaluationPeriod ( address ) external view returns ( uint256 ); function initialCollateralRatio ( address ) external view returns ( uint256 ); function liquidationDiscount ( address ) external view returns ( uint256 ); function liquidationRatio ( address ) external view returns ( uint256 ); function maxColPercent ( address ) external view returns ( uint256 ); function minColPercent ( address ) external view returns ( uint256 ); function setColPartRange ( address asset, uint256 min, uint256 max ) external; function setCollateral ( address asset, uint256 stabilityFeeValue, uint256 liquidationFeeValue, uint256 initialCollateralRatioValue, uint256 liquidationRatioValue, uint256 liquidationDiscountValue, uint256 devaluationPeriodValue, uint256 usdpLimit, uint256[] calldata oracles, uint256 minColP, uint256 maxColP ) external; function setDevaluationPeriod ( address asset, uint256 newValue ) external; function setInitialCollateralRatio ( address asset, uint256 newValue ) external; function setLiquidationDiscount ( address asset, uint256 newValue ) external; function setLiquidationRatio ( address asset, uint256 newValue ) external; function vaultParameters ( ) external view returns ( address ); } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; interface IVaultParameters { function canModifyVault ( address ) external view returns ( bool ); function foundation ( ) external view returns ( address ); function isManager ( address ) external view returns ( bool ); function isOracleTypeEnabled ( uint256, address ) external view returns ( bool ); function liquidationFee ( address ) external view returns ( uint256 ); function setCollateral ( address asset, uint256 stabilityFeeValue, uint256 liquidationFeeValue, uint256 usdpLimit, uint256[] calldata oracles ) external; function setFoundation ( address newFoundation ) external; function setLiquidationFee ( address asset, uint256 newValue ) external; function setManager ( address who, bool permit ) external; function setOracleType ( uint256 _type, address asset, bool enabled ) external; function setStabilityFee ( address asset, uint256 newValue ) external; function setTokenDebtLimit ( address asset, uint256 limit ) external; function setVaultAccess ( address who, bool permit ) external; function stabilityFee ( address ) external view returns ( uint256 ); function tokenDebtLimit ( address ) external view returns ( uint256 ); function vault ( ) external view returns ( address ); function vaultParameters ( ) external view returns ( address ); } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; interface IToken { function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity 0.7.6; /** * @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 () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; /** * @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) { require(b != 0, "SafeMath: division by zero"); 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; } } // SPDX-License-Identifier: bsl-1.1 /* Copyright 2021 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity ^0.7.6; interface IVaultManagerBorrowFeeParameters { /** * @notice 1 = 100% = 10000 basis points **/ function BASIS_POINTS_IN_1() external view returns (uint); /** * @notice Borrow fee receiver **/ function feeReceiver() external view returns (address); /** * @notice Sets the borrow fee receiver. Only manager is able to call this function * @param newFeeReceiver The address of fee receiver **/ function setFeeReceiver(address newFeeReceiver) external; /** * @notice Sets the base borrow fee in basis points (1bp = 0.01% = 0.0001). Only manager is able to call this function * @param newBaseBorrowFeeBasisPoints The borrow fee in basis points **/ function setBaseBorrowFee(uint16 newBaseBorrowFeeBasisPoints) external; /** * @notice Sets the borrow fee for a particular collateral in basis points (1bp = 0.01% = 0.0001). Only manager is able to call this function * @param asset The address of the main collateral token * @param newEnabled Is custom fee enabled for asset * @param newFeeBasisPoints The borrow fee in basis points **/ function setAssetBorrowFee(address asset, bool newEnabled, uint16 newFeeBasisPoints) external; /** * @notice Returns borrow fee for particular collateral in basis points (1bp = 0.01% = 0.0001) * @param asset The address of the main collateral token * @return feeBasisPoints The borrow fee in basis points **/ function getBorrowFee(address asset) external view returns (uint16 feeBasisPoints); /** * @notice Returns borrow fee for usdp amount for particular collateral * @param asset The address of the main collateral token * @return The borrow fee **/ function calcBorrowFeeAmount(address asset, uint usdpAmount) external view returns (uint); } // SPDX-License-Identifier: GPL-3.0-or-later /* Copyright 2020 Unit Protocol: Artem Zakharov ([email protected]). */ pragma solidity 0.7.6; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // 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); }
* @notice Withdraws WETH and converts to ETH @param ethAmount ETH amount to withdraw @param usdpAmount The amount of USDP token to repay/
function exit_Eth(uint ethAmount, uint usdpAmount) public returns (uint) { usdpAmount = exit(WETH, ethAmount, usdpAmount); require(IWETH(WETH).transferFrom(msg.sender, address(this), ethAmount), "Unit Protocol: WETH_TRANSFER_FROM_FAILED"); IWETH(WETH).withdraw(ethAmount); require(success, "Unit Protocol: ETH_TRANSFER_FAILED"); return usdpAmount; }
2,505,551
[ 1, 1190, 9446, 87, 678, 1584, 44, 471, 7759, 358, 512, 2455, 225, 13750, 6275, 512, 2455, 3844, 358, 598, 9446, 225, 584, 9295, 6275, 1021, 3844, 434, 11836, 8640, 1147, 358, 2071, 528, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2427, 67, 41, 451, 12, 11890, 13750, 6275, 16, 2254, 584, 9295, 6275, 13, 1071, 1135, 261, 11890, 13, 288, 203, 3639, 584, 9295, 6275, 273, 2427, 12, 59, 1584, 44, 16, 13750, 6275, 16, 584, 9295, 6275, 1769, 203, 3639, 2583, 12, 45, 59, 1584, 44, 12, 59, 1584, 44, 2934, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 13750, 6275, 3631, 315, 2802, 4547, 30, 678, 1584, 44, 67, 16596, 6553, 67, 11249, 67, 11965, 8863, 203, 3639, 467, 59, 1584, 44, 12, 59, 1584, 44, 2934, 1918, 9446, 12, 546, 6275, 1769, 203, 3639, 2583, 12, 4768, 16, 315, 2802, 4547, 30, 512, 2455, 67, 16596, 6553, 67, 11965, 8863, 203, 3639, 327, 584, 9295, 6275, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; import "./Ownable.sol"; import "./DOSOnChainSDK.sol"; // A user contract asks anything from off-chain world through a url. contract TestUserContract is Ownable, DOSOnChainSDK { string public response; // query_id -> valid_status mapping(uint => bool) private _valid; // Default timeout in seconds: Two blocks. uint public timeout = 14 * 2; string public lastQueriedUrl; string public lastQueriedSelector; event SetTimeout(uint previousTimeout, uint newTimeout); event QueryResponseReady(uint queryId, string result); event RequestSent(bool succ, uint requestId); constructor(address addr) DOSOnChainSDK(addr) public {} modifier auth(uint id) { require(msg.sender == fromDOSProxyContract(), "Unauthenticated response from non-DOS."); require(_valid[id], "Response with invalid request id!"); _; } function setTimeout(uint newTimeout) public onlyOwner { emit SetTimeout(timeout, newTimeout); timeout = newTimeout; } // Ask me anything (AMA) off-chain through an api/url. function AMA(string memory url, string memory selector) public { lastQueriedUrl = url; lastQueriedSelector = selector; uint id = DOSQuery(timeout, url, selector); if (id != 0x0) { _valid[id] = true; emit RequestSent(true, id); } else { revert("Invalid query id."); } } // User-defined callback function handling query response. function __callback__(uint queryId, bytes memory result) public auth(queryId) { response = string(result); emit QueryResponseReady(queryId, response); delete _valid[queryId]; } }
Ask me anything (AMA) off-chain through an api/url.
function AMA(string memory url, string memory selector) public { lastQueriedUrl = url; lastQueriedSelector = selector; uint id = DOSQuery(timeout, url, selector); if (id != 0x0) { _valid[id] = true; emit RequestSent(true, id); revert("Invalid query id."); } }
12,633,696
[ 1, 23663, 1791, 6967, 261, 2192, 37, 13, 3397, 17, 5639, 3059, 392, 1536, 19, 718, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 432, 5535, 12, 1080, 3778, 880, 16, 533, 3778, 3451, 13, 1071, 288, 203, 3639, 1142, 928, 264, 2092, 1489, 273, 880, 31, 203, 3639, 1142, 928, 264, 2092, 4320, 273, 3451, 31, 203, 3639, 2254, 612, 273, 463, 4618, 1138, 12, 4538, 16, 880, 16, 3451, 1769, 203, 3639, 309, 261, 350, 480, 374, 92, 20, 13, 288, 203, 5411, 389, 877, 63, 350, 65, 273, 638, 31, 203, 5411, 3626, 1567, 7828, 12, 3767, 16, 612, 1769, 203, 5411, 15226, 2932, 1941, 843, 612, 1199, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x60e1712167206eeffb073202AA5ed0a0d13de4c6/sources/Sandwich.sol
Authorized transfer(address,uint256) swap(uint256,uint256,address,bytes) Contructor sets the only user
contract Sandwich { using SafeTransfer for IERC20; address internal immutable user; bytes4 internal constant ERC20_TRANSFER_ID = 0xa9059cbb; bytes4 internal constant PAIR_SWAP_ID = 0x022c0d9f; receive() external payable {} constructor(address _owner) { user = _owner; } function recoverERC20(address token) public { require(msg.sender == user, "shoo"); IERC20(token).safeTransfer( msg.sender, IERC20(token).balanceOf(address(this)) ); } Fallback function where you do your frontslice and backslice NO UNCLE BLOCK PROTECTION IN PLACE, USE AT YOUR OWN RISK Payload structure (abi encodePacked) - token: address - Address of the token you're swapping - pair: address - Univ2 pair you're sandwiching on - amountIn: uint128 - Amount you're giving via swap - amountOut: uint128 - Amount you're receiving via swap - tokenOutNo: uint8 - Is the token you're giving token0 or token1? (On univ2 pair) Note: This fallback function generates some dangling bits fallback() external payable { address memUser = user; assembly { if iszero(eq(caller(), memUser)) { revert(3, 3) } let s1 := call(sub(gas(), 5000), token, 0, 0x7c, 0x44, 0, 0) if iszero(s1) { revert(3, 3) } tokenOutNo == 0 ? amountOut : 0, tokenOutNo == 1 ? amountOut : 0, address(this), new bytes(0) ) case 0 { mstore(0x80, amountOut) mstore(0xa0, 0) } case 1 { mstore(0x80, 0) mstore(0xa0, amountOut) } let s2 := call(sub(gas(), 5000), pair, 0, 0x7c, 0xa4, 0, 0) if iszero(s2) { revert(3, 3) } } } Fallback function where you do your frontslice and backslice NO UNCLE BLOCK PROTECTION IN PLACE, USE AT YOUR OWN RISK Payload structure (abi encodePacked) - token: address - Address of the token you're swapping - pair: address - Univ2 pair you're sandwiching on - amountIn: uint128 - Amount you're giving via swap - amountOut: uint128 - Amount you're receiving via swap - tokenOutNo: uint8 - Is the token you're giving token0 or token1? (On univ2 pair) Note: This fallback function generates some dangling bits fallback() external payable { address memUser = user; assembly { if iszero(eq(caller(), memUser)) { revert(3, 3) } let s1 := call(sub(gas(), 5000), token, 0, 0x7c, 0x44, 0, 0) if iszero(s1) { revert(3, 3) } tokenOutNo == 0 ? amountOut : 0, tokenOutNo == 1 ? amountOut : 0, address(this), new bytes(0) ) case 0 { mstore(0x80, amountOut) mstore(0xa0, 0) } case 1 { mstore(0x80, 0) mstore(0xa0, amountOut) } let s2 := call(sub(gas(), 5000), pair, 0, 0x7c, 0xa4, 0, 0) if iszero(s2) { revert(3, 3) } } } Fallback function where you do your frontslice and backslice NO UNCLE BLOCK PROTECTION IN PLACE, USE AT YOUR OWN RISK Payload structure (abi encodePacked) - token: address - Address of the token you're swapping - pair: address - Univ2 pair you're sandwiching on - amountIn: uint128 - Amount you're giving via swap - amountOut: uint128 - Amount you're receiving via swap - tokenOutNo: uint8 - Is the token you're giving token0 or token1? (On univ2 pair) Note: This fallback function generates some dangling bits fallback() external payable { address memUser = user; assembly { if iszero(eq(caller(), memUser)) { revert(3, 3) } let s1 := call(sub(gas(), 5000), token, 0, 0x7c, 0x44, 0, 0) if iszero(s1) { revert(3, 3) } tokenOutNo == 0 ? amountOut : 0, tokenOutNo == 1 ? amountOut : 0, address(this), new bytes(0) ) case 0 { mstore(0x80, amountOut) mstore(0xa0, 0) } case 1 { mstore(0x80, 0) mstore(0xa0, amountOut) } let s2 := call(sub(gas(), 5000), pair, 0, 0x7c, 0xa4, 0, 0) if iszero(s2) { revert(3, 3) } } } let token := shr(96, calldataload(0x00)) let pair := shr(96, calldataload(0x14)) let amountIn := shr(128, calldataload(0x28)) let amountOut := shr(128, calldataload(0x38)) let tokenOutNo := shr(248, calldataload(0x48)) mstore(0x7c, ERC20_TRANSFER_ID) mstore(0x80, pair) mstore(0xa0, amountIn) Fallback function where you do your frontslice and backslice NO UNCLE BLOCK PROTECTION IN PLACE, USE AT YOUR OWN RISK Payload structure (abi encodePacked) - token: address - Address of the token you're swapping - pair: address - Univ2 pair you're sandwiching on - amountIn: uint128 - Amount you're giving via swap - amountOut: uint128 - Amount you're receiving via swap - tokenOutNo: uint8 - Is the token you're giving token0 or token1? (On univ2 pair) Note: This fallback function generates some dangling bits fallback() external payable { address memUser = user; assembly { if iszero(eq(caller(), memUser)) { revert(3, 3) } let s1 := call(sub(gas(), 5000), token, 0, 0x7c, 0x44, 0, 0) if iszero(s1) { revert(3, 3) } tokenOutNo == 0 ? amountOut : 0, tokenOutNo == 1 ? amountOut : 0, address(this), new bytes(0) ) case 0 { mstore(0x80, amountOut) mstore(0xa0, 0) } case 1 { mstore(0x80, 0) mstore(0xa0, amountOut) } let s2 := call(sub(gas(), 5000), pair, 0, 0x7c, 0xa4, 0, 0) if iszero(s2) { revert(3, 3) } } } calls pair.swap( mstore(0x7c, PAIR_SWAP_ID) switch tokenOutNo Fallback function where you do your frontslice and backslice NO UNCLE BLOCK PROTECTION IN PLACE, USE AT YOUR OWN RISK Payload structure (abi encodePacked) - token: address - Address of the token you're swapping - pair: address - Univ2 pair you're sandwiching on - amountIn: uint128 - Amount you're giving via swap - amountOut: uint128 - Amount you're receiving via swap - tokenOutNo: uint8 - Is the token you're giving token0 or token1? (On univ2 pair) Note: This fallback function generates some dangling bits fallback() external payable { address memUser = user; assembly { if iszero(eq(caller(), memUser)) { revert(3, 3) } let s1 := call(sub(gas(), 5000), token, 0, 0x7c, 0x44, 0, 0) if iszero(s1) { revert(3, 3) } tokenOutNo == 0 ? amountOut : 0, tokenOutNo == 1 ? amountOut : 0, address(this), new bytes(0) ) case 0 { mstore(0x80, amountOut) mstore(0xa0, 0) } case 1 { mstore(0x80, 0) mstore(0xa0, amountOut) } let s2 := call(sub(gas(), 5000), pair, 0, 0x7c, 0xa4, 0, 0) if iszero(s2) { revert(3, 3) } } } Fallback function where you do your frontslice and backslice NO UNCLE BLOCK PROTECTION IN PLACE, USE AT YOUR OWN RISK Payload structure (abi encodePacked) - token: address - Address of the token you're swapping - pair: address - Univ2 pair you're sandwiching on - amountIn: uint128 - Amount you're giving via swap - amountOut: uint128 - Amount you're receiving via swap - tokenOutNo: uint8 - Is the token you're giving token0 or token1? (On univ2 pair) Note: This fallback function generates some dangling bits fallback() external payable { address memUser = user; assembly { if iszero(eq(caller(), memUser)) { revert(3, 3) } let s1 := call(sub(gas(), 5000), token, 0, 0x7c, 0x44, 0, 0) if iszero(s1) { revert(3, 3) } tokenOutNo == 0 ? amountOut : 0, tokenOutNo == 1 ? amountOut : 0, address(this), new bytes(0) ) case 0 { mstore(0x80, amountOut) mstore(0xa0, 0) } case 1 { mstore(0x80, 0) mstore(0xa0, amountOut) } let s2 := call(sub(gas(), 5000), pair, 0, 0x7c, 0xa4, 0, 0) if iszero(s2) { revert(3, 3) } } } mstore(0xc0, address()) mstore(0xe0, 0x80) Fallback function where you do your frontslice and backslice NO UNCLE BLOCK PROTECTION IN PLACE, USE AT YOUR OWN RISK Payload structure (abi encodePacked) - token: address - Address of the token you're swapping - pair: address - Univ2 pair you're sandwiching on - amountIn: uint128 - Amount you're giving via swap - amountOut: uint128 - Amount you're receiving via swap - tokenOutNo: uint8 - Is the token you're giving token0 or token1? (On univ2 pair) Note: This fallback function generates some dangling bits fallback() external payable { address memUser = user; assembly { if iszero(eq(caller(), memUser)) { revert(3, 3) } let s1 := call(sub(gas(), 5000), token, 0, 0x7c, 0x44, 0, 0) if iszero(s1) { revert(3, 3) } tokenOutNo == 0 ? amountOut : 0, tokenOutNo == 1 ? amountOut : 0, address(this), new bytes(0) ) case 0 { mstore(0x80, amountOut) mstore(0xa0, 0) } case 1 { mstore(0x80, 0) mstore(0xa0, amountOut) } let s2 := call(sub(gas(), 5000), pair, 0, 0x7c, 0xa4, 0, 0) if iszero(s2) { revert(3, 3) } } } }
1,858,676
[ 1, 15341, 7412, 12, 2867, 16, 11890, 5034, 13, 7720, 12, 11890, 5034, 16, 11890, 5034, 16, 2867, 16, 3890, 13, 735, 8813, 280, 1678, 326, 1338, 729, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 348, 464, 91, 1354, 288, 203, 565, 1450, 14060, 5912, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 1758, 2713, 11732, 729, 31, 203, 203, 565, 1731, 24, 2713, 5381, 4232, 39, 3462, 67, 16596, 6553, 67, 734, 273, 374, 6995, 9349, 6162, 7358, 70, 31, 203, 203, 565, 1731, 24, 2713, 5381, 15662, 7937, 67, 18746, 2203, 67, 734, 273, 374, 92, 3103, 22, 71, 20, 72, 29, 74, 31, 203, 203, 203, 203, 565, 6798, 1435, 3903, 8843, 429, 2618, 203, 565, 3885, 12, 2867, 389, 8443, 13, 288, 203, 3639, 729, 273, 389, 8443, 31, 203, 565, 289, 203, 203, 565, 445, 5910, 654, 39, 3462, 12, 2867, 1147, 13, 1071, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 729, 16, 315, 674, 5161, 8863, 203, 3639, 467, 654, 39, 3462, 12, 2316, 2934, 4626, 5912, 12, 203, 5411, 1234, 18, 15330, 16, 203, 5411, 467, 654, 39, 3462, 12, 2316, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 203, 3639, 11272, 203, 565, 289, 203, 203, 3639, 21725, 445, 1625, 1846, 741, 3433, 6641, 6665, 471, 1473, 6665, 203, 203, 3639, 3741, 5019, 23181, 14073, 4629, 1448, 3106, 2120, 25564, 1441, 16, 14988, 14464, 1624, 51, 1099, 531, 5665, 534, 5127, 47, 203, 203, 3639, 11320, 3695, 261, 21457, 2017, 4420, 329, 13, 203, 203, 3639, 300, 1147, 30, 1758, 3639, 300, 5267, 434, 326, 1147, 1846, 4565, 7720, 1382, 203, 3639, 300, 3082, 30, 1758, 540, 300, 1351, 427, 22, 3082, 1846, 4565, 272, 464, 91, 2 ]
./partial_match/3/0x88bd63A066aE3749cf3E93DA41589B72e69eF025/sources/CTCA.sol
***************************** EXTERNAL FUNCTIONS (ERC20 INTERFACE) ****************************/
function name() public view returns (string memory){ return _name; }
5,113,076
[ 1, 2294, 11702, 13690, 55, 261, 654, 39, 3462, 11391, 11300, 13, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 508, 1435, 1071, 1476, 1135, 261, 1080, 3778, 15329, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x1e958A0526B9F52a34e8D3930941B661784f242e/sources/browser/illustCustody2.sol
get percentage for token
uint256 remainingPayment=royaltyPrice-tokenPrice;
3,874,472
[ 1, 588, 11622, 364, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 4463, 6032, 33, 3800, 15006, 5147, 17, 2316, 5147, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /* * * Blockonix Tokens are governed by the Terms & Conditions separately notified to each existing token holder * of Bitindia, and available on https://blockonix.com and https://blockonix.com/tokenswap * */ /** * Standard Interface for ERC20 Contract */ contract IERC20 { function totalSupply() public constant returns (uint _totalSupply); function balanceOf(address _owner) public constant returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) constant public returns (uint remaining); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } /** * Checking overflows for various operations */ library SafeMathLib { /** * Issue: Change to internal pure **/ function minus(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } /** * Issue: Change to internal pure **/ function plus(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } } /** * @title Ownable * @notice 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; /** * @notice The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @notice Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @notice Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); owner = newOwner; } } contract HasAddresses { address founder1FirstLockup = 0xfC866793142059C79E924d537C26E5E68a3d0CB4; address founder1SecondLockup = 0xa5c5EdA285866a89fbe9434BF85BC7249Fa98D45; address founder1ThirdLockup = 0xBE2D892D27309EE50D53aa3460fB21A2762625d6; address founder2FirstLockup = 0x7aeFB5F308C60D6fD9f9D79D6BEb32e2BbEf8F3C; address founder2SecondLockup = 0x9d92785510fadcBA9D0372e96882441536d6876a; address founder2ThirdLockup = 0x0e0B9943Ea00393B596089631D520bF1489d4d2E; address founder3FirstLockup = 0x8E06EdC382Dd2Bf3F2C36f7e2261Af2c7Eb84835; address founder3SecondLockup = 0x6A5AebCd6fA054ff4D10c51bABce17F189A9998a; address founder3ThirdLockup = 0xe10E613Be00a6383Dde52152Bc33007E5669e861; } contract VestingPeriods{ uint firstLockup = 1544486400; // Human time (GMT): Tuesday, 11 December 2018 00:00:00 uint secondLockup = 1560211200; // Human time (GMT): Tuesday, 11 June 2019 00:00:00 uint thirdLockup = 1576022400; // Human time (GMT): Wednesday, 11 December 2019 00:00:00 } contract Vestable { mapping(address => uint) vestedAddresses ; // Addresses vested till date bool isVestingOver = false; event AddVestingAddress(address vestingAddress, uint maturityTimestamp); function addVestingAddress(address vestingAddress, uint maturityTimestamp) internal{ vestedAddresses[vestingAddress] = maturityTimestamp; emit AddVestingAddress(vestingAddress, maturityTimestamp); } function checkVestingTimestamp(address testAddress) public view returns(uint){ return vestedAddresses[testAddress]; } function checkVestingCondition(address sender) internal view returns(bool) { uint vestingTimestamp = vestedAddresses[sender]; if(vestingTimestamp > 0) { return (now > vestingTimestamp); } else { return true; } } } contract IsUpgradable{ address oldTokenAddress = 0x420335D3DEeF2D5b87524Ff9D0fB441F71EA621f; uint upgradeDeadline = 1543536000; address oldTokenBurnAddress = 0x30E055F7C16B753dbF77B57f38782C11A9f1C653; IERC20 oldToken = IERC20(oldTokenAddress); } /** * @title BlockonixToken Token * @notice The ERC20 Token. */ contract BlockonixToken is IERC20, Ownable, Vestable, HasAddresses, VestingPeriods, IsUpgradable { using SafeMathLib for uint256; uint256 public constant totalTokenSupply = 1009208335 * 10**16; // Total Supply:10,092,083.35 uint256 public burntTokens; string public constant name = "Blockonix"; // Blockonix string public constant symbol = "BDT"; // BDT uint8 public constant decimals = 18; mapping (address => uint256) public balances; mapping(address => mapping(address => uint256)) approved; event Upgraded(address _owner, uint256 amount); constructor() public { uint256 lockedTokenPerAddress = 280335648611111000000000; // Total Founder Tokens(LOCKED): 2,523,020.8375, divided equally in 9 chunks balances[founder1FirstLockup] = lockedTokenPerAddress; balances[founder2FirstLockup] = lockedTokenPerAddress; balances[founder3FirstLockup] = lockedTokenPerAddress; balances[founder1SecondLockup] = lockedTokenPerAddress; balances[founder2SecondLockup] = lockedTokenPerAddress; balances[founder3SecondLockup] = lockedTokenPerAddress; balances[founder1ThirdLockup] = lockedTokenPerAddress; balances[founder2ThirdLockup] = lockedTokenPerAddress; balances[founder3ThirdLockup] = lockedTokenPerAddress; emit Transfer(address(this), founder1FirstLockup, lockedTokenPerAddress); emit Transfer(address(this), founder2FirstLockup, lockedTokenPerAddress); emit Transfer(address(this), founder3FirstLockup, lockedTokenPerAddress); emit Transfer(address(this), founder1SecondLockup, lockedTokenPerAddress); emit Transfer(address(this), founder2SecondLockup, lockedTokenPerAddress); emit Transfer(address(this), founder3SecondLockup, lockedTokenPerAddress); emit Transfer(address(this), founder1ThirdLockup, lockedTokenPerAddress); emit Transfer(address(this), founder2ThirdLockup, lockedTokenPerAddress); emit Transfer(address(this), founder3ThirdLockup, lockedTokenPerAddress); addVestingAddress(founder1FirstLockup, firstLockup); addVestingAddress(founder2FirstLockup, firstLockup); addVestingAddress(founder3FirstLockup, firstLockup); addVestingAddress(founder1SecondLockup, secondLockup); addVestingAddress(founder2SecondLockup, secondLockup); addVestingAddress(founder3SecondLockup, secondLockup); addVestingAddress(founder1ThirdLockup, thirdLockup); addVestingAddress(founder2ThirdLockup, thirdLockup); addVestingAddress(founder3ThirdLockup, thirdLockup); } function burn(uint256 _value) public { require (balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] = balances[msg.sender].minus(_value); burntTokens += _value; emit BurnToken(msg.sender, _value); } function totalSupply() view public returns (uint256 _totalSupply) { return totalTokenSupply - burntTokens; } function balanceOf(address _owner) view public returns (uint256 balance) { return balances[_owner]; } /* Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint256 _value) internal { require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead require (balances[_from] >= _value); // Check if the sender has enough require (balances[_to] + _value > balances[_to]); // Check for overflows balances[_from] = balances[_from].minus(_value); // Subtract from the sender balances[_to] = balances[_to].plus(_value); // Add the same to the recipient emit Transfer(_from, _to, _value); } /** * @notice 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 returns (bool success){ require(checkVestingCondition(msg.sender)); _transfer(msg.sender, _to, _value); return true; } /** * @notice Send `_value` tokens to `_to` on behalf of `_from` * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(checkVestingCondition(_from)); require (_value <= approved[_from][msg.sender]); // Check allowance approved[_from][msg.sender] = approved[_from][msg.sender].minus(_value); _transfer(_from, _to, _value); return true; } /** * @notice Approve `_value` tokens for `_spender` * @param _spender The address of the sender * @param _value the amount to send */ function approve(address _spender, uint256 _value) public returns (bool success) { require(checkVestingCondition(_spender)); if(balances[msg.sender] >= _value) { approved[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } return false; } /** * @notice Check `_value` tokens allowed to `_spender` by `_owner` * @param _owner The address of the Owner * @param _spender The address of the Spender */ function allowance(address _owner, address _spender) view public returns (uint256 remaining) { return approved[_owner][_spender]; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event BurnToken(address _owner, uint256 _value); /** * Upgrade function, requires the owner to first approve tokens equal to their old token balance to this address * */ function upgrade() external { require(now <=upgradeDeadline); uint256 balance = oldToken.balanceOf(msg.sender); require(balance>0); oldToken.transferFrom(msg.sender, oldTokenBurnAddress, balance); balances[msg.sender] += balance; emit Transfer(this, msg.sender, balance); emit Upgraded(msg.sender, balance); } }
* @notice Send `_value` tokens to `_to` on behalf of `_from` @param _from The address of the sender @param _to The address of the recipient @param _value the amount to send/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(checkVestingCondition(_from)); approved[_from][msg.sender] = approved[_from][msg.sender].minus(_value); _transfer(_from, _to, _value); return true; }
6,597,606
[ 1, 3826, 1375, 67, 1132, 68, 2430, 358, 1375, 67, 869, 68, 603, 12433, 6186, 434, 1375, 67, 2080, 68, 225, 389, 2080, 1021, 1758, 434, 326, 5793, 225, 389, 869, 1021, 1758, 434, 326, 8027, 225, 389, 1132, 326, 3844, 358, 1366, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2583, 12, 1893, 58, 10100, 3418, 24899, 2080, 10019, 203, 3639, 20412, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 273, 20412, 63, 67, 2080, 6362, 3576, 18, 15330, 8009, 19601, 24899, 1132, 1769, 203, 3639, 389, 13866, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// Abstract contract for the full ERC 20 Token standard //@ create by m-chain jerry pragma solidity ^0.4.8; contract Token { uint256 public totalSupply; 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); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /* You should inherit from StandardToken or, for a token like you would want to deploy in something like Mist, see WalStandardToken.sol. (This implements ONLY the standard functions and NOTHING else. If you deploy this, you won&#39;t have anything useful.) Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20 .*/ contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { //Default assumes totalSupply can&#39;t be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn&#39;t wrap. //Replace the if with this one instead. //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[msg.sender] >= _value && free_balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; free_balances[msg.sender] -= _value; balances[_to] += _value; free_balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[_from] >= _value && free_balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; free_balances[_to] += _value; balances[_from] -= _value; free_balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function freeBalancesOf(address _owner) constant returns (uint256 free_balance) { return free_balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => uint256) free_balances; mapping (address => mapping (address => uint256)) allowed; } contract tan_lian is StandardToken { /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. string public symbol; //An identifier: eg SBX address owner = msg.sender; function tan_lian() { balances[msg.sender] = 50000000000000000; // Give the creator all initial tokens free_balances[msg.sender] = 50000000000000000; totalSupply = 50000000000000000; // Update total supply name = "tan lian"; // Set the name for display purposes decimals = 8; // Amount of decimals for display purposes symbol = "CBN"; // Set the symbol for display purposes } function transferFreeze(address _to, uint256 _value) returns (bool success) { //Default assumes totalSupply can&#39;t be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn&#39;t wrap. //Replace the if with this one instead. //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (balances[msg.sender] >= _value && _value > 0 && owner == msg.sender) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFree(address _to, uint256 _value) returns (bool success) { //Default assumes totalSupply can&#39;t be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn&#39;t wrap. //Replace the if with this one instead. //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { if (free_balances[msg.sender] >= _value && _value > 0 && owner == msg.sender) { free_balances[msg.sender] -= _value; free_balances[_to] += _value; return true; } else { return false; } } }
Set the name for display purposes
name = "tan lian";
10,655,728
[ 1, 694, 326, 508, 364, 2562, 13694, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 508, 273, 315, 88, 304, 328, 2779, 14432, 4766, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xB0caA67c712D96809f2aBAF2c95369EF942CE8Cb/sources/contracts/pendle/contracts/interfaces/IPVotingEscrowMainchain.sol
============= ACTIONS =============
interface IPVotingEscrowMainchain is IPVeToken { event NewLockPosition(address indexed user, uint128 amount, uint128 expiry); event Withdraw(address indexed user, uint128 amount); event BroadcastTotalSupply(VeBalance newTotalSupply, uint256[] chainIds); event BroadcastUserPosition(address indexed user, uint256[] chainIds); function increaseLockPosition(uint128 additionalAmountToLock, uint128 expiry) external returns (uint128); function withdraw() external returns (uint128); function totalSupplyAt(uint128 timestamp) external view returns (uint128); function getUserHistoryLength(address user) external view returns (uint256); function getUserHistoryAt(address user, uint256 index) external view returns (Checkpoint memory); }
16,556,886
[ 1, 14468, 33, 11385, 55, 422, 1432, 12275, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 30618, 17128, 6412, 492, 6376, 5639, 353, 30618, 73, 1345, 288, 203, 565, 871, 1166, 2531, 2555, 12, 2867, 8808, 729, 16, 2254, 10392, 3844, 16, 2254, 10392, 10839, 1769, 203, 203, 565, 871, 3423, 9446, 12, 2867, 8808, 729, 16, 2254, 10392, 3844, 1769, 203, 203, 565, 871, 19687, 5269, 3088, 1283, 12, 58, 73, 13937, 394, 5269, 3088, 1283, 16, 2254, 5034, 8526, 2687, 2673, 1769, 203, 203, 565, 871, 19687, 1299, 2555, 12, 2867, 8808, 729, 16, 2254, 5034, 8526, 2687, 2673, 1769, 203, 203, 203, 565, 445, 10929, 2531, 2555, 12, 11890, 10392, 3312, 6275, 774, 2531, 16, 2254, 10392, 10839, 13, 203, 3639, 3903, 203, 3639, 1135, 261, 11890, 10392, 1769, 203, 203, 565, 445, 598, 9446, 1435, 3903, 1135, 261, 11890, 10392, 1769, 203, 203, 565, 445, 2078, 3088, 1283, 861, 12, 11890, 10392, 2858, 13, 3903, 1476, 1135, 261, 11890, 10392, 1769, 203, 203, 565, 445, 4735, 5623, 1782, 12, 2867, 729, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 4735, 5623, 861, 12, 2867, 729, 16, 2254, 5034, 770, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 14431, 3778, 1769, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x677885afde857b70f40741ff8B60F9aFbA95Dd49/sources/contracts/pendle/contracts/core/StandardizedYield/implementations/BalancerStable/base/PendleAuraBalancerStableLPSYV2.sol
//*/ @notice allows owner to add new reward tokens in in case Aura does so with their pools
function _getImmutablePoolData() internal view virtual returns (bytes memory); REWARDS-RELATED function addRewardTokens(address token) external virtual onlyOwner { if (token == BAL_TOKEN || token == AURA_TOKEN || extraRewards.contains(token)) revert Errors.SYInvalidRewardToken(token); uint256 nRewardsAura = IRewards(auraRewardManager).extraRewardsLength(); for (uint256 i = 0; i < nRewardsAura; i++) { if (token == IRewards(IRewards(auraRewardManager).extraRewards(i)).rewardToken()) { extraRewards.push(token); return; } } revert Errors.SYInvalidRewardToken(token); }
3,214,110
[ 1, 28111, 225, 5360, 3410, 358, 527, 394, 19890, 2430, 316, 316, 648, 432, 21401, 1552, 1427, 598, 3675, 16000, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 588, 16014, 2864, 751, 1435, 2713, 1476, 5024, 1135, 261, 3890, 3778, 1769, 203, 203, 1171, 9079, 2438, 16777, 3948, 17, 15868, 6344, 203, 203, 565, 445, 527, 17631, 1060, 5157, 12, 2867, 1147, 13, 3903, 5024, 1338, 5541, 288, 203, 3639, 309, 261, 2316, 422, 605, 1013, 67, 8412, 747, 1147, 422, 432, 1099, 37, 67, 8412, 747, 2870, 17631, 14727, 18, 12298, 12, 2316, 3719, 203, 5411, 15226, 9372, 18, 7474, 1941, 17631, 1060, 1345, 12, 2316, 1769, 203, 203, 3639, 2254, 5034, 290, 17631, 14727, 37, 21401, 273, 15908, 359, 14727, 12, 69, 21401, 17631, 1060, 1318, 2934, 7763, 17631, 14727, 1782, 5621, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 290, 17631, 14727, 37, 21401, 31, 277, 27245, 288, 203, 5411, 309, 261, 2316, 422, 15908, 359, 14727, 12, 7937, 359, 14727, 12, 69, 21401, 17631, 1060, 1318, 2934, 7763, 17631, 14727, 12, 77, 13, 2934, 266, 2913, 1345, 10756, 288, 203, 7734, 2870, 17631, 14727, 18, 6206, 12, 2316, 1769, 203, 7734, 327, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 15226, 9372, 18, 7474, 1941, 17631, 1060, 1345, 12, 2316, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; /// @title PatientRecords /// @author Nicolas Frega - <[email protected]> /// Allows Medical Record System to maintain records of patients in their network. /// Records can be accessed by Hospitals if and only if patient provides name. /// Patients are rewarded with erc20 tokens for providing their name import "./InterfacePatientRecords.sol"; import "./SpringToken.sol"; import "./TokenDestructible.sol"; import "./SafeMath.sol"; contract PatientRecords is InterfacePatientRecords, TokenDestructible { using SafeMath for uint256; /* * Events */ event Deposit(address indexed sender, uint256 value); event HospitalAddition(address hospital); event HospitalRemoval(address hospital); event PatientAddition(address patient); event PatientRemoval(address patient); event PatientRecordAdded(uint256 recordID, address patientAddress); event NameAddedToRecords(uint256 recordID, address patientAddress); event TokenRewardSet(uint256 tokenReward); event PatientPaid(address patientAddress); /* * Constans */ uint constant public MAX_COUNT = 50; /* * Storage */ SpringToken public springToken; mapping (address => bool) public isPatient; mapping (address => bool) public isHospital; mapping (uint256 => mapping (address => Records)) records; mapping (uint256 => dateRange) dateRanges; mapping (address => mapping (string => uint256)) mappingByName; uint256 public recordCount = 0; uint256 public tokenRewardAmount; address public tokenAddress; struct Records { bool providedName; string name; address patient; address hospital; uint256 admissionDate; uint256 dischargeDate; uint256 visitReason; } struct dateRange { uint256 admissionDate; uint256 dischargeDate; } /* * Modifiers */ modifier validParameters(uint count) { require(count <= MAX_COUNT && count != 0); _; } modifier hospitalDoesNotExist(address hospital) { require(!isHospital[hospital]); _; } modifier hospitalExist(address hospital) { require(isHospital[hospital]); _; } modifier patientDoesNotExist(address patient) { require(!isPatient[patient]); _; } modifier patientExist(address patient) { require(isPatient[patient]); _; } modifier notNull(address _address) { require(_address != 0); _; } modifier notEmpty(string name) { bytes memory tempString = bytes(name); require(tempString.length != 0); _; } modifier onlyPatient(uint256 recordId) { require(records[recordId][msg.sender].patient == msg.sender); _; } modifier onlyHospital(uint256 recordId, address _patientAddress) { require(records[recordId][_patientAddress].hospital == msg.sender); _; } modifier recordExists(uint256 recordId, address patientAddress) { address _hospital = records[recordId][patientAddress].hospital; require(_hospital != 0x0); _; } modifier patientProvidedName(uint256 recordId, address patient) { require(records[recordId][patient].providedName == true); _; } modifier patientNotProvidedName(uint256 recordId, address patient) { require(records[recordId][patient].providedName == false); _; } modifier higherThanZero(uint256 _uint) { require(_uint > 0); _; } /// @dev Fallback function allows to deposit ether. function() public payable { if (msg.value > 0) { emit Deposit(msg.sender, msg.value); } } /* * Public functions */ /// @dev Contract constructor sets initial hospitals and patients. /// @param _hospitals Address array of initial hospitals. /// @param _patients Address array of initial patients constructor(address[] _hospitals, address[] _patients) public validParameters(_hospitals.length) validParameters(_patients.length) { uint i; for (i = 0; i < _hospitals.length; i++) { require(_hospitals[i] != 0x0); isHospital[_hospitals[i]] = true; } for (i = 0; i < _patients.length; i++) { require(!isHospital[_patients[i]]); require(_patients[i] != 0x0); isPatient[_patients[i]] = true; } setSpringToken(new SpringToken()); uint256 initialReward = 1000; setSpringTokenReward(initialReward); } /// @dev Allows to add a new hospital in the network. /// @param _hospital Address of new hospital. function addHospital(address _hospital) public onlyOwner hospitalDoesNotExist(_hospital) patientDoesNotExist(_hospital) notNull(_hospital) { isHospital[_hospital] = true; emit HospitalAddition(_hospital); } /// @dev Allows to remove a hospital in the network. /// @param _hospital Address of hospital to remove. function removeHospital(address _hospital) public onlyOwner hospitalExist(_hospital) { isHospital[_hospital] = false; emit HospitalRemoval(_hospital); } /// @dev Allows to add a new patient in the network. /// @param _patient Address of new patient. function addPatient(address _patient) public onlyOwner patientDoesNotExist(_patient) hospitalDoesNotExist(_patient) notNull(_patient) { isPatient[_patient] = true; emit PatientAddition(_patient); } /// @dev Allows to remove a patient in the network. /// @param _patient Address of patient to remove. function removePatient(address _patient) public onlyOwner patientExist(_patient) { isPatient[_patient] = false; emit PatientRemoval(_patient); } /// @dev Allows to add a patient record in the network. /// @param _patientAddress address of the patient for record. /// @param _hospital address of the hospital for record. /// @param _admissionDate date of admission, simple uint. /// @param _dischargeDate date of discharge, simple uint. /// @param _visitReason internal code for reason for visit. function addRecord ( address _patientAddress, address _hospital, uint256 _admissionDate, uint256 _dischargeDate, uint256 _visitReason) public onlyOwner patientExist(_patientAddress) hospitalExist(_hospital) { records[recordCount][_patientAddress].providedName = false; records[recordCount][_patientAddress].patient = _patientAddress; records[recordCount][_patientAddress].hospital = _hospital; records[recordCount][_patientAddress].admissionDate = _admissionDate; records[recordCount][_patientAddress].dischargeDate = _dischargeDate; records[recordCount][_patientAddress].visitReason = _visitReason; dateRanges[recordCount].admissionDate = _admissionDate; dateRanges[recordCount].dischargeDate = _dischargeDate; emit PatientRecordAdded(recordCount, _patientAddress); recordCount += 1; } /// @dev Allows a patient to add their name to the record in the network. /// @param _recordID ID of the patient specific record. /// @param _name Name for the patient function addName(uint256 _recordID, string _name) public patientExist(msg.sender) onlyPatient(_recordID) recordExists(_recordID, msg.sender) notEmpty(_name) patientNotProvidedName(_recordID, msg.sender) { records[_recordID][msg.sender].providedName = true; records[_recordID][msg.sender].name = _name; address hostpitalInRecord = records[_recordID][msg.sender].hospital; mappingByName[hostpitalInRecord][_name] += 1; payPatient(msg.sender); emit NameAddedToRecords(_recordID, msg.sender); } /// @dev Allows a Hospital to retrieve the record for a patient. /// @param _recordID ID of the patient specific record. /// @param _patientAddress address of the patient for record. function getRecord(uint _recordID, address _patientAddress) public recordExists(_recordID, _patientAddress) patientProvidedName(_recordID, _patientAddress) onlyHospital(_recordID, _patientAddress) view returns ( string _name, address _hospital, uint256 _admissionDate, uint256 _dischargeDate, uint256 _visitReason ) { _name = records[_recordID][_patientAddress].name; _hospital = records[_recordID][_patientAddress].hospital; _admissionDate = records[_recordID][_patientAddress].admissionDate; _dischargeDate = records[_recordID][_patientAddress].dischargeDate; _visitReason = records[_recordID][_patientAddress].visitReason; } /// @dev Allows a Hospital to view the number of records for a patient. /// @param _name Name for the patient function getRecordByName(string _name) public hospitalExist(msg.sender) view returns (uint256 numberOfRecords) { if (mappingByName[msg.sender][_name] != 0) { numberOfRecords = mappingByName[msg.sender][_name]; return numberOfRecords; } else return 0; } /// @dev Allows a Hospital to view the number of patients on a given date range. /// @param from Starting date /// @param to Ending date function getCurrentPatients(uint from, uint to) public hospitalExist(msg.sender) view returns (uint _numberOfPatients) { uint i; _numberOfPatients = 0; for(i = 0; i < recordCount; i++) { if(dateRanges[i].admissionDate >= from && dateRanges[i].dischargeDate <= to) _numberOfPatients += 1; } } /// @dev sets the amount of Spring token rewards for providing name. /// @param _tokenReward Amount of tokens to reward patient. function setSpringTokenReward(uint256 _tokenReward) public onlyOwner higherThanZero(_tokenReward) { tokenRewardAmount = _tokenReward; emit TokenRewardSet(_tokenReward); } /// @dev gets the balance of patient. /// @param _patientAddress address of patient. /// @return Returns patient balance. function getPatientBalance(address _patientAddress) public onlyOwner view returns (uint256) { return springToken.balanceOf(_patientAddress); } /* * Internal functions */ /// @dev sets the patient token reward contract. /// @param _newspringToken Address of patient token. function setSpringToken(address _newspringToken) internal onlyOwner notNull(_newspringToken) { springToken = SpringToken(_newspringToken); tokenAddress = address(springToken); } /// @dev pays a patient for providing their name. /// @param _patientAddress to receive tokens. function payPatient(address _patientAddress) private notNull(_patientAddress) { springToken.transfer(_patientAddress, tokenRewardAmount); emit PatientPaid(_patientAddress); } }
@dev Allows to remove a patient in the network. @param _patient Address of patient to remove.
function removePatient(address _patient) public onlyOwner patientExist(_patient) { isPatient[_patient] = false; emit PatientRemoval(_patient); }
5,404,516
[ 1, 19132, 358, 1206, 279, 18608, 316, 326, 2483, 18, 225, 389, 16330, 1979, 5267, 434, 18608, 358, 1206, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 22834, 1979, 12, 2867, 389, 16330, 1979, 13, 203, 3639, 1071, 203, 3639, 1338, 5541, 203, 3639, 18608, 4786, 24899, 16330, 1979, 13, 203, 565, 288, 203, 3639, 353, 22834, 1979, 63, 67, 16330, 1979, 65, 273, 629, 31, 203, 3639, 3626, 29541, 1979, 24543, 24899, 16330, 1979, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; library SafeMath { function mul(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal 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 returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract OwOWorldToken { using SafeMath for uint256; string public constant symbol = "OWO"; string public constant name = "OwO.World Token"; uint public constant decimals = 18; uint public _owoAmount; uint public _totalSupply = 0; uint public _oneTokenInWei = 108931000000000; // starts at $0.02 bool public _CROWDSALE_PAUSED = false; address public _ownerWallet; // owner wallet address public _multiSigWallet; // The address to hold the funds donated uint public _totalEthCollected = 0; // In wei bool public _saleFinalized = false; // Has OwO Dev finalized the sale? uint constant public dust = 1 finney; // Minimum investment uint public _cap = 50000 ether; // Hard cap to protect the ETH network from a really high raise uint public _capOwO = 100000000 * 10 ** decimals; // total supply of owo for the crowdsale uint public MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE = 25; /* How many distinct addresses have invested */ uint public _investorCount = 0; /* the UNIX timestamp end date of the crowdsale */ uint public _endsAt; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); // Crowdsale end time has been changed event EndsAtChanged(uint endsAt); mapping(address => uint256) balances; mapping(address => mapping(address => uint256)) allowed; mapping (address => uint256) public investedAmountOf; mapping (address => uint256) public tokenAmountOf; function () payable{ createTokens(); } function OwOWorldToken() { _ownerWallet = msg.sender; uint tokenAmount = 500000 * 10 ** decimals; balances[_ownerWallet] = balances[_ownerWallet].add(tokenAmount); _totalSupply = _totalSupply.add(tokenAmount); _multiSigWallet = 0x6c5140f605a9Add003B3626Aae4f08F41E6c6FfF; _endsAt = 1514332800; } modifier onlyOwner(){ require(msg.sender == _ownerWallet); _; } function setOneTokenInWei(uint w) onlyOwner { _oneTokenInWei = w; changed(msg.sender); } function setMultiSigWallet(address w) onlyOwner { require(w != 0 && _investorCount < MAX_INVESTMENTS_BEFORE_MULTISIG_CHANGE ); _multiSigWallet = w; changed(msg.sender); } function setEndsAt(uint time) onlyOwner { require(now < time); _endsAt = time; EndsAtChanged(_endsAt); } function setPause(bool w) onlyOwner{ _CROWDSALE_PAUSED = w; changed(msg.sender); } function setFinalized(bool w) onlyOwner{ _saleFinalized = w; changed(msg.sender); if(_saleFinalized == true){ withdraw(); } } function getMultiSigWallet() constant returns (address){ return _multiSigWallet; } function getMultiSigBalance() constant returns (uint){ return balances[_multiSigWallet]; } function getTotalSupply() constant returns (uint){ return _totalSupply; } function getTotalEth() constant returns (uint){ return _totalEthCollected; } function getTotalPlayers() constant returns (uint){ return _investorCount; } function createTokens() payable{ require( msg.value > 0 && _totalSupply < _capOwO && _CROWDSALE_PAUSED ==false && _saleFinalized == false && now < _endsAt ); //priced at $0.03 if(_totalSupply >500001 && _totalSupply<1000000 && _oneTokenInWei<135714800000000){ _oneTokenInWei = 135714800000000; } //priced at $0.04 if(_totalSupply >1000001 && _totalSupply<2000000 && _oneTokenInWei<180953100000000){ _oneTokenInWei = 180953100000000; } //priced at $0.05 if(_totalSupply>2000001 && _totalSupply<4000000 && _oneTokenInWei<226191400000000){ _oneTokenInWei = 226191400000000; } //priced at $0.06 if(_totalSupply>4000001 && _totalSupply<6000000 && _oneTokenInWei<271429700000000){ _oneTokenInWei = 271429700000000; } //priced at $0.07 if(_totalSupply>6000001 && _totalSupply<8000000 && _oneTokenInWei<316667900000000){ _oneTokenInWei = 316667900000000; } //priced at $0.08 if(_totalSupply>8000001 && _totalSupply<10000001 && _oneTokenInWei<361906200000000){ _oneTokenInWei = 361906200000000; } if(investedAmountOf[msg.sender] == 0) { // A new investor _investorCount = _investorCount.add(1); } _owoAmount = msg.value.div(_oneTokenInWei); balances[msg.sender] = balances[msg.sender].add(_owoAmount); _totalSupply = _totalSupply.add(_owoAmount); _totalEthCollected = _totalEthCollected.add(msg.value); investedAmountOf[msg.sender] = investedAmountOf[msg.sender].add(msg.value); transfer(_ownerWallet,msg.value); } function balanceOf(address _owner) constant returns(uint256 balance){ return balances[_owner]; } event changed(address a); function transfer(address _to, uint256 _value) returns(bool success){ require( balances[msg.sender] >= _value && _value > 0 ); balances[msg.sender].sub(_value); balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) onlyOwner returns (bool success){ require( allowed[_from][msg.sender] >= _value && balances[_from] >= _value && _value >0 ); balances[_from].sub(_value); balances[_to].add(_value); allowed[_from][msg.sender].sub(_value); Transfer(_from,_to,_value); return true; } function getBlockNumber() constant internal returns (uint) { return block.number; } function withdraw() onlyOwner payable{ assert(_multiSigWallet.send(this.balance)); } }
total supply of owo for the crowdsale
uint public _capOwO = 100000000 * 10 ** decimals;
5,366,176
[ 1, 4963, 14467, 434, 2523, 83, 364, 326, 276, 492, 2377, 5349, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 1071, 389, 5909, 3494, 51, 273, 2130, 9449, 380, 1728, 2826, 15105, 31, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-08-31 */ // SPDX-License-Identifier: UNLICENSED pragma solidity 0.6.8; pragma experimental ABIEncoderV2; interface iERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint); function totalSupply() external view returns (uint); function balanceOf(address account) external view returns (uint); function transfer(address, uint) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function approve(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } interface iBASE { function secondsPerEra() external view returns (uint); // function DAO() external view returns (iDAO); } interface iUTILS { function calcPart(uint bp, uint total) external pure returns (uint part); function calcShare(uint part, uint total, uint amount) external pure returns (uint share); function calcSwapOutput(uint x, uint X, uint Y) external pure returns (uint output); function calcSwapFee(uint x, uint X, uint Y) external pure returns (uint output); function calcStakeUnits(uint a, uint A, uint v, uint S) external pure returns (uint units); // function calcAsymmetricShare(uint s, uint T, uint A) external pure returns (uint share); // function getPoolAge(address token) external view returns(uint age); function getPoolShare(address token, uint units) external view returns(uint baseAmt, uint tokenAmt); function getPoolShareAssym(address token, uint units, bool toBase) external view returns(uint baseAmt, uint tokenAmt, uint outputAmt); function calcValueInBase(address token, uint amount) external view returns (uint value); function calcValueInToken(address token, uint amount) external view returns (uint value); function calcValueInBaseWithPool(address payable pool, uint amount) external view returns (uint value); } interface iDAO { function ROUTER() external view returns(address); function UTILS() external view returns(iUTILS); function FUNDS_CAP() external view returns(uint); } // SafeMath library SafeMath { function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } } contract Pool_Vether is iERC20 { using SafeMath for uint; address public BASE; address public TOKEN; iDAO public DAO; uint public one = 10**18; // ERC-20 Parameters string _name; string _symbol; uint public override decimals; uint public override totalSupply; // ERC-20 Mappings mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint public genesis; uint public baseAmt; uint public tokenAmt; uint public baseAmtStaked; uint public tokenAmtStaked; uint public fees; uint public volume; uint public txCount; // Only Router can execute modifier onlyRouter() { _isRouter(); _; } function _isRouter() internal view { require(msg.sender == _DAO().ROUTER(), "RouterErr"); } function _DAO() internal view returns(iDAO) { return DAO; } constructor (address _base, address _token, iDAO _dao) public payable { BASE = _base; TOKEN = _token; DAO = _dao; string memory poolName = "VetherPoolV1-"; string memory poolSymbol = "VPT1-"; if(block.coinbase == address(0)){ //injected CONTRACT AFFECTED BY MINERS _name = string(abi.encodePacked(poolName, "Ethereum")); _symbol = string(abi.encodePacked(poolSymbol, "ETH")); } else { _name = string(abi.encodePacked(poolName, iERC20(_token).name())); _symbol = string(abi.encodePacked(poolSymbol, iERC20(_token).symbol())); } decimals = 18; genesis = now; } function _checkApprovals() external onlyRouter{ if(block.number == 0){ //injected CONTRACT AFFECTED BY MINERS if(block.coinbase != address(0)){ //injected CONTRACT AFFECTED BY MINERS iERC20(TOKEN).approve(_DAO().ROUTER(), (2**256)-1); } iERC20(BASE).approve(_DAO().ROUTER(), (2**256)-1); } } receive() external payable {} //========================================iERC20=========================================// function name() public view override returns (string memory) { return _name; } function symbol() public view override returns (string memory) { return _symbol; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } // iERC20 Transfer function function transfer(address to, uint value) public override returns (bool success) { __transfer(msg.sender, to, value); return true; } // iERC20 Approve function function approve(address spender, uint256 amount) public virtual override returns (bool) { __approve(msg.sender, spender, amount); return true; } function __approve(address owner, address spender, uint256 amount) internal virtual { _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } // iERC20 TransferFrom function function transferFrom(address from, address to, uint value) public override returns (bool success) { require(value <= _allowances[from][msg.sender], 'AllowanceErr'); _allowances[from][msg.sender] = _allowances[from][msg.sender].sub(value); __transfer(from, to, value); return true; } // Internal transfer function function __transfer(address _from, address _to, uint _value) private { require(_balances[_from] >= _value, 'BalanceErr'); require(_balances[_to] + _value >= _balances[_to], 'BalanceErr'); _balances[_from] =_balances[_from].sub(_value); _balances[_to] += _value; emit Transfer(_from, _to, _value); } // Router can mint function _mint(address account, uint256 amount) external onlyRouter { totalSupply = totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _allowances[account][DAO.ROUTER()] += amount; emit Transfer(address(0), account, amount); } // Burn supply function burn(uint256 amount) public virtual { __burn(msg.sender, amount); } function burnFrom(address from, uint256 value) public virtual { require(value <= _allowances[from][msg.sender], 'AllowanceErr'); _allowances[from][msg.sender] = _allowances[from][msg.sender].sub(value); __burn(from, value); } function __burn(address account, uint256 amount) internal virtual { _balances[account] = _balances[account].sub(amount, "BalanceErr"); totalSupply = totalSupply.sub(amount); emit Transfer(account, address(0), amount); } //==================================================================================// // Extended Asset Functions // TransferTo function function transferTo(address recipient, uint256 amount) public returns (bool) { __transfer(tx.origin, recipient, amount); return true; } // ETH Transfer function function transferETH(address payable to, uint value) public payable onlyRouter returns (bool success) { to.call{value:value}(""); return true; } function sync() public { if (block.coinbase == address(0)) { //injected CONTRACT AFFECTED BY MINERS tokenAmt = address(this).balance; } else { tokenAmt = iERC20(TOKEN).balanceOf(address(this)); } } function add(address token, uint amount) public payable returns (bool success) { if(block.coinbase == BASE){ //injected CONTRACT AFFECTED BY MINERS iERC20(BASE).transferFrom(msg.sender, address(this), amount); baseAmt = baseAmt.add(amount); return true; } else if (block.coinbase == TOKEN){ //injected CONTRACT AFFECTED BY MINERS iERC20(TOKEN).transferFrom(msg.sender, address(this), amount); tokenAmt = tokenAmt.add(amount); return true; } else if (block.coinbase == address(0)){ //injected CONTRACT AFFECTED BY MINERS require((amount == msg.value), "InputErr"); tokenAmt = tokenAmt.add(amount); } else { return false; } } //==================================================================================// // Data Model function _incrementPoolBalances(uint _baseAmt, uint _tokenAmt) external onlyRouter { baseAmt += _baseAmt; tokenAmt += _tokenAmt; baseAmtStaked += _baseAmt; tokenAmtStaked += _tokenAmt; } function _setPoolBalances(uint _baseAmt, uint _tokenAmt, uint _baseAmtStaked, uint _tokenAmtStaked) external onlyRouter { baseAmtStaked = _baseAmtStaked; tokenAmtStaked = _tokenAmtStaked; __setPool(_baseAmt, _tokenAmt); } function _setPoolAmounts(uint _baseAmt, uint _tokenAmt) external onlyRouter { __setPool(_baseAmt, _tokenAmt); } function __setPool(uint _baseAmt, uint _tokenAmt) internal { baseAmt = _baseAmt; tokenAmt = _tokenAmt; } function _decrementPoolBalances(uint _baseAmt, uint _tokenAmt) external onlyRouter { uint _unstakedBase = _DAO().UTILS().calcShare(_baseAmt, baseAmt, baseAmtStaked); uint _unstakedToken = _DAO().UTILS().calcShare(_tokenAmt, tokenAmt, tokenAmtStaked); baseAmtStaked = baseAmtStaked.sub(_unstakedBase); tokenAmtStaked = tokenAmtStaked.sub(_unstakedToken); __decrementPool(_baseAmt, _tokenAmt); } function __decrementPool(uint _baseAmt, uint _tokenAmt) internal { baseAmt = baseAmt.sub(_baseAmt); tokenAmt = tokenAmt.sub(_tokenAmt); } function _addPoolMetrics(uint _volume, uint _fee) external onlyRouter { txCount += 1; volume += _volume; fees += _fee; } } contract Router_Vether { using SafeMath for uint; address public BASE; address public DEPLOYER; iDAO public DAO; // uint256 public currentEra; // uint256 public nextEraTime; // uint256 public reserve; uint public totalStaked; uint public totalVolume; uint public totalFees; uint public unstakeTx; uint public stakeTx; uint public swapTx; address[] public arrayTokens; mapping(address=>address payable) private mapToken_Pool; mapping(address=>bool) public isPool; event NewPool(address token, address pool, uint genesis); event Staked(address member, uint inputBase, uint inputToken, uint unitsIssued); event Unstaked(address member, uint outputBase, uint outputToken, uint unitsClaimed); event Swapped(address tokenFrom, address tokenTo, uint inputAmount, uint transferAmount, uint outputAmount, uint fee, address recipient); // event NewEra(uint256 currentEra, uint256 nextEraTime, uint256 reserve); // Only Deployer can execute modifier onlyDeployer() { require(msg.sender == DEPLOYER, "DeployerErr"); _; } constructor () public payable { BASE = 0x4Ba6dDd7b89ed838FEd25d208D4f644106E34279; DEPLOYER = msg.sender; } receive() external payable { buyTo(msg.value, address(0), msg.sender); } function setGenesisDao(address dao) public onlyDeployer { DAO = iDAO(dao); } function _DAO() internal view returns(iDAO) { return DAO; } function migrateRouterData(address payable oldRouter) public onlyDeployer { totalStaked = Router_Vether(oldRouter).totalStaked(); totalVolume = Router_Vether(oldRouter).totalVolume(); totalFees = Router_Vether(oldRouter).totalFees(); unstakeTx = Router_Vether(oldRouter).unstakeTx(); stakeTx = Router_Vether(oldRouter).stakeTx(); swapTx = Router_Vether(oldRouter).swapTx(); } function migrateTokenData(address payable oldRouter) public onlyDeployer { uint tokenCount = Router_Vether(oldRouter).tokenCount(); for(uint i = 0; i<tokenCount; i++){ address token = Router_Vether(oldRouter).getToken(i); address payable pool = Router_Vether(oldRouter).getPool(token); isPool[pool] = true; arrayTokens.push(token); mapToken_Pool[token] = pool; } } function purgeDeployer() public onlyDeployer { DEPLOYER = address(0); } function createPool(uint inputBase, uint inputToken, address token) public payable returns(address payable pool){ require(getPool(token) == address(0), "CreateErr"); require(token != BASE, "Must not be Base"); require((inputToken > 0 && inputBase > 0), "Must get tokens for both"); Pool_Vether newPool = new Pool_Vether(BASE, token, DAO); pool = payable(address(newPool)); uint _actualInputToken = _handleTransferIn(token, inputToken, pool); uint _actualInputBase = _handleTransferIn(BASE, inputBase, pool); mapToken_Pool[token] = pool; arrayTokens.push(token); isPool[pool] = true; totalStaked += _actualInputBase; stakeTx += 1; uint units = _handleStake(pool, _actualInputBase, _actualInputToken, msg.sender); emit NewPool(token, pool, now); emit Staked(msg.sender, _actualInputBase, _actualInputToken, units); return pool; } //==================================================================================// // Staking functions function stake(uint inputBase, uint inputToken, address token) public payable returns (uint units) { units = stakeForMember(inputBase, inputToken, token, msg.sender); return units; } function stakeForMember(uint inputBase, uint inputToken, address token, address member) public payable returns (uint units) { address payable pool = getPool(token); uint _actualInputToken = _handleTransferIn(token, inputToken, pool); uint _actualInputBase = _handleTransferIn(BASE, inputBase, pool); totalStaked += _actualInputBase; stakeTx += 1; require(totalStaked <= DAO.FUNDS_CAP(), "Must be less than Funds Cap"); units = _handleStake(pool, _actualInputBase, _actualInputToken, member); emit Staked(member, _actualInputBase, _actualInputToken, units); return units; } function _handleStake(address payable pool, uint _baseAmt, uint _tokenAmt, address _member) internal returns (uint _units) { Pool_Vether(pool)._checkApprovals(); uint _S = Pool_Vether(pool).baseAmt().add(_baseAmt); uint _A = Pool_Vether(pool).tokenAmt().add(_tokenAmt); Pool_Vether(pool)._incrementPoolBalances(_baseAmt, _tokenAmt); _units = _DAO().UTILS().calcStakeUnits(_tokenAmt, _A, _baseAmt, _S); Pool_Vether(pool)._mint(_member, _units); return _units; } //==================================================================================// // Unstaking functions // Unstake % for self function unstake(uint basisPoints, address token) public returns (bool success) { require((basisPoints > 0 && basisPoints <= 10000), "InputErr"); uint _units = _DAO().UTILS().calcPart(basisPoints, iERC20(getPool(token)).balanceOf(msg.sender)); unstakeExact(_units, token); return true; } // Unstake an exact qty of units function unstakeExact(uint units, address token) public returns (bool success) { address payable pool = getPool(token); address payable member = msg.sender; (uint _outputBase, uint _outputToken) = _DAO().UTILS().getPoolShare(token, units); totalStaked = totalStaked.sub(_outputBase); unstakeTx += 1; _handleUnstake(pool, units, _outputBase, _outputToken, member); emit Unstaked(member, _outputBase, _outputToken, units); _handleTransferOut(token, _outputToken, pool, member); _handleTransferOut(BASE, _outputBase, pool, member); return true; } // // Unstake % Asymmetrically function unstakeAsymmetric(uint basisPoints, bool toBase, address token) public returns (uint outputAmount){ uint _units = _DAO().UTILS().calcPart(basisPoints, iERC20(getPool(token)).balanceOf(msg.sender)); outputAmount = unstakeExactAsymmetric(_units, toBase, token); return outputAmount; } // Unstake Exact Asymmetrically function unstakeExactAsymmetric(uint units, bool toBase, address token) public returns (uint outputAmount){ address payable pool = getPool(token); require(units < iERC20(pool).totalSupply(), "InputErr"); (uint _outputBase, uint _outputToken, uint _outputAmount) = _DAO().UTILS().getPoolShareAssym(token, units, toBase); totalStaked = totalStaked.sub(_outputBase); unstakeTx += 1; _handleUnstake(pool, units, _outputBase, _outputToken, msg.sender); emit Unstaked(msg.sender, _outputBase, _outputToken, units); _handleTransferOut(token, _outputToken, pool, msg.sender); _handleTransferOut(BASE, _outputBase, pool, msg.sender); return _outputAmount; } function _handleUnstake(address payable pool, uint _units, uint _outputBase, uint _outputToken, address _member) internal returns (bool success) { Pool_Vether(pool)._checkApprovals(); Pool_Vether(pool)._decrementPoolBalances(_outputBase, _outputToken); Pool_Vether(pool).burnFrom(_member, _units); return true; } //==================================================================================// // Universal Swapping Functions function buy(uint amount, address token) public payable returns (uint outputAmount, uint fee){ (outputAmount, fee) = buyTo(amount, token, msg.sender); return (outputAmount, fee); } function buyTo(uint amount, address token, address payable member) public payable returns (uint outputAmount, uint fee) { address payable pool = getPool(token); Pool_Vether(pool)._checkApprovals(); uint _actualAmount = _handleTransferIn(BASE, amount, pool); // uint _minusFee = _getFee(_actualAmount); (outputAmount, fee) = _swapBaseToToken(pool, _actualAmount); // addDividend(pool, outputAmount, fee); totalStaked += _actualAmount; totalVolume += _actualAmount; totalFees += _DAO().UTILS().calcValueInBase(token, fee); swapTx += 1; _handleTransferOut(token, outputAmount, pool, member); emit Swapped(BASE, token, _actualAmount, 0, outputAmount, fee, member); return (outputAmount, fee); } // function _getFee(uint amount) private view returns(uint){ // return amount // } function sell(uint amount, address token) public payable returns (uint outputAmount, uint fee){ (outputAmount, fee) = sellTo(amount, token, msg.sender); return (outputAmount, fee); } function sellTo(uint amount, address token, address payable member) public payable returns (uint outputAmount, uint fee) { address payable pool = getPool(token); Pool_Vether(pool)._checkApprovals(); uint _actualAmount = _handleTransferIn(token, amount, pool); (outputAmount, fee) = _swapTokenToBase(pool, _actualAmount); // addDividend(pool, outputAmount, fee); totalStaked = totalStaked.sub(outputAmount); totalVolume += outputAmount; totalFees += fee; swapTx += 1; _handleTransferOut(BASE, outputAmount, pool, member); emit Swapped(token, BASE, _actualAmount, 0, outputAmount, fee, member); return (outputAmount, fee); } function swap(uint inputAmount, address fromToken, address toToken) public payable returns (uint outputAmount, uint fee) { require(fromToken != toToken, "InputErr"); address payable poolFrom = getPool(fromToken); address payable poolTo = getPool(toToken); Pool_Vether(poolFrom)._checkApprovals(); Pool_Vether(poolTo)._checkApprovals(); uint _actualAmount = _handleTransferIn(fromToken, inputAmount, poolFrom); uint _transferAmount = 0; if(block.coinbase == BASE){ //injected CONTRACT AFFECTED BY MINERS (outputAmount, fee) = _swapBaseToToken(poolFrom, _actualAmount); // Buy to token totalStaked += _actualAmount; totalVolume += _actualAmount; // addDividend(poolFrom, outputAmount, fee); } else if(block.coinbase == BASE) { //injected CONTRACT AFFECTED BY MINERS (outputAmount, fee) = _swapTokenToBase(poolFrom,_actualAmount); // Sell to token totalStaked = totalStaked.sub(outputAmount); totalVolume += outputAmount; // addDividend(poolFrom, outputAmount, fee); } else { (uint _yy, uint _feey) = _swapTokenToBase(poolFrom, _actualAmount); // Sell to BASE uint _actualYY = _handleTransferOver(BASE, poolFrom, poolTo, _yy); totalStaked = totalStaked.add(_actualYY).sub(_actualAmount); totalVolume += _yy; totalFees += _feey; // addDividend(poolFrom, _yy, _feey); (uint _zz, uint _feez) = _swapBaseToToken(poolTo, _actualYY); // Buy to token totalFees += _DAO().UTILS().calcValueInBase(toToken, _feez); // addDividend(poolTo, _zz, _feez); _transferAmount = _actualYY; outputAmount = _zz; fee = _feez + _DAO().UTILS().calcValueInToken(toToken, _feey); } swapTx += 1; _handleTransferOut(toToken, outputAmount, poolTo, msg.sender); emit Swapped(fromToken, toToken, _actualAmount, _transferAmount, outputAmount, fee, msg.sender); return (outputAmount, fee); } function _swapBaseToToken(address payable pool, uint _x) internal returns (uint _y, uint _fee){ uint _X = Pool_Vether(pool).baseAmt(); uint _Y = Pool_Vether(pool).tokenAmt(); _y = _DAO().UTILS().calcSwapOutput(_x, _X, _Y); _fee = _DAO().UTILS().calcSwapFee(_x, _X, _Y); Pool_Vether(pool)._setPoolAmounts(_X.add(_x), _Y.sub(_y)); _updatePoolMetrics(pool, _y+_fee, _fee, false); // _checkEmission(); return (_y, _fee); } function _swapTokenToBase(address payable pool, uint _x) internal returns (uint _y, uint _fee){ uint _X = Pool_Vether(pool).tokenAmt(); uint _Y = Pool_Vether(pool).baseAmt(); _y = _DAO().UTILS().calcSwapOutput(_x, _X, _Y); _fee = _DAO().UTILS().calcSwapFee(_x, _X, _Y); Pool_Vether(pool)._setPoolAmounts(_Y.sub(_y), _X.add(_x)); _updatePoolMetrics(pool, _y+_fee, _fee, true); // _checkEmission(); return (_y, _fee); } function _updatePoolMetrics(address payable pool, uint _txSize, uint _fee, bool _toBase) internal { if(_toBase){ Pool_Vether(pool)._addPoolMetrics(_txSize, _fee); } else { uint _txBase = _DAO().UTILS().calcValueInBaseWithPool(pool, _txSize); uint _feeBase = _DAO().UTILS().calcValueInBaseWithPool(pool, _fee); Pool_Vether(pool)._addPoolMetrics(_txBase, _feeBase); } } //==================================================================================// // Revenue Functions // Every swap, calculate fee, add to reserve // Every era, send reserve to DAO // function _checkEmission() private { // if (now >= nextEraTime) { // If new Era and allowed to emit // currentEra += 1; // Increment Era // nextEraTime = now + iBASE(BASE).secondsPerEra() + 100; // Set next Era time // uint reserve = iERC20(BASE).balanceOf(address(this)); // iERC20(BASE).transfer(address(_DAO()), reserve); // emit NewEra(currentEra, nextEraTime, reserve); // Emit Event // } // } //==================================================================================// // Token Transfer Functions function _handleTransferIn(address _token, uint _amount, address _pool) internal returns(uint actual){ if(block.number > 0) { //injected CONTRACT AFFECTED BY MINERS if(block.coinbase == address(0)){ //injected CONTRACT AFFECTED BY MINERS require((_amount == msg.value), "InputErr"); payable(_pool).call{value:_amount}(""); actual = _amount; } else { uint startBal = iERC20(_token).balanceOf(_pool); iERC20(_token).transferFrom(msg.sender, _pool, _amount); actual = iERC20(_token).balanceOf(_pool).sub(startBal); } } } function _handleTransferOut(address _token, uint _amount, address _pool, address payable _recipient) internal { if(block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS if (block.coinbase == address(0)) { //injected CONTRACT AFFECTED BY MINERS Pool_Vether(payable(_pool)).transferETH(_recipient, _amount); } else { iERC20(_token).transferFrom(_pool, _recipient, _amount); } } } function _handleTransferOver(address _token, address _from, address _to, uint _amount) internal returns(uint actual){ if(block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS uint startBal = iERC20(_token).balanceOf(_to); iERC20(_token).transferFrom(_from, _to, _amount); actual = iERC20(_token).balanceOf(_to).sub(startBal); } } //======================================HELPERS========================================// // Helper Functions function getPool(address token) public view returns(address payable pool){ return mapToken_Pool[token]; } function tokenCount() public view returns(uint){ return arrayTokens.length; } function getToken(uint i) public view returns(address){ return arrayTokens[i]; } }
ETH Transfer function
function transferETH(address payable to, uint value) public payable onlyRouter returns (bool success) { return true; to.call{value:value}(""); }
1,793,920
[ 1, 1584, 44, 12279, 445, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1584, 44, 12, 2867, 8843, 429, 358, 16, 2254, 460, 13, 1071, 8843, 429, 1338, 8259, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 327, 638, 31, 203, 3639, 358, 18, 1991, 95, 1132, 30, 1132, 97, 2932, 8863, 7010, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.15; /** * @title SafeMath * @dev Math operations with safety checks that throw on error * @notice This is a softer (in terms of throws) variant of SafeMath: * https://github.com/OpenZeppelin/openzeppelin-solidity/pull/1121 */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint128 _a, uint128 _b) internal constant returns (uint128 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint128 _a, uint128 _b) internal constant returns (uint128) { // Solidity automatically throws when dividing by 0 // therefore require beforehand avoid throw require(_b > 0); // uint128 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(uint128 _a, uint128 _b) internal constant returns (uint128) { require(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint128 _a, uint128 _b) internal constant returns (uint128 c) { c = _a + _b; require(c >= _a); return c; } } /// @title Contract to bet AION for a number and win randomly when the number of bets is met. /// @author Merunas Grincalaitis /// edited by Kim Codeashian contract Casino { using SafeMath for uint; address owner; // The minimum bet a user has to make to participate in the game uint public minimumBet = 1; // Equal to 1.00 AION // The maximum bet a user has to make to participate in the game uint public maximumBet = 100; // Equal to 100 AION // The total number of bets the users have made uint public numberOfBets; // The maximum amount of bets can be made for each game uint public maxAmountOfBets = 7; // The total amount of AION bet for this current game uint public totalBet; // The total amount of AION paid out (contract paid out) uint public totalPaid; // The number / animal that won the last game uint public lastLuckyAnimal; // The current round number uint public numberRound; // Array of players in each round address[] public players; struct Player { uint amountBet; uint numberSelected; } // The address of the player and => the user info mapping(address => Player) public playerInfo; event AnimalChosen(uint value); event WinnerTransfer(address to, uint value); // Modifier to only allow the execution of functions when the bets are completed modifier onEndGame(){ if(numberOfBets >= maxAmountOfBets) _; } modifier onlyOwner() { require(msg.sender == owner); _; } function Casino(){ owner = msg.sender; } // Make sure contract has balance > maximumBet so // distributePrizes will be able to execute without failure function() public payable {} // refund all tokens back to owner function refund() public onlyOwner { uint totalBalance = this.balance; owner.transfer(totalBalance); } function kill() public { if(msg.sender == owner) selfdestruct(owner); } /// @notice Check if a player exists in the current game /// @param player The address of the player to check /// @return bool Returns true is it exists or false if it doesn't function checkPlayerExists(address player) public constant returns(bool){ for(uint i = 0; i < players.length; i++){ if(players[i] == player) return true; } return false; } /// @notice To bet for a number by sending AION /// @param numberSelected The number that the player wants to bet for. Must be between 1 and 10 both inclusive function bet(uint numberSelected) payable { // Check that the max amount of bets hasn't been met yet require(numberOfBets <= maxAmountOfBets); // Check that the number to bet is within the range require(numberSelected >= 1 && numberSelected <= 10); // Check that the player doesn't exists require(checkPlayerExists(msg.sender) == false); // Check that the amount paid is bigger or equal the minimum bet require(msg.value >= minimumBet); playerInfo[msg.sender].amountBet = msg.value; playerInfo[msg.sender].numberSelected = numberSelected; numberOfBets++; players.push(msg.sender); totalBet += msg.value; if(numberOfBets >= maxAmountOfBets) generateNumberWinner(); } /// @notice Generates a random number between 1 and 10 both inclusive. /// Can only be executed when the game ends. function generateNumberWinner() private onEndGame { uint numberGenerated = block.number % 10 + 1; // This isn't secure lastLuckyAnimal = numberGenerated; distributePrizes(); AnimalChosen(lastLuckyAnimal); } /// @notice Sends the corresponding AION to each winner then deletes all the /// players for the next game and resets the `totalBet` and `numberOfBets` function distributePrizes() private onEndGame { address[100] memory winners; // We have to create a temporary in memory array with fixed size uint count = 0; // Winner count uint winnerBetPool = 0; // Total Winner Bet Pool // Store winners in array, and tally winner bet pool for(uint i = 0; i < players.length; i++){ address playerAddress = players[i]; if(playerInfo[playerAddress].numberSelected == lastLuckyAnimal){ winners[count] = playerAddress; winnerBetPool += playerInfo[playerAddress].amountBet; count++; } } if (count > 0){ for(uint j = 0; j < count; j++){ if(winners[j] != address(0)) // Check that the address in this fixed array is not empty address playerAddressW = winners[j]; // Grab winning addresses uint winnerAIONAmount = SafeMath.div(SafeMath.mul(totalBet, playerInfo[playerAddressW].amountBet), winnerBetPool); winners[j].transfer(winnerAIONAmount); // Calculate winner proportions of the prize pool totalPaid += winnerAIONAmount; // Add to Total Payout WinnerTransfer(winners[j], winnerAIONAmount); } totalBet = 0; // Clear total bets, if no winner - totalBets get rolled over } players.length = 0; // Delete all the players array numberOfBets = 0; // Reset number of bets numberRound++; // Increase Round Number } }
refund all tokens back to owner
function refund() public onlyOwner { uint totalBalance = this.balance; owner.transfer(totalBalance); }
12,656,207
[ 1, 1734, 1074, 777, 2430, 1473, 358, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 16255, 1435, 1071, 1338, 5541, 288, 203, 565, 2254, 2078, 13937, 273, 333, 18, 12296, 31, 203, 565, 3410, 18, 13866, 12, 4963, 13937, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.23; /** * @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 Owned * @author Adria Massanet <[email protected]> * @notice The Owned contract has an owner address, and provides basic * authorization control functions, this simplifies & the implementation of * user permissions; this contract has three work flows for a change in * ownership, the first requires the new owner to validate that they have the * ability to accept ownership, the second allows the ownership to be * directly transferred without requiring acceptance, and the third allows for * the ownership to be removed to allow for decentralization */ contract Owned { address public owner; address public newOwnerCandidate; event OwnershipRequested(address indexed by, address indexed to); event OwnershipTransferred(address indexed from, address indexed to); event OwnershipRemoved(); /** * @dev The constructor sets the `msg.sender` as the`owner` of the contract */ constructor() public { owner = msg.sender; } /** * @dev `owner` is the only address that can call a function with this * modifier */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev In this 1st option for ownership transfer `proposeOwnership()` must * be called first by the current `owner` then `acceptOwnership()` must be * called by the `newOwnerCandidate` * @notice `onlyOwner` Proposes to transfer control of the contract to a * new owner * @param _newOwnerCandidate The address being proposed as the new owner */ function proposeOwnership(address _newOwnerCandidate) external onlyOwner { newOwnerCandidate = _newOwnerCandidate; emit OwnershipRequested(msg.sender, newOwnerCandidate); } /** * @notice Can only be called by the `newOwnerCandidate`, accepts the * transfer of ownership */ function acceptOwnership() external { require(msg.sender == newOwnerCandidate); address oldOwner = owner; owner = newOwnerCandidate; newOwnerCandidate = 0x0; emit OwnershipTransferred(oldOwner, owner); } /** * @dev In this 2nd option for ownership transfer `changeOwnership()` can * be called and it will immediately assign ownership to the `newOwner` * @notice `owner` can step down and assign some other address to this role * @param _newOwner The address of the new owner */ function changeOwnership(address _newOwner) external onlyOwner { require(_newOwner != 0x0); address oldOwner = owner; owner = _newOwner; newOwnerCandidate = 0x0; emit OwnershipTransferred(oldOwner, owner); } /** * @dev In this 3rd option for ownership transfer `removeOwnership()` can * be called and it will immediately assign ownership to the 0x0 address; * it requires a 0xdece be input as a parameter to prevent accidental use * @notice Decentralizes the contract, this operation cannot be undone * @param _dac `0xdac` has to be entered for this function to work */ function removeOwnership(address _dac) external onlyOwner { require(_dac == 0xdac); owner = 0x0; newOwnerCandidate = 0x0; emit OwnershipRemoved(); } } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ interface ERC777TokensRecipient { function tokensReceived( address operator, address from, address to, uint amount, bytes userData, bytes operatorData ) public; } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ interface ERC777TokensSender { function tokensToSend( address operator, address from, address to, uint amount, bytes userData, bytes operatorData ) public; } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ interface ERC777Token { function name() public view returns (string); function symbol() public view returns (string); function totalSupply() public view returns (uint256); function granularity() public view returns (uint256); function balanceOf(address owner) public view returns (uint256); function send(address to, uint256 amount) public; function send(address to, uint256 amount, bytes userData) public; function authorizeOperator(address operator) public; function revokeOperator(address operator) public; function isOperatorFor(address operator, address tokenHolder) public view returns (bool); function operatorSend(address from, address to, uint256 amount, bytes userData, bytes operatorData) public; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes userData, bytes operatorData ); // solhint-disable-next-line separate-by-one-line-in-contract event Minted(address indexed operator, address indexed to, uint256 amount, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes userData, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ interface ERC20Token { function name() public view returns (string); function symbol() public view returns (string); function decimals() public view returns (uint8); function totalSupply() public view returns (uint256); function balanceOf(address owner) public view returns (uint256); function transfer(address to, uint256 amount) public returns (bool); function transferFrom(address from, address to, uint256 amount) public returns (bool); function approve(address spender, uint256 amount) public returns (bool); function allowance(address owner, address spender) public view returns (uint256); // solhint-disable-next-line no-simple-event-func-name event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); } contract ERC820Registry { function getManager(address addr) public view returns(address); function setManager(address addr, address newManager) public; function getInterfaceImplementer(address addr, bytes32 iHash) public constant returns (address); function setInterfaceImplementer(address addr, bytes32 iHash, address implementer) public; } contract ERC820Implementer { ERC820Registry public erc820Registry; constructor(address _registry) public { erc820Registry = ERC820Registry(_registry); } function setInterfaceImplementation(string ifaceLabel, address impl) internal { bytes32 ifaceHash = keccak256(ifaceLabel); erc820Registry.setInterfaceImplementer(this, ifaceHash, impl); } function interfaceAddr(address addr, string ifaceLabel) internal constant returns(address) { bytes32 ifaceHash = keccak256(ifaceLabel); return erc820Registry.getInterfaceImplementer(addr, ifaceHash); } function delegateManagement(address newManager) internal { erc820Registry.setManager(this, newManager); } } /** * @title ERC777 Helper Contract * @author Panos */ contract ERC777Helper is ERC777Token, ERC20Token, ERC820Implementer { using SafeMath for uint256; bool internal mErc20compatible; uint256 internal mGranularity; mapping(address => uint) internal mBalances; /** * @notice Internal function that ensures `_amount` is multiple of the granularity * @param _amount The quantity that want's to be checked */ function requireMultiple(uint256 _amount) internal view { require(_amount.div(mGranularity).mul(mGranularity) == _amount); } /** * @notice Check whether an address is a regular address or not. * @param _addr Address of the contract that has to be checked * @return `true` if `_addr` is a regular address (not a contract) */ function isRegularAddress(address _addr) internal view returns(bool) { if (_addr == 0) { return false; } uint size; assembly { size := extcodesize(_addr) } // solhint-disable-line no-inline-assembly return size == 0; } /** * @notice Helper function actually performing the sending of tokens. * @param _from The address holding the tokens being sent * @param _to The address of the recipient * @param _amount The number of tokens to be sent * @param _userData Data generated by the user to be passed to the recipient * @param _operatorData Data generated by the operator to be passed to the recipient * @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not * implementing `erc777_tokenHolder`. * ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer * functions SHOULD set this parameter to `false`. */ function doSend( address _from, address _to, uint256 _amount, bytes _userData, address _operator, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) require(mBalances[_from] >= _amount); // ensure enough funds mBalances[_from] = mBalances[_from].sub(_amount); mBalances[_to] = mBalances[_to].add(_amount); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); emit Sent(_operator, _from, _to, _amount, _userData, _operatorData); if (mErc20compatible) { emit Transfer(_from, _to, _amount); } } /** * @notice Helper function that checks for ERC777TokensRecipient on the recipient and calls it. * May throw according to `_preventLocking` * @param _from The address holding the tokens being sent * @param _to The address of the recipient * @param _amount The number of tokens to be sent * @param _userData Data generated by the user to be passed to the recipient * @param _operatorData Data generated by the operator to be passed to the recipient * @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not * implementing `ERC777TokensRecipient`. * ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer * functions SHOULD set this parameter to `false`. */ function callRecipient( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData, bool _preventLocking ) internal { address recipientImplementation = interfaceAddr(_to, "ERC777TokensRecipient"); if (recipientImplementation != 0) { ERC777TokensRecipient(recipientImplementation).tokensReceived( _operator, _from, _to, _amount, _userData, _operatorData); } else if (_preventLocking) { require(isRegularAddress(_to)); } } /** * @notice Helper function that checks for ERC777TokensSender on the sender and calls it. * May throw according to `_preventLocking` * @param _from The address holding the tokens being sent * @param _to The address of the recipient * @param _amount The amount of tokens to be sent * @param _userData Data generated by the user to be passed to the recipient * @param _operatorData Data generated by the operator to be passed to the recipient * implementing `ERC777TokensSender`. * ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer * functions SHOULD set this parameter to `false`. */ function callSender( address _operator, address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData ) internal { address senderImplementation = interfaceAddr(_from, "ERC777TokensSender"); if (senderImplementation != 0) { ERC777TokensSender(senderImplementation).tokensToSend( _operator, _from, _to, _amount, _userData, _operatorData); } } } /** * @title ERC20 Compatibility Contract * @author Panos */ contract ERC20TokenCompat is ERC777Helper, Owned { mapping(address => mapping(address => uint256)) private mAllowed; /** * @notice Contract construction */ constructor() public { mErc20compatible = true; setInterfaceImplementation("ERC20Token", this); } /** * @notice This modifier is applied to erc20 obsolete methods that are * implemented only to maintain backwards compatibility. When the erc20 * compatibility is disabled, this methods will fail. */ modifier erc20 () { require(mErc20compatible); _; } /** * @notice Disables the ERC20 interface. This function can only be called * by the owner. */ function disableERC20() public onlyOwner { mErc20compatible = false; setInterfaceImplementation("ERC20Token", 0x0); } /** * @notice Re enables the ERC20 interface. This function can only be called * by the owner. */ function enableERC20() public onlyOwner { mErc20compatible = true; setInterfaceImplementation("ERC20Token", this); } /* * @notice For Backwards compatibility * @return The decimals of the token. Forced to 18 in ERC777. */ function decimals() public erc20 view returns (uint8) {return uint8(18);} /** * @notice ERC20 backwards compatible transfer. * @param _to The address of the recipient * @param _amount The number of tokens to be transferred * @return `true`, if the transfer can't be done, it should fail. */ function transfer(address _to, uint256 _amount) public erc20 returns (bool success) { doSend(msg.sender, _to, _amount, "", msg.sender, "", false); return true; } /** * @notice ERC20 backwards compatible transferFrom. * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The number of tokens to be transferred * @return `true`, if the transfer can't be done, it should fail. */ function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) { require(_amount <= mAllowed[_from][msg.sender]); // Cannot be after doSend because of tokensReceived re-entry mAllowed[_from][msg.sender] = mAllowed[_from][msg.sender].sub(_amount); doSend(_from, _to, _amount, "", msg.sender, "", false); return true; } /** * @notice ERC20 backwards compatible approve. * `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf. * @param _spender The address of the account able to transfer the tokens * @param _amount The number of tokens to be approved for transfer * @return `true`, if the approve can't be done, it should fail. */ function approve(address _spender, uint256 _amount) public erc20 returns (bool success) { mAllowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /** * @notice ERC20 backwards compatible allowance. * This function makes it easy to read the `allowed[]` map * @param _owner The address of the account that owns the token * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens of _owner that _spender is allowed * to spend */ function allowance(address _owner, address _spender) public erc20 view returns (uint256 remaining) { return mAllowed[_owner][_spender]; } } /** * @title ERC777 Standard Contract * @author Panos */ contract ERC777StandardToken is ERC777Helper, Owned { string private mName; string private mSymbol; uint256 private mTotalSupply; mapping(address => mapping(address => bool)) private mAuthorized; /** * @notice Constructor to create a ERC777StandardToken * @param _name Name of the new token * @param _symbol Symbol of the new token. * @param _totalSupply Total tokens issued * @param _granularity Minimum transferable chunk. */ constructor( string _name, string _symbol, uint256 _totalSupply, uint256 _granularity ) public { require(_granularity >= 1); require(_totalSupply > 0); mName = _name; mSymbol = _symbol; mTotalSupply = _totalSupply; mGranularity = _granularity; mBalances[msg.sender] = mTotalSupply; setInterfaceImplementation("ERC777Token", this); } /** * @return the name of the token */ function name() public view returns (string) {return mName;} /** * @return the symbol of the token */ function symbol() public view returns (string) {return mSymbol;} /** * @return the granularity of the token */ function granularity() public view returns (uint256) {return mGranularity;} /** * @return the total supply of the token */ function totalSupply() public view returns (uint256) {return mTotalSupply;} /** * @notice Return the account balance of some account * @param _tokenHolder Address for which the balance is returned * @return the balance of `_tokenAddress`. */ function balanceOf(address _tokenHolder) public view returns (uint256) {return mBalances[_tokenHolder];} /** * @notice Send `_amount` of tokens to address `_to` * @param _to The address of the recipient * @param _amount The number of tokens to be sent */ function send(address _to, uint256 _amount) public { doSend(msg.sender, _to, _amount, "", msg.sender, "", true); } /** * @notice Send `_amount` of tokens to address `_to` passing `_userData` to the recipient * @param _to The address of the recipient * @param _amount The number of tokens to be sent * @param _userData The user supplied data */ function send(address _to, uint256 _amount, bytes _userData) public { doSend(msg.sender, _to, _amount, _userData, msg.sender, "", true); } /** * @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens. * @param _operator The operator that wants to be Authorized */ function authorizeOperator(address _operator) public { require(_operator != msg.sender); mAuthorized[_operator][msg.sender] = true; emit AuthorizedOperator(_operator, msg.sender); } /** * @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens. * @param _operator The operator that wants to be Revoked */ function revokeOperator(address _operator) public { require(_operator != msg.sender); mAuthorized[_operator][msg.sender] = false; emit RevokedOperator(_operator, msg.sender); } /** * @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` address. * @param _operator address to check if it has the right to manage the tokens * @param _tokenHolder address which holds the tokens to be managed * @return `true` if `_operator` is authorized for `_tokenHolder` */ function isOperatorFor(address _operator, address _tokenHolder) public view returns (bool) { return _operator == _tokenHolder || mAuthorized[_operator][_tokenHolder]; } /** * @notice Send `_amount` of tokens on behalf of the address `from` to the address `to`. * @param _from The address holding the tokens being sent * @param _to The address of the recipient * @param _amount The number of tokens to be sent * @param _userData Data generated by the user to be sent to the recipient * @param _operatorData Data generated by the operator to be sent to the recipient */ function operatorSend(address _from, address _to, uint256 _amount, bytes _userData, bytes _operatorData) public { require(isOperatorFor(msg.sender, _from)); doSend(_from, _to, _amount, _userData, msg.sender, _operatorData, true); } } /** * @title ERC20 Multi Transfer Contract * @author Panos */ contract ERC20Multi is ERC20TokenCompat { /** * @dev Transfer the specified amounts of tokens to the specified addresses. * @dev Be aware that there is no check for duplicate recipients. * @param _toAddresses Receiver addresses. * @param _amounts Amounts of tokens that will be transferred. */ function multiPartyTransfer(address[] _toAddresses, uint256[] _amounts) external erc20 { /* Ensures _toAddresses array is less than or equal to 255 */ require(_toAddresses.length <= 255); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_toAddresses.length == _amounts.length); for (uint8 i = 0; i < _toAddresses.length; i++) { transfer(_toAddresses[i], _amounts[i]); } } /** * @dev Transfer the specified amounts of tokens to the specified addresses from authorized balance of sender. * @dev Be aware that there is no check for duplicate recipients. * @param _from The address of the sender * @param _toAddresses The addresses of the recipients (MAX 255) * @param _amounts The amounts of tokens to be transferred */ function multiPartyTransferFrom(address _from, address[] _toAddresses, uint256[] _amounts) external erc20 { /* Ensures _toAddresses array is less than or equal to 255 */ require(_toAddresses.length <= 255); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_toAddresses.length == _amounts.length); for (uint8 i = 0; i < _toAddresses.length; i++) { transferFrom(_from, _toAddresses[i], _amounts[i]); } } } /** * @title ERC777 Multi Transfer Contract * @author Panos */ contract ERC777Multi is ERC777Helper { /** * @dev Transfer the specified amounts of tokens to the specified addresses as `_from`. * @dev Be aware that there is no check for duplicate recipients. * @param _from Address to use as sender * @param _to Receiver addresses. * @param _amounts Amounts of tokens that will be transferred. * @param _userData User supplied data * @param _operatorData Operator supplied data */ function multiOperatorSend(address _from, address[] _to, uint256[] _amounts, bytes _userData, bytes _operatorData) external { /* Ensures _toAddresses array is less than or equal to 255 */ require(_to.length <= 255); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_to.length == _amounts.length); for (uint8 i = 0; i < _to.length; i++) { operatorSend(_from, _to[i], _amounts[i], _userData, _operatorData); } } /** * @dev Transfer the specified amounts of tokens to the specified addresses. * @dev Be aware that there is no check for duplicate recipients. * @param _toAddresses Receiver addresses. * @param _amounts Amounts of tokens that will be transferred. * @param _userData User supplied data */ function multiPartySend(address[] _toAddresses, uint256[] _amounts, bytes _userData) public { /* Ensures _toAddresses array is less than or equal to 255 */ require(_toAddresses.length <= 255); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_toAddresses.length == _amounts.length); for (uint8 i = 0; i < _toAddresses.length; i++) { doSend(msg.sender, _toAddresses[i], _amounts[i], _userData, msg.sender, "", true); } } /** * @dev Transfer the specified amounts of tokens to the specified addresses. * @dev Be aware that there is no check for duplicate recipients. * @param _toAddresses Receiver addresses. * @param _amounts Amounts of tokens that will be transferred. */ function multiPartySend(address[] _toAddresses, uint256[] _amounts) public { /* Ensures _toAddresses array is less than or equal to 255 */ require(_toAddresses.length <= 255); /* Ensures _toAddress and _amounts have the same number of entries. */ require(_toAddresses.length == _amounts.length); for (uint8 i = 0; i < _toAddresses.length; i++) { doSend(msg.sender, _toAddresses[i], _amounts[i], "", msg.sender, "", true); } } } /** * @title Safe Guard Contract * @author Panos */ contract SafeGuard is Owned { event Transaction(address indexed destination, uint value, bytes data); /** * @dev Allows owner to execute a transaction. */ function executeTransaction(address destination, uint value, bytes data) public onlyOwner { require(externalCall(destination, value, data.length, data)); emit Transaction(destination, value, data); } /** * @dev call has been separated into its own function in order to take advantage * of the Solidity's code generator to produce a loop that copies tx.data into memory. */ function externalCall(address destination, uint value, uint dataLength, bytes data) private returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly let x := mload(0x40) // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas, 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; } } /** * @title ERC664 Standard Balances Contract * @author chrisfranko */ contract ERC664Balances is SafeGuard { using SafeMath for uint256; uint256 public totalSupply; event BalanceAdj(address indexed module, address indexed account, uint amount, string polarity); event ModuleSet(address indexed module, bool indexed set); mapping(address => bool) public modules; mapping(address => uint256) public balances; mapping(address => mapping(address => uint256)) public allowed; modifier onlyModule() { require(modules[msg.sender]); _; } /** * @notice Constructor to create ERC664Balances * @param _initialAmount Database initial amount */ constructor(uint256 _initialAmount) public { balances[msg.sender] = _initialAmount; totalSupply = _initialAmount; } /** * @notice Set allowance of `_spender` in behalf of `_sender` at `_value` * @param _sender Owner account * @param _spender Spender account * @param _value Value to approve * @return Operation status */ function setApprove(address _sender, address _spender, uint256 _value) external onlyModule returns (bool) { allowed[_sender][_spender] = _value; return true; } /** * @notice Decrease allowance of `_spender` in behalf of `_from` at `_value` * @param _from Owner account * @param _spender Spender account * @param _value Value to decrease * @return Operation status */ function decApprove(address _from, address _spender, uint _value) external onlyModule returns (bool) { allowed[_from][_spender] = allowed[_from][_spender].sub(_value); return true; } /** * @notice Increase total supply by `_val` * @param _val Value to increase * @return Operation status */ function incTotalSupply(uint _val) external onlyOwner returns (bool) { totalSupply = totalSupply.add(_val); return true; } /** * @notice Decrease total supply by `_val` * @param _val Value to decrease * @return Operation status */ function decTotalSupply(uint _val) external onlyOwner returns (bool) { totalSupply = totalSupply.sub(_val); return true; } /** * @notice Set/Unset `_acct` as an authorized module * @param _acct Module address * @param _set Module set status * @return Operation status */ function setModule(address _acct, bool _set) external onlyOwner returns (bool) { modules[_acct] = _set; emit ModuleSet(_acct, _set); return true; } /** * @notice Get `_acct` balance * @param _acct Target account to get balance. * @return The account balance */ function getBalance(address _acct) external view returns (uint256) { return balances[_acct]; } /** * @notice Get allowance of `_spender` in behalf of `_owner` * @param _owner Owner account * @param _spender Spender account * @return Allowance */ function getAllowance(address _owner, address _spender) external view returns (uint256) { return allowed[_owner][_spender]; } /** * @notice Get if `_acct` is an authorized module * @param _acct Module address * @return Operation status */ function getModule(address _acct) external view returns (bool) { return modules[_acct]; } /** * @notice Get total supply * @return Total supply */ function getTotalSupply() external view returns (uint256) { return totalSupply; } /** * @notice Increment `_acct` balance by `_val` * @param _acct Target account to increment balance. * @param _val Value to increment * @return Operation status */ function incBalance(address _acct, uint _val) public onlyModule returns (bool) { balances[_acct] = balances[_acct].add(_val); emit BalanceAdj(msg.sender, _acct, _val, "+"); return true; } /** * @notice Decrement `_acct` balance by `_val` * @param _acct Target account to decrement balance. * @param _val Value to decrement * @return Operation status */ function decBalance(address _acct, uint _val) public onlyModule returns (bool) { balances[_acct] = balances[_acct].sub(_val); emit BalanceAdj(msg.sender, _acct, _val, "-"); return true; } } /** * @title ERC664 Database Contract * @author Panos */ contract CStore is ERC664Balances, ERC820Implementer { mapping(address => mapping(address => bool)) private mAuthorized; /** * @notice Database construction * @param _totalSupply The total supply of the token * @param _registry The ERC820 Registry Address */ constructor(uint256 _totalSupply, address _registry) public ERC664Balances(_totalSupply) ERC820Implementer(_registry) { setInterfaceImplementation("ERC664Balances", this); } /** * @notice Increase total supply by `_val` * @param _val Value to increase * @return Operation status */ // solhint-disable-next-line no-unused-vars function incTotalSupply(uint _val) external onlyOwner returns (bool) { return false; } /** * @notice Decrease total supply by `_val` * @param _val Value to decrease * @return Operation status */ // solhint-disable-next-line no-unused-vars function decTotalSupply(uint _val) external onlyOwner returns (bool) { return false; } /** * @notice moving `_amount` from `_from` to `_to` * @param _from The sender address * @param _to The receiving address * @param _amount The moving amount * @return bool The move result */ function move(address _from, address _to, uint256 _amount) external onlyModule returns (bool) { balances[_from] = balances[_from].sub(_amount); emit BalanceAdj(msg.sender, _from, _amount, "-"); balances[_to] = balances[_to].add(_amount); emit BalanceAdj(msg.sender, _to, _amount, "+"); return true; } /** * @notice Setting operator `_operator` for `_tokenHolder` * @param _operator The operator to set status * @param _tokenHolder The token holder to set operator * @param _status The operator status * @return bool Status of operation */ function setOperator(address _operator, address _tokenHolder, bool _status) external onlyModule returns (bool) { mAuthorized[_operator][_tokenHolder] = _status; return true; } /** * @notice Getting operator `_operator` for `_tokenHolder` * @param _operator The operator address to get status * @param _tokenHolder The token holder address * @return bool Operator status */ function getOperator(address _operator, address _tokenHolder) external view returns (bool) { return mAuthorized[_operator][_tokenHolder]; } /** * @notice Increment `_acct` balance by `_val` * @param _acct Target account to increment balance. * @param _val Value to increment * @return Operation status */ // solhint-disable-next-line no-unused-vars function incBalance(address _acct, uint _val) public onlyModule returns (bool) { return false; } /** * @notice Decrement `_acct` balance by `_val` * @param _acct Target account to decrement balance. * @param _val Value to decrement * @return Operation status */ // solhint-disable-next-line no-unused-vars function decBalance(address _acct, uint _val) public onlyModule returns (bool) { return false; } } /** * @title ERC777 CALL Contract * @author Panos */ contract CALL is ERC820Implementer, ERC777StandardToken, ERC20TokenCompat, ERC20Multi, ERC777Multi, SafeGuard { using SafeMath for uint256; CStore public balancesDB; /** * @notice Token construction * @param _intRegistry The ERC820 Registry Address * @param _name The name of the token * @param _symbol The symbol of the token * @param _totalSupply The total supply of the token * @param _granularity The granularity of the token * @param _balancesDB The address of balances database */ constructor(address _intRegistry, string _name, string _symbol, uint256 _totalSupply, uint256 _granularity, address _balancesDB) public ERC820Implementer(_intRegistry) ERC777StandardToken(_name, _symbol, _totalSupply, _granularity) { balancesDB = CStore(_balancesDB); setInterfaceImplementation("ERC777CALLToken", this); } /** * @notice change the balances database to `_newDB` * @param _newDB The new balances database address */ function changeBalancesDB(address _newDB) public onlyOwner { balancesDB = CStore(_newDB); } /** * @notice ERC20 backwards compatible transferFrom using backendDB. * @param _from The address holding the tokens being transferred * @param _to The address of the recipient * @param _amount The number of tokens to be transferred * @return `true`, if the transfer can't be done, it should fail. */ function transferFrom(address _from, address _to, uint256 _amount) public erc20 returns (bool success) { uint256 allowance = balancesDB.getAllowance(_from, msg.sender); require(_amount <= allowance); // Cannot be after doSend because of tokensReceived re-entry require(balancesDB.decApprove(_from, msg.sender, _amount)); doSend(_from, _to, _amount, "", msg.sender, "", false); return true; } /** * @notice ERC20 backwards compatible approve. * `msg.sender` approves `_spender` to spend `_amount` tokens on its behalf. * @param _spender The address of the account able to transfer the tokens * @param _amount The number of tokens to be approved for transfer * @return `true`, if the approve can't be done, it should fail. */ function approve(address _spender, uint256 _amount) public erc20 returns (bool success) { require(balancesDB.setApprove(msg.sender, _spender, _amount)); emit Approval(msg.sender, _spender, _amount); return true; } /** * @notice ERC20 backwards compatible allowance. * This function makes it easy to read the `allowed[]` map * @param _owner The address of the account that owns the token * @param _spender The address of the account able to transfer the tokens * @return Amount of remaining tokens of _owner that _spender is allowed * to spend */ function allowance(address _owner, address _spender) public erc20 view returns (uint256 remaining) { return balancesDB.getAllowance(_owner, _spender); } /** * @return the total supply of the token */ function totalSupply() public view returns (uint256) { return balancesDB.getTotalSupply(); } /** * @notice Return the account balance of some account * @param _tokenHolder Address for which the balance is returned * @return the balance of `_tokenAddress`. */ function balanceOf(address _tokenHolder) public view returns (uint256) { return balancesDB.getBalance(_tokenHolder); } /** * @notice Authorize a third party `_operator` to manage (send) `msg.sender`'s tokens at remote database. * @param _operator The operator that wants to be Authorized */ function authorizeOperator(address _operator) public { require(_operator != msg.sender); require(balancesDB.setOperator(_operator, msg.sender, true)); emit AuthorizedOperator(_operator, msg.sender); } /** * @notice Revoke a third party `_operator`'s rights to manage (send) `msg.sender`'s tokens at remote database. * @param _operator The operator that wants to be Revoked */ function revokeOperator(address _operator) public { require(_operator != msg.sender); require(balancesDB.setOperator(_operator, msg.sender, false)); emit RevokedOperator(_operator, msg.sender); } /** * @notice Check whether the `_operator` address is allowed to manage the tokens held by `_tokenHolder` * address at remote database. * @param _operator address to check if it has the right to manage the tokens * @param _tokenHolder address which holds the tokens to be managed * @return `true` if `_operator` is authorized for `_tokenHolder` */ function isOperatorFor(address _operator, address _tokenHolder) public view returns (bool) { return _operator == _tokenHolder || balancesDB.getOperator(_operator, _tokenHolder); } /** * @notice Helper function actually performing the sending of tokens using a backend database. * @param _from The address holding the tokens being sent * @param _to The address of the recipient * @param _amount The number of tokens to be sent * @param _userData Data generated by the user to be passed to the recipient * @param _operatorData Data generated by the operator to be passed to the recipient * @param _preventLocking `true` if you want this function to throw when tokens are sent to a contract not * implementing `erc777_tokenHolder`. * ERC777 native Send functions MUST set this parameter to `true`, and backwards compatible ERC20 transfer * functions SHOULD set this parameter to `false`. */ function doSend( address _from, address _to, uint256 _amount, bytes _userData, address _operator, bytes _operatorData, bool _preventLocking ) internal { requireMultiple(_amount); callSender(_operator, _from, _to, _amount, _userData, _operatorData); require(_to != address(0)); // forbid sending to 0x0 (=burning) // require(mBalances[_from] >= _amount); // ensure enough funds // (Not Required due to SafeMath throw if underflow in database and false check) require(balancesDB.move(_from, _to, _amount)); callRecipient(_operator, _from, _to, _amount, _userData, _operatorData, _preventLocking); emit Sent(_operator, _from, _to, _amount, _userData, _operatorData); if (mErc20compatible) { emit Transfer(_from, _to, _amount); } } }
* @notice Get if `_acct` is an authorized module @param _acct Module address @return Operation status/
function getModule(address _acct) external view returns (bool) { return modules[_acct]; }
1,825,455
[ 1, 967, 309, 1375, 67, 1077, 299, 68, 353, 392, 10799, 1605, 225, 389, 1077, 299, 5924, 1758, 327, 4189, 1267, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 11251, 12, 2867, 389, 1077, 299, 13, 3903, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 4381, 63, 67, 1077, 299, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]